diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..721a117462b96324f6f55b65b3553f00df9edba2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +packages/benchmark/data/longmemeval_oracle.json filter=lfs diff=lfs merge=lfs -text diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3028a71c38fd240500ad0b8ea862a94d1dae141c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,125 @@ +# ============================================================================= +# Engram Benchmark - Hugging Face Spaces +# ============================================================================= +# GPU-enabled container for running LongMemEval benchmarks with L4 GPU. +# Designed for Hugging Face Spaces Docker deployment. +# +# Usage: +# 1. Push this to HF Spaces (engram/benchmark) +# 2. Select L4 GPU hardware ($0.80/hr) +# 3. Access web UI to trigger benchmark runs +# +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Stage 1: Build dependencies +# ----------------------------------------------------------------------------- +FROM node:22-bookworm-slim AS builder + +WORKDIR /app + +# Install build essentials for native modules +RUN apt-get update && apt-get install -y \ + python3 \ + make \ + g++ \ + git \ + && rm -rf /var/lib/apt/lists/* + +# Copy monorepo package files +COPY package*.json ./ +COPY packages/benchmark/package.json packages/benchmark/ +COPY packages/search/package.json packages/search/ +COPY packages/graph/package.json packages/graph/ +COPY packages/storage/package.json packages/storage/ +COPY packages/logger/package.json packages/logger/ +COPY packages/common/package.json packages/common/ +COPY packages/temporal/package.json packages/temporal/ + +# Install all dependencies +RUN npm install --include=dev + +# Copy source code +COPY packages/ packages/ +COPY biome.json ./ + +# ----------------------------------------------------------------------------- +# Stage 2: Runtime image with CUDA support +# ----------------------------------------------------------------------------- +FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04 + +# Install Node.js 22 LTS and system dependencies +RUN apt-get update && apt-get install -y \ + curl \ + ca-certificates \ + wget \ + jq \ + && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ + && apt-get install -y nodejs \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +# Copy built application from builder +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/packages ./packages +COPY --from=builder /app/package*.json ./ + +# Reinstall native modules for the runtime platform +RUN npm install --os=linux --cpu=x64 sharp + +# Model cache directory +ENV HF_HOME=/app/.cache +ENV TRANSFORMERS_CACHE=/app/.cache +ENV XDG_CACHE_HOME=/app/.cache + +# Create cache directory for models (downloaded on first run) +# Skipping model preload during Docker build to avoid build failures +# Models will be cached after first run +RUN mkdir -p /app/.cache + +# Install Qdrant for local vector search +RUN wget -q https://github.com/qdrant/qdrant/releases/download/v1.16.2/qdrant-x86_64-unknown-linux-gnu.tar.gz \ + && tar xzf qdrant-x86_64-unknown-linux-gnu.tar.gz -C /usr/local/bin \ + && rm qdrant-x86_64-unknown-linux-gnu.tar.gz \ + && mkdir -p /app/qdrant-storage + +# Install Redis 7.4+ for FalkorDB (Ubuntu 22.04 has old Redis, install from source) +RUN apt-get update && apt-get install -y \ + libgomp1 \ + build-essential \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /app/falkordb-data \ + && wget -q https://github.com/redis/redis/archive/refs/tags/7.4.2.tar.gz \ + && tar xzf 7.4.2.tar.gz \ + && cd redis-7.4.2 && make -j$(nproc) && make install \ + && cd .. && rm -rf redis-7.4.2 7.4.2.tar.gz + +# Download FalkorDB module (v4.14.10 - latest) +RUN mkdir -p /opt/falkordb \ + && wget -q https://github.com/FalkorDB/FalkorDB/releases/download/v4.14.10/falkordb-x64.so -O /opt/falkordb/falkordb.so \ + && chmod +x /opt/falkordb/falkordb.so + +# Copy HF Space runner script +COPY packages/benchmark/hf-space/run.sh /app/run.sh +RUN chmod +x /app/run.sh + +# Create directories for data and results +RUN mkdir -p /data /results + +# Environment configuration +ENV NODE_ENV=production +ENV BENCHMARK_VERBOSE=true +ENV NODE_OPTIONS="--max-old-space-size=24576" + +# GPU mode with FP16 for L4 +ENV EMBEDDER_DEVICE=cuda +ENV EMBEDDER_DTYPE=fp16 +ENV QDRANT_URL=http://localhost:6333 +ENV FALKORDB_URL=redis://localhost:6379 + +# HF Spaces requires port 7860 +EXPOSE 7860 + +# Run the benchmark server +CMD ["/app/run.sh"] diff --git a/README.md b/README.md index fbc64668e28a3ca88a31c124513b64e190354029..35708755091af9157d466dca31cca3b78b24031d 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,117 @@ --- title: Engram Benchmark -emoji: 🏆 -colorFrom: indigo -colorTo: purple +emoji: 🧠 +colorFrom: purple +colorTo: blue sdk: docker -pinned: false +app_port: 7860 +suggested_hardware: l4x1 +suggested_storage: small --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# Engram LongMemEval Benchmark + +GPU-accelerated benchmark runner for evaluating the Engram memory retrieval system on LongMemEval dataset. + +**Full Engram Stack:** FalkorDB (bitemporal graph) + Qdrant (vectors) running in-container. + +## Hardware + +This Space requires **L4 GPU** ($0.80/hr) for optimal performance: +- 24GB VRAM for embedding models (E5-large, fp16) +- CUDA 12.3 with cuDNN 9 for ONNX Runtime + +## API Endpoints + +| Endpoint | Method | Description | +|----------|--------|-------------| +| `/` | GET | Health check (shows FalkorDB + Qdrant status) | +| `/ingest` | POST | Ingest dataset into FalkorDB + Qdrant | +| `/start` | POST | Start benchmark (requires ingest first) | +| `/status` | GET | Get current status and output | +| `/results` | GET | Download results (when complete) | + +## Usage + +```bash +# Check health +curl https://engram-benchmark.hf.space/ + +# Step 1: Ingest data into FalkorDB (graph) + Qdrant (vectors) +curl -X POST https://engram-benchmark.hf.space/ingest + +# Wait for ingest to complete... +curl https://engram-benchmark.hf.space/status + +# Step 2: Run benchmark with full Engram pipeline +curl -X POST https://engram-benchmark.hf.space/start + +# Check status +curl https://engram-benchmark.hf.space/status + +# Step 3: Download results +curl https://engram-benchmark.hf.space/results > results.jsonl +``` + +## Architecture + +The benchmark runs the **full Engram stack**: + +``` +LongMemEval Dataset + ↓ + FalkorDB (bitemporal graph) + - Session nodes with timestamps + - Turn nodes with content + - Memory nodes for retrieval + ↓ + Qdrant (vector index) + - E5-large embeddings (fp16) + - Hybrid search (dense + sparse) + ↓ + Engram Retrieval Pipeline + - Graph traversal + vector search + - Session-aware hierarchical retrieval + - Temporal query parsing + ↓ + Gemini (answer generation) + ↓ + Results +``` + +## Configuration + +Set these secrets in the Space settings: + +| Secret | Description | +|--------|-------------| +| `GOOGLE_GENERATIVE_AI_API_KEY` | Gemini API key for answer generation | + +## Benchmark Features + +Full Engram pipeline with all optimizations: + +**Retrieval:** +- Dense embeddings (E5-large, 1024d, fp16) +- Sparse embeddings (SPLADE) +- Hybrid search with RRF fusion +- Multi-query expansion +- Session-aware hierarchical retrieval +- Temporal query parsing + +**Reranking:** +- Cross-encoder reranking (accurate tier) +- Deep candidate pool (50 docs) + +**Reading:** +- Chain-of-Note structured reasoning +- Time-aware query expansion + +**Abstention (3-layer):** +- Low retrieval confidence +- NLI answer grounding +- Hedging pattern detection + +## Results + +Results are saved to `/results/benchmark-results.jsonl` and can be downloaded via the `/results` endpoint. diff --git a/biome.json b/biome.json new file mode 100644 index 0000000000000000000000000000000000000000..f44094a7a72c41d6eca05dec315acfdb6a8bc26d --- /dev/null +++ b/biome.json @@ -0,0 +1,85 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.3.8/schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "files": { + "ignoreUnknown": false, + "includes": ["**", "!**/dist", "!**/.next", "!**/node_modules", "!**/coverage", "!**/.turbo"] + }, + "css": { + "linter": { + "enabled": false + } + }, + "formatter": { + "enabled": true, + "indentStyle": "tab", + "indentWidth": 2, + "lineWidth": 100 + }, + "assist": { "actions": { "source": { "organizeImports": "on" } } }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "suspicious": { + "noExplicitAny": "off", + "noArrayIndexKey": "warn" + }, + "a11y": { + "useButtonType": "warn", + "noSvgWithoutTitle": "off", + "noStaticElementInteractions": "off" + }, + "complexity": { + "noUselessConstructor": "warn", + "noBannedTypes": "warn" + }, + "style": { + "noNonNullAssertion": "warn" + }, + "correctness": { + "noUnusedVariables": "warn", + "noUnusedFunctionParameters": "warn", + "noConstructorReturn": "warn" + } + } + }, + "overrides": [ + { + "includes": ["**/*.test.ts", "**/*.test.tsx", "tests/**/*"], + "linter": { + "rules": { + "suspicious": { + "noExplicitAny": "off", + "noArrayIndexKey": "off" + }, + "correctness": { + "noUnusedVariables": "off" + } + } + } + }, + { + "includes": ["scripts/**/*"], + "linter": { + "rules": { + "suspicious": { + "noExplicitAny": "off" + }, + "correctness": { + "noUnusedFunctionParameters": "off" + } + } + } + } + ], + "javascript": { + "formatter": { + "quoteStyle": "double" + } + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..abfffc6d3cda764daa04f60fb4c329a879af96af --- /dev/null +++ b/package-lock.json @@ -0,0 +1,12973 @@ +{ + "name": "engram", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "engram", + "version": "0.0.0", + "workspaces": [ + "apps/*", + "packages/*", + "tooling/*" + ], + "dependencies": { + "@confluentinc/kafka-javascript": "^1.7.0" + }, + "devDependencies": { + "@biomejs/biome": "^2.3.8", + "@engram/events": "*", + "@engram/storage": "*", + "@modelcontextprotocol/sdk": "^1.24.3", + "@qdrant/js-client-rest": "^1.16.2", + "@vitest/coverage-v8": "^3.2.4", + "falkordb": "^6.3.1", + "husky": "^9.1.7", + "jsdom": "^27.3.0", + "patch-package": "^8.0.1", + "pino-pretty": "^13.1.3", + "tsx": "^4.21.0", + "turbo": "^2.6.3", + "typescript": "^5.9.3", + "vitest": "^3.2.3", + "zod": "^4.1.13" + } + }, + "apps/control": { + "name": "control-service", + "version": "0.0.0", + "dependencies": { + "@ai-sdk/xai": "^2.0.39", + "@engram/graph": "*", + "@engram/logger": "*", + "@engram/search": "*", + "@engram/storage": "*", + "@modelcontextprotocol/sdk": "^1.24.3", + "ai": "^5.0.108", + "xstate": "^5.24.0", + "zod": "^3.25.76" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1" + } + }, + "apps/execution": { + "name": "execution-service", + "version": "0.0.0", + "extraneous": true, + "dependencies": { + "@engram/logger": "*", + "@engram/storage": "*", + "@engram/temporal": "*", + "@engram/vfs": "*", + "@modelcontextprotocol/sdk": "^1.24.3", + "zod": "^3.25.76" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1" + } + }, + "apps/ingestion": { + "name": "ingestion-service", + "version": "0.0.0", + "dependencies": { + "@engram/events": "*", + "@engram/logger": "*", + "@engram/parser": "*", + "@engram/storage": "*", + "zod": "^3.25.76" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1" + } + }, + "apps/interface": { + "name": "interface-service", + "version": "0.0.0", + "dependencies": { + "@clerk/nextjs": "^6.36.0", + "@engram/events": "*", + "@engram/graph": "*", + "@engram/logger": "*", + "@engram/search": "*", + "@engram/storage": "*", + "@huggingface/transformers": "^3.8.1", + "@react-three/drei": "^10.7.7", + "@react-three/fiber": "^9.4.2", + "@types/three": "^0.181.0", + "@xyflow/react": "^12.10.0", + "dagre": "^0.8.5", + "graphql": "^16.8.1", + "graphql-yoga": "^5.3.0", + "lucide-react": "^0.556.0", + "next": "^16.0.7", + "next-openapi-gen": "^0.8.9", + "onnxruntime-node": "^1.23.2", + "pino": "^10.1.0", + "pino-pretty": "^13.1.3", + "react": "^19.2.1", + "react-dom": "^19.2.1", + "sharp": "^0.34.5", + "sonic-boom": "^4.2.0", + "swr": "^2.3.7", + "thread-stream": "^4.0.0", + "three": "^0.181.2", + "ws": "^8.18.3", + "zod": "^4.1.13" + }, + "devDependencies": { + "@testing-library/dom": "^10.4.1", + "@testing-library/react": "^16.3.1", + "@types/node": "^24.10.1", + "@types/react": "^19.2.7", + "@types/ws": "^8.18.1", + "typescript": "^5.9.3", + "vitest-websocket-mock": "^0.5.0" + } + }, + "apps/mcp": { + "name": "engram-mcp", + "version": "0.0.0", + "dependencies": { + "@engram/graph": "*", + "@engram/logger": "*", + "@engram/search": "*", + "@engram/storage": "*", + "@hono/node-server": "^1.14.1", + "@modelcontextprotocol/sdk": "^1.24.3", + "hono": "^4.7.10", + "ulid": "^3.0.2", + "zod": "^4.1.13" + }, + "bin": { + "engram-mcp": "dist/index.js" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "apps/memory": { + "name": "memory-service", + "version": "0.0.0", + "dependencies": { + "@engram/graph": "*", + "@engram/logger": "*", + "@engram/storage": "*", + "@modelcontextprotocol/sdk": "^1.24.3", + "zod": "^4.1.13" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1" + } + }, + "apps/search": { + "name": "search-service", + "version": "0.0.0", + "dependencies": { + "@engram/logger": "*", + "@engram/search": "*", + "@engram/storage": "*" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1" + } + }, + "node_modules/@acemir/cssom": { + "version": "0.9.29", + "resolved": "https://registry.npmjs.org/@acemir/cssom/-/cssom-0.9.29.tgz", + "integrity": "sha512-G90x0VW+9nW4dFajtjCoT+NM0scAfH9Mb08IcjgFHYbfiL/lU04dTF9JuVOi3/OH+DJCQdcIseSXkdCB9Ky6JA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ai-sdk/gateway": { + "version": "2.0.18", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "2.0.0", + "@ai-sdk/provider-utils": "3.0.18", + "@vercel/oidc": "3.0.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, + "node_modules/@ai-sdk/google": { + "version": "1.2.22", + "resolved": "https://registry.npmjs.org/@ai-sdk/google/-/google-1.2.22.tgz", + "integrity": "sha512-Ppxu3DIieF1G9pyQ5O1Z646GYR0gkC57YdBqXJ82qvCdhEhZHu0TWhmnOoeIWe2olSbuDeoOY+MfJrW8dzS3Hw==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "@ai-sdk/provider-utils": "2.2.8" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.0.0" + } + }, + "node_modules/@ai-sdk/google/node_modules/@ai-sdk/provider": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz", + "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==", + "license": "Apache-2.0", + "dependencies": { + "json-schema": "^0.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@ai-sdk/google/node_modules/@ai-sdk/provider-utils": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-2.2.8.tgz", + "integrity": "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "nanoid": "^3.3.8", + "secure-json-parse": "^2.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.23.8" + } + }, + "node_modules/@ai-sdk/google/node_modules/secure-json-parse": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", + "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", + "license": "BSD-3-Clause" + }, + "node_modules/@ai-sdk/openai-compatible": { + "version": "1.0.28", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "2.0.0", + "@ai-sdk/provider-utils": "3.0.18" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, + "node_modules/@ai-sdk/provider": { + "version": "2.0.0", + "license": "Apache-2.0", + "dependencies": { + "json-schema": "^0.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@ai-sdk/provider-utils": { + "version": "3.0.18", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "2.0.0", + "@standard-schema/spec": "^1.0.0", + "eventsource-parser": "^3.0.6" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, + "node_modules/@ai-sdk/react": { + "version": "1.2.12", + "resolved": "https://registry.npmjs.org/@ai-sdk/react/-/react-1.2.12.tgz", + "integrity": "sha512-jK1IZZ22evPZoQW3vlkZ7wvjYGYF+tRBKXtrcolduIkQ/m/sOAVcVeVDUDvh1T91xCnWCdUGCPZg2avZ90mv3g==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider-utils": "2.2.8", + "@ai-sdk/ui-utils": "1.2.11", + "swr": "^2.2.5", + "throttleit": "2.1.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "^18 || ^19 || ^19.0.0-rc", + "zod": "^3.23.8" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@ai-sdk/react/node_modules/@ai-sdk/provider": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz", + "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==", + "license": "Apache-2.0", + "dependencies": { + "json-schema": "^0.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@ai-sdk/react/node_modules/@ai-sdk/provider-utils": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-2.2.8.tgz", + "integrity": "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "nanoid": "^3.3.8", + "secure-json-parse": "^2.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.23.8" + } + }, + "node_modules/@ai-sdk/react/node_modules/secure-json-parse": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", + "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", + "license": "BSD-3-Clause" + }, + "node_modules/@ai-sdk/ui-utils": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/@ai-sdk/ui-utils/-/ui-utils-1.2.11.tgz", + "integrity": "sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "@ai-sdk/provider-utils": "2.2.8", + "zod-to-json-schema": "^3.24.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.23.8" + } + }, + "node_modules/@ai-sdk/ui-utils/node_modules/@ai-sdk/provider": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz", + "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==", + "license": "Apache-2.0", + "dependencies": { + "json-schema": "^0.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@ai-sdk/ui-utils/node_modules/@ai-sdk/provider-utils": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-2.2.8.tgz", + "integrity": "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "nanoid": "^3.3.8", + "secure-json-parse": "^2.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.23.8" + } + }, + "node_modules/@ai-sdk/ui-utils/node_modules/secure-json-parse": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", + "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", + "license": "BSD-3-Clause" + }, + "node_modules/@ai-sdk/xai": { + "version": "2.0.39", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/openai-compatible": "1.0.28", + "@ai-sdk/provider": "2.0.0", + "@ai-sdk/provider-utils": "3.0.18" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.52.0.tgz", + "integrity": "sha512-d4c+fg+xy9e46c8+YnrrgIQR45CZlAi7PwdzIfDXDM6ACxEZli1/fxhURsq30ZpMZy6LvSkr41jGq5aF5TD7rQ==", + "license": "MIT", + "optional": true, + "bin": { + "anthropic-ai-sdk": "bin/cli" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-4.1.1.tgz", + "integrity": "sha512-B0Hv6G3gWGMn0xKJ0txEi/jM5iFpT3MfDxmhZFb4W047GvytCf1DHQ1D69W3zHI4yWe2aTZAA0JnbMZ7Xc8DuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.4", + "@csstools/css-color-parser": "^3.1.0", + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4", + "lru-cache": "^11.2.4" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-6.7.6.tgz", + "integrity": "sha512-hBaJER6A9MpdG3WgdlOolHmbOYvSk46y7IQN/1+iqiCuUu6iWdQrs9DGKF8ocqsEqWujWf/V7b7vaDgiUmIvUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.1.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.4" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@babel/code-frame": { + "version": "7.27.1", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.27.1", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator": { + "version": "7.28.5", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.28.4", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.27.2", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/parser": "^7.27.2", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.28.5", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.5", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@biomejs/biome": { + "version": "2.3.8", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-darwin-arm64": "2.3.8", + "@biomejs/cli-darwin-x64": "2.3.8", + "@biomejs/cli-linux-arm64": "2.3.8", + "@biomejs/cli-linux-arm64-musl": "2.3.8", + "@biomejs/cli-linux-x64": "2.3.8", + "@biomejs/cli-linux-x64-musl": "2.3.8", + "@biomejs/cli-win32-arm64": "2.3.8", + "@biomejs/cli-win32-x64": "2.3.8" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.3.8", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.3.8.tgz", + "integrity": "sha512-lUDQ03D7y/qEao7RgdjWVGCu+BLYadhKTm40HkpJIi6kn8LSv5PAwRlew/DmwP4YZ9ke9XXoTIQDO1vAnbRZlA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.3.8.tgz", + "integrity": "sha512-Uo1OJnIkJgSgF+USx970fsM/drtPcQ39I+JO+Fjsaa9ZdCN1oysQmy6oAGbyESlouz+rzEckLTF6DS7cWse95g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.3.8.tgz", + "integrity": "sha512-PShR4mM0sjksUMyxbyPNMxoKFPVF48fU8Qe8Sfx6w6F42verbwRLbz+QiKNiDPRJwUoMG1nPM50OBL3aOnTevA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.3.8.tgz", + "integrity": "sha512-QDPMD5bQz6qOVb3kiBui0zKZXASLo0NIQ9JVJio5RveBEFgDgsvJFUvZIbMbUZT3T00M/1wdzwWXk4GIh0KaAw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.3.8.tgz", + "integrity": "sha512-YGLkqU91r1276uwSjiUD/xaVikdxgV1QpsicT0bIA1TaieM6E5ibMZeSyjQ/izBn4tKQthUSsVZacmoJfa3pDA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.3.8.tgz", + "integrity": "sha512-H4IoCHvL1fXKDrTALeTKMiE7GGWFAraDwBYFquE/L/5r1927Te0mYIGseXi4F+lrrwhSWbSGt5qPFswNoBaCxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.3.8.tgz", + "integrity": "sha512-RguzimPoZWtBapfKhKjcWXBVI91tiSprqdBYu7tWhgN8pKRZhw24rFeNZTNf6UiBfjCYCi9eFQs/JzJZIhuK4w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@clerk/backend": { + "version": "2.26.0", + "license": "MIT", + "dependencies": { + "@clerk/shared": "^3.39.0", + "@clerk/types": "^4.101.6", + "cookie": "1.0.2", + "standardwebhooks": "^1.0.0", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=18.17.0" + } + }, + "node_modules/@clerk/backend/node_modules/cookie": { + "version": "1.0.2", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@clerk/clerk-react": { + "version": "5.58.1", + "license": "MIT", + "dependencies": { + "@clerk/shared": "^3.39.0", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=18.17.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-0", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-0" + } + }, + "node_modules/@clerk/nextjs": { + "version": "6.36.1", + "license": "MIT", + "dependencies": { + "@clerk/backend": "^2.26.0", + "@clerk/clerk-react": "^5.58.1", + "@clerk/shared": "^3.39.0", + "@clerk/types": "^4.101.6", + "server-only": "0.0.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=18.17.0" + }, + "peerDependencies": { + "next": "^13.5.7 || ^14.2.25 || ^15.2.3 || ^16", + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-0", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-0" + } + }, + "node_modules/@clerk/shared": { + "version": "3.39.0", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "csstype": "3.1.3", + "dequal": "2.0.3", + "glob-to-regexp": "0.4.1", + "js-cookie": "3.0.5", + "std-env": "^3.9.0", + "swr": "2.3.4" + }, + "engines": { + "node": ">=18.17.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-0", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/@clerk/shared/node_modules/swr": { + "version": "2.3.4", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3", + "use-sync-external-store": "^1.4.0" + }, + "peerDependencies": { + "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/@clerk/types": { + "version": "4.101.6", + "license": "MIT", + "dependencies": { + "@clerk/shared": "^3.39.0" + }, + "engines": { + "node": ">=18.17.0" + } + }, + "node_modules/@confluentinc/kafka-javascript": { + "version": "1.7.0", + "hasInstallScript": true, + "license": "MIT", + "workspaces": [ + ".", + "schemaregistry", + "schemaregistry-examples" + ], + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.11", + "bindings": "^1.3.1", + "nan": "^2.22.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.0.21", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.0.21.tgz", + "integrity": "sha512-plP8N8zKfEZ26figX4Nvajx8DuzfuRpLTqglQ5d0chfnt35Qt3X+m6ASZ+rG0D0kxe/upDVNwSIVJP5n4FuNfw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "license": "Apache-2.0" + }, + "node_modules/@engram/benchmark": { + "resolved": "packages/benchmark", + "link": true + }, + "node_modules/@engram/common": { + "resolved": "packages/common", + "link": true + }, + "node_modules/@engram/events": { + "resolved": "packages/events", + "link": true + }, + "node_modules/@engram/graph": { + "resolved": "packages/graph", + "link": true + }, + "node_modules/@engram/infra": { + "resolved": "packages/infra", + "link": true + }, + "node_modules/@engram/logger": { + "resolved": "packages/logger", + "link": true + }, + "node_modules/@engram/parser": { + "resolved": "packages/parser", + "link": true + }, + "node_modules/@engram/search": { + "resolved": "packages/search", + "link": true + }, + "node_modules/@engram/storage": { + "resolved": "packages/storage", + "link": true + }, + "node_modules/@engram/temporal": { + "resolved": "packages/temporal", + "link": true + }, + "node_modules/@engram/tsconfig": { + "resolved": "packages/tsconfig", + "link": true + }, + "node_modules/@engram/tuner": { + "resolved": "packages/tuner", + "link": true + }, + "node_modules/@engram/vfs": { + "resolved": "packages/vfs", + "link": true + }, + "node_modules/@envelop/core": { + "version": "5.4.0", + "license": "MIT", + "dependencies": { + "@envelop/instrumentation": "^1.0.0", + "@envelop/types": "^5.2.1", + "@whatwg-node/promise-helpers": "^1.2.4", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@envelop/instrumentation": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@whatwg-node/promise-helpers": "^1.2.1", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@envelop/types": { + "version": "5.2.1", + "license": "MIT", + "dependencies": { + "@whatwg-node/promise-helpers": "^1.0.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.1.tgz", + "integrity": "sha512-HHB50pdsBX6k47S4u5g/CaLjqS3qwaOVE5ILsq64jyzgMhLuCuZ8rGzM9yhsAjfjkbgUPMzZEPa7DAp7yz6vuA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.1.tgz", + "integrity": "sha512-kFqa6/UcaTbGm/NncN9kzVOODjhZW8e+FRdSeypWe6j33gzclHtwlANs26JrupOntlcWmB0u8+8HZo8s7thHvg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.1.tgz", + "integrity": "sha512-45fuKmAJpxnQWixOGCrS+ro4Uvb4Re9+UTieUY2f8AEc+t7d4AaZ6eUJ3Hva7dtrxAAWHtlEFsXFMAgNnGU9uQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.1.tgz", + "integrity": "sha512-LBEpOz0BsgMEeHgenf5aqmn/lLNTFXVfoWMUox8CtWWYK9X4jmQzWjoGoNb8lmAYml/tQ/Ysvm8q7szu7BoxRQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.1", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.1.tgz", + "integrity": "sha512-+3ELd+nTzhfWb07Vol7EZ+5PTbJ/u74nC6iv4/lwIU99Ip5uuY6QoIf0Hn4m2HoV0qcnRivN3KSqc+FyCHjoVQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.1.tgz", + "integrity": "sha512-/8Rfgns4XD9XOSXlzUDepG8PX+AVWHliYlUkFI3K3GB6tqbdjYqdhcb4BKRd7C0BhZSoaCxhv8kTcBrcZWP+xg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.1.tgz", + "integrity": "sha512-GITpD8dK9C+r+5yRT/UKVT36h/DQLOHdwGVwwoHidlnA168oD3uxA878XloXebK4Ul3gDBBIvEdL7go9gCUFzQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.1.tgz", + "integrity": "sha512-ieMID0JRZY/ZeCrsFQ3Y3NlHNCqIhTprJfDgSB3/lv5jJZ8FX3hqPyXWhe+gvS5ARMBJ242PM+VNz/ctNj//eA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.1.tgz", + "integrity": "sha512-W9//kCrh/6in9rWIBdKaMtuTTzNj6jSeG/haWBADqLLa9P8O5YSRDzgD5y9QBok4AYlzS6ARHifAb75V6G670Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.1.tgz", + "integrity": "sha512-VIUV4z8GD8rtSVMfAj1aXFahsi/+tcoXXNYmXgzISL+KB381vbSTNdeZHHHIYqFyXcoEhu9n5cT+05tRv13rlw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.1.tgz", + "integrity": "sha512-l4rfiiJRN7sTNI//ff65zJ9z8U+k6zcCg0LALU5iEWzY+a1mVZ8iWC1k5EsNKThZ7XCQ6YWtsZ8EWYm7r1UEsg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.1.tgz", + "integrity": "sha512-U0bEuAOLvO/DWFdygTHWY8C067FXz+UbzKgxYhXC0fDieFa0kDIra1FAhsAARRJbvEyso8aAqvPdNxzWuStBnA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.1.tgz", + "integrity": "sha512-NzdQ/Xwu6vPSf/GkdmRNsOfIeSGnh7muundsWItmBsVpMoNPVpM61qNzAVY3pZ1glzzAxLR40UyYM23eaDDbYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.1.tgz", + "integrity": "sha512-7zlw8p3IApcsN7mFw0O1Z1PyEk6PlKMu18roImfl3iQHTnr/yAfYv6s4hXPidbDoI2Q0pW+5xeoM4eTCC0UdrQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.1.tgz", + "integrity": "sha512-cGj5wli+G+nkVQdZo3+7FDKC25Uh4ZVwOAK6A06Hsvgr8WqBBuOy/1s+PUEd/6Je+vjfm6stX0kmib5b/O2Ykw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.1.tgz", + "integrity": "sha512-z3H/HYI9MM0HTv3hQZ81f+AKb+yEoCRlUby1F80vbQ5XdzEMyY/9iNlAmhqiBKw4MJXwfgsh7ERGEOhrM1niMA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.1.tgz", + "integrity": "sha512-wzC24DxAvk8Em01YmVXyjl96Mr+ecTPyOuADAvjGg+fyBpGmxmcr2E5ttf7Im8D0sXZihpxzO1isus8MdjMCXQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.1.tgz", + "integrity": "sha512-1YQ8ybGi2yIXswu6eNzJsrYIGFpnlzEWRl6iR5gMgmsrR0FcNoV1m9k9sc3PuP5rUBLshOZylc9nqSgymI+TYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.1.tgz", + "integrity": "sha512-5Z+DzLCrq5wmU7RDaMDe2DVXMRm2tTDvX2KU14JJVBN2CT/qov7XVix85QoJqHltpvAOZUAc3ndU56HSMWrv8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.1.tgz", + "integrity": "sha512-Q73ENzIdPF5jap4wqLtsfh8YbYSZ8Q0wnxplOlZUOyZy7B4ZKW8DXGWgTCZmF8VWD7Tciwv5F4NsRf6vYlZtqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.1.tgz", + "integrity": "sha512-ajbHrGM/XiK+sXM0JzEbJAen+0E+JMQZ2l4RR4VFwvV9JEERx+oxtgkpoKv1SevhjavK2z2ReHk32pjzktWbGg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.1.tgz", + "integrity": "sha512-IPUW+y4VIjuDVn+OMzHc5FV4GubIwPnsz6ubkvN8cuhEqH81NovB53IUlrlBkPMEPxvNnf79MGBoz8rZ2iW8HA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.1.tgz", + "integrity": "sha512-RIVRWiljWA6CdVu8zkWcRmGP7iRRIIwvhDKem8UMBjPql2TXM5PkDVvvrzMtj1V+WFPB4K7zkIGM7VzRtFkjdg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.1.tgz", + "integrity": "sha512-2BR5M8CPbptC1AK5JbJT1fWrHLvejwZidKx3UMSF0ecHMa+smhi16drIrCEggkgviBwLYd5nwrFLSl5Kho96RQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.1.tgz", + "integrity": "sha512-d5X6RMYv6taIymSk8JBP+nxv8DQAMY6A51GPgusqLdK9wBz5wWIXy1KjTck6HnjE9hqJzJRdk+1p/t5soSbCtw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@fastify/busboy": { + "version": "3.2.0", + "license": "MIT" + }, + "node_modules/@google-cloud/paginator": { + "version": "5.0.2", + "license": "Apache-2.0", + "dependencies": { + "arrify": "^2.0.0", + "extend": "^3.0.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/projectify": { + "version": "4.0.0", + "license": "Apache-2.0", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@google-cloud/promisify": { + "version": "4.0.0", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@google-cloud/storage": { + "version": "7.18.0", + "license": "Apache-2.0", + "dependencies": { + "@google-cloud/paginator": "^5.0.0", + "@google-cloud/projectify": "^4.0.0", + "@google-cloud/promisify": "<4.1.0", + "abort-controller": "^3.0.0", + "async-retry": "^1.3.3", + "duplexify": "^4.1.3", + "fast-xml-parser": "^4.4.1", + "gaxios": "^6.0.2", + "google-auth-library": "^9.6.3", + "html-entities": "^2.5.2", + "mime": "^3.0.0", + "p-limit": "^3.0.1", + "retry-request": "^7.0.0", + "teeny-request": "^9.0.0", + "uuid": "^8.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google/genai": { + "version": "1.34.0", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-1.34.0.tgz", + "integrity": "sha512-vu53UMPvjmb7PGzlYu6Tzxso8Dfhn+a7eQFaS2uNemVtDZKwzSpJ5+ikqBbXplF7RGB1STcVDqCkPvquiwb2sw==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "google-auth-library": "^10.3.0", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.24.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + } + }, + "node_modules/@google/genai/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@google/genai/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@google/genai/node_modules/gaxios": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.3.tgz", + "integrity": "sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2", + "rimraf": "^5.0.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@google/genai/node_modules/gcp-metadata": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz", + "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "gaxios": "^7.0.0", + "google-logging-utils": "^1.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@google/genai/node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "license": "ISC", + "optional": true, + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@google/genai/node_modules/google-auth-library": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.5.0.tgz", + "integrity": "sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^7.0.0", + "gcp-metadata": "^8.0.0", + "google-logging-utils": "^1.0.0", + "gtoken": "^8.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@google/genai/node_modules/google-logging-utils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", + "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@google/genai/node_modules/gtoken": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-8.0.0.tgz", + "integrity": "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==", + "license": "MIT", + "optional": true, + "dependencies": { + "gaxios": "^7.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@google/genai/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@google/genai/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "optional": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@google/genai/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "optional": true, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@google/genai/node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "optional": true, + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/@google/genai/node_modules/rimraf": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.10.tgz", + "integrity": "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==", + "license": "ISC", + "optional": true, + "dependencies": { + "glob": "^10.3.7" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@graphql-tools/executor": { + "version": "1.5.0", + "license": "MIT", + "dependencies": { + "@graphql-tools/utils": "^10.11.0", + "@graphql-typed-document-node/core": "^3.2.0", + "@repeaterjs/repeater": "^3.0.4", + "@whatwg-node/disposablestack": "^0.0.6", + "@whatwg-node/promise-helpers": "^1.0.0", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" + } + }, + "node_modules/@graphql-tools/merge": { + "version": "9.1.6", + "license": "MIT", + "dependencies": { + "@graphql-tools/utils": "^10.11.0", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" + } + }, + "node_modules/@graphql-tools/schema": { + "version": "10.0.30", + "license": "MIT", + "dependencies": { + "@graphql-tools/merge": "^9.1.6", + "@graphql-tools/utils": "^10.11.0", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" + } + }, + "node_modules/@graphql-tools/utils": { + "version": "10.11.0", + "license": "MIT", + "dependencies": { + "@graphql-typed-document-node/core": "^3.1.1", + "@whatwg-node/promise-helpers": "^1.0.0", + "cross-inspect": "1.0.1", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + }, + "peerDependencies": { + "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" + } + }, + "node_modules/@graphql-typed-document-node/core": { + "version": "3.2.0", + "license": "MIT", + "peerDependencies": { + "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" + } + }, + "node_modules/@graphql-yoga/logger": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@graphql-yoga/subscription": { + "version": "5.0.5", + "license": "MIT", + "dependencies": { + "@graphql-yoga/typed-event-target": "^3.0.2", + "@repeaterjs/repeater": "^3.0.4", + "@whatwg-node/events": "^0.1.0", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@graphql-yoga/typed-event-target": { + "version": "3.0.2", + "license": "MIT", + "dependencies": { + "@repeaterjs/repeater": "^3.0.4", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@grpc/grpc-js": { + "version": "1.14.2", + "license": "Apache-2.0", + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.8.0", + "license": "Apache-2.0", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.3", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.7", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.7.tgz", + "integrity": "sha512-vUcD0uauS7EU2caukW8z5lJKtoGMokxNbJtBiwHgpqxEXokaHCBkQUmCHhjFB1VUTWdqj25QoMkMKzgjq+uhrw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@huggingface/jinja": { + "version": "0.5.3", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/transformers": { + "version": "3.8.1", + "license": "Apache-2.0", + "dependencies": { + "@huggingface/jinja": "^0.5.3", + "onnxruntime-node": "1.21.0", + "onnxruntime-web": "1.22.0-dev.20250409-89f8206ba4", + "sharp": "^0.34.1" + } + }, + "node_modules/@huggingface/transformers/node_modules/chownr": { + "version": "3.0.0", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/transformers/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@huggingface/transformers/node_modules/minizlib": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/@huggingface/transformers/node_modules/onnxruntime-common": { + "version": "1.21.0", + "license": "MIT" + }, + "node_modules/@huggingface/transformers/node_modules/onnxruntime-node": { + "version": "1.21.0", + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "global-agent": "^3.0.0", + "onnxruntime-common": "1.21.0", + "tar": "^7.0.1" + } + }, + "node_modules/@huggingface/transformers/node_modules/tar": { + "version": "7.5.2", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/transformers/node_modules/yallist": { + "version": "5.0.0", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@ioredis/commands": { + "version": "1.4.0", + "license": "MIT" + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.2.2", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.3", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.2", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@isaacs/fs-minipass/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@isaacs/string-locale-compare": { + "version": "1.1.0", + "license": "ISC" + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/@js-temporal/polyfill": { + "version": "0.5.1", + "license": "ISC", + "dependencies": { + "jsbi": "^4.3.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@logdna/tail-file": { + "version": "2.2.0", + "license": "SEE LICENSE IN LICENSE", + "engines": { + "node": ">=10.3.0" + } + }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.11", + "license": "BSD-3-Clause", + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@mediapipe/tasks-vision": { + "version": "0.10.17", + "license": "Apache-2.0" + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.24.3", + "license": "MIT", + "dependencies": { + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.0.1", + "express-rate-limit": "^7.5.0", + "jose": "^6.1.1", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@monogrid/gainmap-js": { + "version": "3.4.0", + "license": "MIT", + "dependencies": { + "promise-worker-transferable": "^1.0.4" + }, + "peerDependencies": { + "three": ">= 0.159.0" + } + }, + "node_modules/@next/env": { + "version": "16.0.8", + "license": "MIT" + }, + "node_modules/@next/swc-darwin-arm64": { + "version": "16.0.8", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-x64": { + "version": "16.0.8", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.0.8.tgz", + "integrity": "sha512-+zu2N3QQ0ZOb6RyqQKfcu/pn0UPGmg+mUDqpAAEviAcEVEYgDckemOpiMRsBP3IsEKpcoKuNzekDcPczEeEIzA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "16.0.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.0.8.tgz", + "integrity": "sha512-LConttk+BeD0e6RG0jGEP9GfvdaBVMYsLJ5aDDweKiJVVCu6sGvo+Ohz9nQhvj7EQDVVRJMCGhl19DmJwGr6bQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "16.0.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.0.8.tgz", + "integrity": "sha512-JaXFAlqn8fJV+GhhA9lpg6da/NCN/v9ub98n3HoayoUSPOVdoxEEt86iT58jXqQCs/R3dv5ZnxGkW8aF4obMrQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "16.0.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.0.8.tgz", + "integrity": "sha512-O7M9it6HyNhsJp3HNAsJoHk5BUsfj7hRshfptpGcVsPZ1u0KQ/oVy8oxF7tlwxA5tR43VUP0yRmAGm1us514ng==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-musl": { + "version": "16.0.8", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.0.8.tgz", + "integrity": "sha512-8+KClEC/GLI2dLYcrWwHu5JyC5cZYCFnccVIvmxpo6K+XQt4qzqM5L4coofNDZYkct/VCCyJWGbZZDsg6w6LFA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "16.0.8", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.0.8.tgz", + "integrity": "sha512-rpQ/PgTEgH68SiXmhu/cJ2hk9aZ6YgFvspzQWe2I9HufY6g7V02DXRr/xrVqOaKm2lenBFPNQ+KAaeveywqV+A==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "16.0.8", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.0.8.tgz", + "integrity": "sha512-jWpWjWcMQu2iZz4pEK2IktcfR+OA9+cCG8zenyLpcW8rN4rzjfOzH4yj/b1FiEAZHKS+5Vq8+bZyHi+2yqHbFA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@npmcli/agent": { + "version": "2.2.2", + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^10.0.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/agent/node_modules/agent-base": { + "version": "7.1.4", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/@npmcli/agent/node_modules/https-proxy-agent": { + "version": "7.0.6", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@npmcli/arborist": { + "version": "7.5.4", + "license": "ISC", + "dependencies": { + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/fs": "^3.1.1", + "@npmcli/installed-package-contents": "^2.1.0", + "@npmcli/map-workspaces": "^3.0.2", + "@npmcli/metavuln-calculator": "^7.1.1", + "@npmcli/name-from-folder": "^2.0.0", + "@npmcli/node-gyp": "^3.0.0", + "@npmcli/package-json": "^5.1.0", + "@npmcli/query": "^3.1.0", + "@npmcli/redact": "^2.0.0", + "@npmcli/run-script": "^8.1.0", + "bin-links": "^4.0.4", + "cacache": "^18.0.3", + "common-ancestor-path": "^1.0.1", + "hosted-git-info": "^7.0.2", + "json-parse-even-better-errors": "^3.0.2", + "json-stringify-nice": "^1.1.4", + "lru-cache": "^10.2.2", + "minimatch": "^9.0.4", + "nopt": "^7.2.1", + "npm-install-checks": "^6.2.0", + "npm-package-arg": "^11.0.2", + "npm-pick-manifest": "^9.0.1", + "npm-registry-fetch": "^17.0.1", + "pacote": "^18.0.6", + "parse-conflict-json": "^3.0.0", + "proc-log": "^4.2.0", + "proggy": "^2.0.0", + "promise-all-reject-late": "^1.0.0", + "promise-call-limit": "^3.0.1", + "read-package-json-fast": "^3.0.2", + "semver": "^7.3.7", + "ssri": "^10.0.6", + "treeverse": "^3.0.0", + "walk-up-path": "^3.0.1" + }, + "bin": { + "arborist": "bin/index.js" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/@npmcli/git": { + "version": "5.0.8", + "license": "ISC", + "dependencies": { + "@npmcli/promise-spawn": "^7.0.0", + "ini": "^4.1.3", + "lru-cache": "^10.0.1", + "npm-pick-manifest": "^9.0.0", + "proc-log": "^4.0.0", + "promise-inflight": "^1.0.1", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/@npmcli/package-json": { + "version": "5.2.1", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^5.0.0", + "glob": "^10.2.2", + "hosted-git-info": "^7.0.0", + "json-parse-even-better-errors": "^3.0.0", + "normalize-package-data": "^6.0.0", + "proc-log": "^4.0.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/@npmcli/promise-spawn": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "which": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/abbrev": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/glob": { + "version": "10.5.0", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/arborist/node_modules/hosted-git-info": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/ini": { + "version": "4.1.3", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/isexe": { + "version": "3.1.1", + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/@npmcli/arborist/node_modules/json-parse-even-better-errors": { + "version": "3.0.2", + "license": "MIT", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/arborist/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@npmcli/arborist/node_modules/nopt": { + "version": "7.2.1", + "license": "ISC", + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/npm-pick-manifest": { + "version": "9.1.0", + "license": "ISC", + "dependencies": { + "npm-install-checks": "^6.0.0", + "npm-normalize-package-bin": "^3.0.0", + "npm-package-arg": "^11.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/arborist/node_modules/which": { + "version": "4.0.0", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/fs": { + "version": "3.1.1", + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/git": { + "version": "6.0.3", + "license": "ISC", + "dependencies": { + "@npmcli/promise-spawn": "^8.0.0", + "ini": "^5.0.0", + "lru-cache": "^10.0.1", + "npm-pick-manifest": "^10.0.0", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/git/node_modules/isexe": { + "version": "3.1.1", + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/@npmcli/git/node_modules/which": { + "version": "5.0.0", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/installed-package-contents": { + "version": "2.1.0", + "license": "ISC", + "dependencies": { + "npm-bundled": "^3.0.0", + "npm-normalize-package-bin": "^3.0.0" + }, + "bin": { + "installed-package-contents": "bin/index.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/map-workspaces": { + "version": "3.0.6", + "license": "ISC", + "dependencies": { + "@npmcli/name-from-folder": "^2.0.0", + "glob": "^10.2.2", + "minimatch": "^9.0.0", + "read-package-json-fast": "^3.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/glob": { + "version": "10.5.0", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/map-workspaces/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@npmcli/metavuln-calculator": { + "version": "7.1.1", + "license": "ISC", + "dependencies": { + "cacache": "^18.0.0", + "json-parse-even-better-errors": "^3.0.0", + "pacote": "^18.0.0", + "proc-log": "^4.1.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/json-parse-even-better-errors": { + "version": "3.0.2", + "license": "MIT", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/name-from-folder": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/node-gyp": { + "version": "3.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/package-json": { + "version": "6.2.0", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^6.0.0", + "glob": "^10.2.2", + "hosted-git-info": "^8.0.0", + "json-parse-even-better-errors": "^4.0.0", + "proc-log": "^5.0.0", + "semver": "^7.5.3", + "validate-npm-package-license": "^3.0.4" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/package-json/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@npmcli/package-json/node_modules/glob": { + "version": "10.5.0", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/package-json/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/package-json/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@npmcli/promise-spawn": { + "version": "8.0.3", + "license": "ISC", + "dependencies": { + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/promise-spawn/node_modules/isexe": { + "version": "3.1.1", + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/@npmcli/promise-spawn/node_modules/which": { + "version": "5.0.0", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/query": { + "version": "3.1.0", + "license": "ISC", + "dependencies": { + "postcss-selector-parser": "^6.0.10" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/redact": { + "version": "2.0.1", + "license": "ISC", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script": { + "version": "8.1.0", + "license": "ISC", + "dependencies": { + "@npmcli/node-gyp": "^3.0.0", + "@npmcli/package-json": "^5.0.0", + "@npmcli/promise-spawn": "^7.0.0", + "node-gyp": "^10.0.0", + "proc-log": "^4.0.0", + "which": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/@npmcli/git": { + "version": "5.0.8", + "license": "ISC", + "dependencies": { + "@npmcli/promise-spawn": "^7.0.0", + "ini": "^4.1.3", + "lru-cache": "^10.0.1", + "npm-pick-manifest": "^9.0.0", + "proc-log": "^4.0.0", + "promise-inflight": "^1.0.1", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/@npmcli/package-json": { + "version": "5.2.1", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^5.0.0", + "glob": "^10.2.2", + "hosted-git-info": "^7.0.0", + "json-parse-even-better-errors": "^3.0.0", + "normalize-package-data": "^6.0.0", + "proc-log": "^4.0.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/@npmcli/promise-spawn": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "which": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/glob": { + "version": "10.5.0", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/run-script/node_modules/hosted-git-info": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/ini": { + "version": "4.1.3", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/isexe": { + "version": "3.1.1", + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/@npmcli/run-script/node_modules/json-parse-even-better-errors": { + "version": "3.0.2", + "license": "MIT", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@npmcli/run-script/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@npmcli/run-script/node_modules/npm-pick-manifest": { + "version": "9.1.0", + "license": "ISC", + "dependencies": { + "npm-install-checks": "^6.0.0", + "npm-normalize-package-bin": "^3.0.0", + "npm-package-arg": "^11.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@npmcli/run-script/node_modules/which": { + "version": "4.0.0", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^16.13.0 || >=18.0.0" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "license": "MIT" + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "license": "BSD-3-Clause" + }, + "node_modules/@pulumi/gcp": { + "version": "9.6.0", + "license": "Apache-2.0", + "dependencies": { + "@npmcli/package-json": "^6.2.0", + "@pulumi/pulumi": "^3.142.0", + "@types/express": "^4.16.0" + } + }, + "node_modules/@pulumi/kubernetes": { + "version": "4.24.1", + "resolved": "https://registry.npmjs.org/@pulumi/kubernetes/-/kubernetes-4.24.1.tgz", + "integrity": "sha512-3KC4fsxniS9W1dUo45MzMDByIWc+wGhOYQdbVe/neSmuRFpu3JmiLHSGukcIGNUGSblqRdVzsfiW5WEtCghbcA==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@pulumi/pulumi": "^3.142.0", + "glob": "^10.3.10", + "shell-quote": "^1.6.1" + } + }, + "node_modules/@pulumi/kubernetes/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@pulumi/kubernetes/node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@pulumi/kubernetes/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@pulumi/kubernetes/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@pulumi/pulumi": { + "version": "3.210.0", + "license": "Apache-2.0", + "dependencies": { + "@grpc/grpc-js": "^1.10.1", + "@logdna/tail-file": "^2.0.6", + "@npmcli/arborist": "^7.3.1", + "@opentelemetry/api": "^1.9", + "@opentelemetry/exporter-zipkin": "^1.28", + "@opentelemetry/instrumentation": "^0.55", + "@opentelemetry/instrumentation-grpc": "^0.55", + "@opentelemetry/resources": "^1.28", + "@opentelemetry/sdk-trace-base": "^1.28", + "@opentelemetry/sdk-trace-node": "^1.28", + "@types/google-protobuf": "^3.15.5", + "@types/semver": "^7.5.6", + "@types/tmp": "^0.2.6", + "execa": "^5.1.0", + "fdir": "^6.1.1", + "google-protobuf": "^3.21.4", + "got": "^11.8.6", + "ini": "^2.0.0", + "js-yaml": "^3.14.2", + "minimist": "^1.2.6", + "normalize-package-data": "^6.0.0", + "package-directory": "^8.1.0", + "picomatch": "^3.0.1", + "require-from-string": "^2.0.1", + "semver": "^7.5.2", + "source-map-support": "^0.5.6", + "tmp": "^0.2.4", + "upath": "^1.1.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "ts-node": ">= 7.0.1 < 12", + "typescript": ">= 3.8.3 < 6" + }, + "peerDependenciesMeta": { + "ts-node": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/api-logs": { + "version": "0.55.0", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/context-async-hooks": { + "version": "1.30.1", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/core": { + "version": "1.30.1", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/exporter-zipkin": { + "version": "1.30.1", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.0.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/instrumentation": { + "version": "0.55.0", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.55.0", + "@types/shimmer": "^1.2.0", + "import-in-the-middle": "^1.8.1", + "require-in-the-middle": "^7.1.1", + "semver": "^7.5.2", + "shimmer": "^1.2.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/instrumentation-grpc": { + "version": "0.55.0", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/instrumentation": "0.55.0", + "@opentelemetry/semantic-conventions": "1.27.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/instrumentation-grpc/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.27.0", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/propagator-b3": { + "version": "1.30.1", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/propagator-jaeger": { + "version": "1.30.1", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/resources": { + "version": "1.30.1", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/sdk-trace-base": { + "version": "1.30.1", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "1.30.1", + "@opentelemetry/resources": "1.30.1", + "@opentelemetry/semantic-conventions": "1.28.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/sdk-trace-node": { + "version": "1.30.1", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/context-async-hooks": "1.30.1", + "@opentelemetry/core": "1.30.1", + "@opentelemetry/propagator-b3": "1.30.1", + "@opentelemetry/propagator-jaeger": "1.30.1", + "@opentelemetry/sdk-trace-base": "1.30.1", + "semver": "^7.5.2" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@pulumi/pulumi/node_modules/@opentelemetry/semantic-conventions": { + "version": "1.28.0", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@pulumi/pulumi/node_modules/fdir": { + "version": "6.5.0", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/@pulumi/pulumi/node_modules/ini": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/@pulumi/pulumi/node_modules/picomatch": { + "version": "3.0.1", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/@qdrant/js-client-rest": { + "version": "1.16.2", + "license": "Apache-2.0", + "dependencies": { + "@qdrant/openapi-typescript-fetch": "1.2.6", + "undici": "^6.0.0" + }, + "engines": { + "node": ">=18.17.0", + "pnpm": ">=8" + }, + "peerDependencies": { + "typescript": ">=4.7" + } + }, + "node_modules/@qdrant/openapi-typescript-fetch": { + "version": "1.2.6", + "license": "MIT", + "engines": { + "node": ">=18.0.0", + "pnpm": ">=8" + } + }, + "node_modules/@react-three/drei": { + "version": "10.7.7", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.26.0", + "@mediapipe/tasks-vision": "0.10.17", + "@monogrid/gainmap-js": "^3.0.6", + "@use-gesture/react": "^10.3.1", + "camera-controls": "^3.1.0", + "cross-env": "^7.0.3", + "detect-gpu": "^5.0.56", + "glsl-noise": "^0.0.0", + "hls.js": "^1.5.17", + "maath": "^0.10.8", + "meshline": "^3.3.1", + "stats-gl": "^2.2.8", + "stats.js": "^0.17.0", + "suspend-react": "^0.1.3", + "three-mesh-bvh": "^0.8.3", + "three-stdlib": "^2.35.6", + "troika-three-text": "^0.52.4", + "tunnel-rat": "^0.1.2", + "use-sync-external-store": "^1.4.0", + "utility-types": "^3.11.0", + "zustand": "^5.0.1" + }, + "peerDependencies": { + "@react-three/fiber": "^9.0.0", + "react": "^19", + "react-dom": "^19", + "three": ">=0.159" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/@react-three/fiber": { + "version": "9.4.2", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.17.8", + "@types/react-reconciler": "^0.32.0", + "@types/webxr": "*", + "base64-js": "^1.5.1", + "buffer": "^6.0.3", + "its-fine": "^2.0.0", + "react-reconciler": "^0.31.0", + "react-use-measure": "^2.1.7", + "scheduler": "^0.25.0", + "suspend-react": "^0.1.3", + "use-sync-external-store": "^1.4.0", + "zustand": "^5.0.3" + }, + "peerDependencies": { + "expo": ">=43.0", + "expo-asset": ">=8.4", + "expo-file-system": ">=11.0", + "expo-gl": ">=11.0", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "react-native": ">=0.78", + "three": ">=0.156" + }, + "peerDependenciesMeta": { + "expo": { + "optional": true + }, + "expo-asset": { + "optional": true + }, + "expo-file-system": { + "optional": true + }, + "expo-gl": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "react-native": { + "optional": true + } + } + }, + "node_modules/@redis/bloom": { + "version": "1.2.0", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/client": { + "version": "1.6.1", + "license": "MIT", + "dependencies": { + "cluster-key-slot": "1.1.2", + "generic-pool": "3.9.0", + "yallist": "4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@redis/graph": { + "version": "1.1.1", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/json": { + "version": "1.0.7", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/search": { + "version": "1.2.0", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@redis/time-series": { + "version": "1.1.0", + "license": "MIT", + "peerDependencies": { + "@redis/client": "^1.0.0" + } + }, + "node_modules/@repeaterjs/repeater": { + "version": "3.0.6", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.53.3.tgz", + "integrity": "sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.53.3.tgz", + "integrity": "sha512-CbDGaMpdE9sh7sCmTrTUyllhrg65t6SwhjlMJsLr+J8YjFuPmCEjbBSx4Z/e4SmDyH3aB5hGaJUP2ltV/vcs4w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.53.3.tgz", + "integrity": "sha512-Nr7SlQeqIBpOV6BHHGZgYBuSdanCXuw09hon14MGOLGmXAFYjx1wNvquVPmpZnl0tLjg25dEdr4IQ6GgyToCUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.53.3.tgz", + "integrity": "sha512-DZ8N4CSNfl965CmPktJ8oBnfYr3F8dTTNBQkRlffnUarJ2ohudQD17sZBa097J8xhQ26AwhHJ5mvUyQW8ddTsQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.53.3.tgz", + "integrity": "sha512-yMTrCrK92aGyi7GuDNtGn2sNW+Gdb4vErx4t3Gv/Tr+1zRb8ax4z8GWVRfr3Jw8zJWvpGHNpss3vVlbF58DZ4w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.53.3.tgz", + "integrity": "sha512-lMfF8X7QhdQzseM6XaX0vbno2m3hlyZFhwcndRMw8fbAGUGL3WFMBdK0hbUBIUYcEcMhVLr1SIamDeuLBnXS+Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.53.3.tgz", + "integrity": "sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.53.3.tgz", + "integrity": "sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.53.3.tgz", + "integrity": "sha512-RGrFLWgMhSxRs/EWJMIFM1O5Mzuz3Xy3/mnxJp/5cVhZ2XoCAxJnmNsEyeMJtpK+wu0FJFWz+QF4mjCA7AUQ3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.53.3.tgz", + "integrity": "sha512-kASyvfBEWYPEwe0Qv4nfu6pNkITLTb32p4yTgzFCocHnJLAHs+9LjUu9ONIhvfT/5lv4YS5muBHyuV84epBo/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.53.3.tgz", + "integrity": "sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.53.3.tgz", + "integrity": "sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.53.3.tgz", + "integrity": "sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.53.3.tgz", + "integrity": "sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.53.3.tgz", + "integrity": "sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", + "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", + "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.53.3.tgz", + "integrity": "sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.53.3.tgz", + "integrity": "sha512-GOFuKpsxR/whszbF/bzydebLiXIHSgsEUp6M0JI8dWvi+fFa1TD6YQa4aSZHtpmh2/uAlj/Dy+nmby3TJ3pkTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.53.3.tgz", + "integrity": "sha512-iah+THLcBJdpfZ1TstDFbKNznlzoxa8fmnFYK4V67HvmuNYkVdAywJSoteUszvBQ9/HqN2+9AZghbajMsFT+oA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.53.3.tgz", + "integrity": "sha512-J9QDiOIZlZLdcot5NXEepDkstocktoVjkaKUtqzgzpt2yWjGlbYiKyp05rWwk4nypbYUNoFAztEgixoLaSETkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.53.3.tgz", + "integrity": "sha512-UhTd8u31dXadv0MopwGgNOBpUVROFKWVQgAg5N1ESyCz8AuBcMqm4AuTjrwgQKGDfoFuz02EuMRHQIw/frmYKQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@sigstore/bundle": { + "version": "2.3.2", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.3.2" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@sigstore/core": { + "version": "1.1.0", + "license": "Apache-2.0", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@sigstore/protobuf-specs": { + "version": "0.3.3", + "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/sign": { + "version": "2.3.2", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^2.3.2", + "@sigstore/core": "^1.0.0", + "@sigstore/protobuf-specs": "^0.3.2", + "make-fetch-happen": "^13.0.1", + "proc-log": "^4.2.0", + "promise-retry": "^2.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@sigstore/sign/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/@sigstore/tuf": { + "version": "2.3.4", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.3.2", + "tuf-js": "^2.2.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@sigstore/verify": { + "version": "1.2.1", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^2.3.2", + "@sigstore/core": "^1.1.0", + "@sigstore/protobuf-specs": "^0.3.2" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@sindresorhus/is": { + "version": "4.6.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/@swc/helpers": { + "version": "0.5.15", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@szmarczak/http-timer": { + "version": "4.0.6", + "license": "MIT", + "dependencies": { + "defer-to-connect": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@testing-library/dom": { + "version": "10.4.1", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", + "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/react": { + "version": "16.3.1", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.1.tgz", + "integrity": "sha512-gr4KtAWqIOQoucWYD/f6ki+j5chXfcPc74Col/6poTyqTmn7zRmodWahWRCp8tYd+GMqBonw6hstNzqjbs6gjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@tootallnate/once": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tufjs/canonical-json": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@tufjs/models": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "@tufjs/canonical-json": "2.0.0", + "minimatch": "^9.0.4" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@tufjs/models/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@tufjs/models/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "license": "MIT" + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/cacheable-request": { + "version": "6.0.3", + "license": "MIT", + "dependencies": { + "@types/http-cache-semantics": "*", + "@types/keyv": "^3.1.4", + "@types/node": "*", + "@types/responselike": "^1.0.0" + } + }, + "node_modules/@types/caseless": { + "version": "0.12.5", + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "license": "MIT" + }, + "node_modules/@types/d3-drag": { + "version": "3.0.7", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-selection": { + "version": "3.0.11", + "license": "MIT" + }, + "node_modules/@types/d3-transition": { + "version": "3.0.9", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-zoom": { + "version": "3.0.8", + "license": "MIT", + "dependencies": { + "@types/d3-interpolate": "*", + "@types/d3-selection": "*" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/diff": { + "version": "8.0.0", + "deprecated": "This is a stub types definition. diff provides its own type definitions, so you do not need this installed.", + "license": "MIT", + "dependencies": { + "diff": "*" + } + }, + "node_modules/@types/diff-match-patch": { + "version": "1.0.36", + "resolved": "https://registry.npmjs.org/@types/diff-match-patch/-/diff-match-patch-1.0.36.tgz", + "integrity": "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==", + "license": "MIT" + }, + "node_modules/@types/draco3d": { + "version": "1.4.10", + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/express": { + "version": "4.17.25", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.7", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/google-protobuf": { + "version": "3.15.12", + "license": "MIT" + }, + "node_modules/@types/http-cache-semantics": { + "version": "4.0.4", + "license": "MIT" + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "license": "MIT" + }, + "node_modules/@types/keyv": { + "version": "3.1.4", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.10.2", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/offscreencanvas": { + "version": "2019.7.3", + "license": "MIT" + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.2.7", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-reconciler": { + "version": "0.32.3", + "license": "MIT", + "peerDependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/react/node_modules/csstype": { + "version": "3.2.3", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/request": { + "version": "2.48.13", + "license": "MIT", + "dependencies": { + "@types/caseless": "*", + "@types/node": "*", + "@types/tough-cookie": "*", + "form-data": "^2.5.5" + } + }, + "node_modules/@types/responselike": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/semver": { + "version": "7.7.1", + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/shimmer": { + "version": "1.2.0", + "license": "MIT" + }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.181.0", + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": "*", + "@webgpu/types": "*", + "fflate": "~0.8.2", + "meshoptimizer": "~0.22.0" + } + }, + "node_modules/@types/tmp": { + "version": "0.2.6", + "license": "MIT" + }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "license": "MIT" + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@use-gesture/core": { + "version": "10.3.1", + "license": "MIT" + }, + "node_modules/@use-gesture/react": { + "version": "10.3.1", + "license": "MIT", + "dependencies": { + "@use-gesture/core": "10.3.1" + }, + "peerDependencies": { + "react": ">= 16.8.0" + } + }, + "node_modules/@vercel/oidc": { + "version": "3.0.5", + "license": "Apache-2.0", + "engines": { + "node": ">= 20" + } + }, + "node_modules/@vitest/coverage-v8": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-3.2.4.tgz", + "integrity": "sha512-EyF9SXU6kS5Ku/U82E259WSnvg6c8KTjppUncuNdm5QHpe17mwREHnjDzozC8x9MZ0xfBUFSaLkRv4TMA75ALQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.3.0", + "@bcoe/v8-coverage": "^1.0.2", + "ast-v8-to-istanbul": "^0.3.3", + "debug": "^4.4.1", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-lib-source-maps": "^5.0.6", + "istanbul-reports": "^3.1.7", + "magic-string": "^0.30.17", + "magicast": "^0.3.5", + "std-env": "^3.9.0", + "test-exclude": "^7.0.1", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "3.2.4", + "vitest": "3.2.4" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", + "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.4.tgz", + "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.4.tgz", + "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.4", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.4.tgz", + "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.4.tgz", + "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.4.tgz", + "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@webgpu/types": { + "version": "0.1.67", + "license": "BSD-3-Clause" + }, + "node_modules/@whatwg-node/disposablestack": { + "version": "0.0.6", + "license": "MIT", + "dependencies": { + "@whatwg-node/promise-helpers": "^1.0.0", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@whatwg-node/events": { + "version": "0.1.2", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@whatwg-node/fetch": { + "version": "0.10.13", + "license": "MIT", + "dependencies": { + "@whatwg-node/node-fetch": "^0.8.3", + "urlpattern-polyfill": "^10.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@whatwg-node/node-fetch": { + "version": "0.8.4", + "license": "MIT", + "dependencies": { + "@fastify/busboy": "^3.1.1", + "@whatwg-node/disposablestack": "^0.0.6", + "@whatwg-node/promise-helpers": "^1.3.2", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@whatwg-node/promise-helpers": { + "version": "1.3.2", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@whatwg-node/server": { + "version": "0.10.17", + "license": "MIT", + "dependencies": { + "@envelop/instrumentation": "^1.0.0", + "@whatwg-node/disposablestack": "^0.0.6", + "@whatwg-node/fetch": "^0.10.13", + "@whatwg-node/promise-helpers": "^1.3.2", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@xyflow/react": { + "version": "12.10.0", + "license": "MIT", + "dependencies": { + "@xyflow/system": "0.0.74", + "classcat": "^5.0.3", + "zustand": "^4.4.0" + }, + "peerDependencies": { + "react": ">=17", + "react-dom": ">=17" + } + }, + "node_modules/@xyflow/react/node_modules/zustand": { + "version": "4.5.7", + "license": "MIT", + "dependencies": { + "use-sync-external-store": "^1.2.2" + }, + "engines": { + "node": ">=12.7.0" + }, + "peerDependencies": { + "@types/react": ">=16.8", + "immer": ">=9.0.6", + "react": ">=16.8" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/@xyflow/system": { + "version": "0.0.74", + "license": "MIT", + "dependencies": { + "@types/d3-drag": "^3.0.7", + "@types/d3-interpolate": "^3.0.4", + "@types/d3-selection": "^3.0.10", + "@types/d3-transition": "^3.0.8", + "@types/d3-zoom": "^3.0.8", + "d3-drag": "^3.0.0", + "d3-interpolate": "^3.0.1", + "d3-selection": "^3.0.0", + "d3-zoom": "^3.0.0" + } + }, + "node_modules/@yarnpkg/lockfile": { + "version": "1.1.0", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/abbrev": { + "version": "1.1.1", + "license": "ISC" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-attributes": { + "version": "1.9.5", + "license": "MIT", + "peerDependencies": { + "acorn": "^8" + } + }, + "node_modules/adm-zip": { + "version": "0.5.16", + "license": "MIT", + "engines": { + "node": ">=12.0" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ai": { + "version": "5.0.108", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/gateway": "2.0.18", + "@ai-sdk/provider": "2.0.0", + "@ai-sdk/provider-utils": "3.0.18", + "@opentelemetry/api": "1.9.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/aproba": { + "version": "2.1.0", + "license": "ISC" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "license": "ISC", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/arrify": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.8.tgz", + "integrity": "sha512-szgSZqUxI5T8mLKvS7WTjF9is+MVbOeLADU73IseOcrqhxr/VAvy6wfoVE39KnKzA7JRhjF5eUagNlHwvZPlKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^9.0.1" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-retry": { + "version": "1.3.3", + "license": "MIT", + "dependencies": { + "retry": "0.13.1" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "license": "MIT" + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bidi-js": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, + "node_modules/bignumber.js": { + "version": "9.3.1", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/bin-links": { + "version": "4.0.4", + "license": "ISC", + "dependencies": { + "cmd-shim": "^6.0.0", + "npm-normalize-package-bin": "^3.0.0", + "read-cmd-shim": "^4.0.0", + "write-file-atomic": "^5.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bintrees": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.2.1", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/boolean": { + "version": "3.2.0", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "license": "BSD-3-Clause" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "license": "MIT" + }, + "node_modules/bytes": { + "version": "3.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cacache": { + "version": "18.0.4", + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^3.1.0", + "fs-minipass": "^3.0.0", + "glob": "^10.2.2", + "lru-cache": "^10.0.1", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^4.0.0", + "ssri": "^10.0.0", + "tar": "^6.1.11", + "unique-filename": "^3.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/cacache/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/cacache/node_modules/fs-minipass": { + "version": "3.0.3", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/cacache/node_modules/glob": { + "version": "10.5.0", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/cacache/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/cacache/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/cacache/node_modules/p-map": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cacheable-lookup": { + "version": "5.0.4", + "license": "MIT", + "engines": { + "node": ">=10.6.0" + } + }, + "node_modules/cacheable-request": { + "version": "7.0.4", + "license": "MIT", + "dependencies": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cacheable-request/node_modules/get-stream": { + "version": "5.2.0", + "license": "MIT", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/call-bind": { + "version": "1.0.8", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.0", + "es-define-property": "^1.0.0", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camera-controls": { + "version": "3.1.2", + "license": "MIT", + "engines": { + "node": ">=22.0.0", + "npm": ">=10.5.1" + }, + "peerDependencies": { + "three": ">=0.126.1" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001760", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/check-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", + "integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/chownr": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/chrono-node": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/chrono-node/-/chrono-node-2.9.0.tgz", + "integrity": "sha512-glI4YY2Jy6JII5l3d5FN6rcrIbKSQqKPhWsIRYPK2IK8Mm4Q1ZZFdYIaDqglUNf7gNwG+kWIzTn0omzzE0VkvQ==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/ci-info": { + "version": "3.9.0", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cjs-module-lexer": { + "version": "1.4.3", + "license": "MIT" + }, + "node_modules/classcat": { + "version": "5.0.5", + "license": "MIT" + }, + "node_modules/clean-stack": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "2.9.2", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/client-only": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/cliui": { + "version": "8.0.1", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/clone-response": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "mimic-response": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/cmd-shim": { + "version": "6.0.3", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "license": "MIT" + }, + "node_modules/color-support": { + "version": "1.1.3", + "license": "ISC", + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/colorette": { + "version": "2.0.20", + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "14.0.2", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/common-ancestor-path": { + "version": "1.0.1", + "license": "ISC" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "license": "ISC" + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/control-service": { + "resolved": "apps/control", + "link": true + }, + "node_modules/cookie": { + "version": "0.7.2", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cross-env": { + "version": "7.0.3", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "bin": { + "cross-env": "src/bin/cross-env.js", + "cross-env-shell": "src/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=10.14", + "npm": ">=6", + "yarn": ">=1" + } + }, + "node_modules/cross-inspect": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/css-tree": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.1.0.tgz", + "integrity": "sha512-0eW44TGN5SQXU1mWSkKwFstI/22X2bG1nYzZTYMAWjylYURhse752YgbE4Cx46AC+bAvI+/dYTPRk1LqSUnu6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.12.2", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cssstyle": { + "version": "5.3.5", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-5.3.5.tgz", + "integrity": "sha512-GlsEptulso7Jg0VaOZ8BXQi3AkYM5BOJKEO/rjMidSCq70FkIC5y0eawrCXeYzxgt3OCf4Ls+eoxN+/05vN0Ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^4.1.1", + "@csstools/css-syntax-patches-for-csstree": "^1.0.21", + "css-tree": "^3.1.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/csstype": { + "version": "3.1.3", + "license": "MIT" + }, + "node_modules/d3-color": { + "version": "3.1.0", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dispatch": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-drag": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-selection": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-selection": { + "version": "3.0.0", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-transition": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-dispatch": "1 - 3", + "d3-ease": "1 - 3", + "d3-interpolate": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "d3-selection": "2 - 3" + } + }, + "node_modules/d3-zoom": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "2 - 3", + "d3-transition": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/dagre": { + "version": "0.8.5", + "license": "MIT", + "dependencies": { + "graphlib": "^2.1.8", + "lodash": "^4.17.15" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 12" + } + }, + "node_modules/data-urls": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-6.0.0.tgz", + "integrity": "sha512-BnBS08aLUM+DKamupXs3w2tJJoqU+AkaE/+6vQxi/G/DPmIZFJJp9Dkb1kM03AZx8ADehDUZgsNxju3mPXZYIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^15.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/data-urls/node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/data-urls/node_modules/webidl-conversions": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.0.tgz", + "integrity": "sha512-n4W4YFyz5JzOfQeA8oN7dUYpR+MBP3PIUsn2jLjWXwK5ASUzt0Jc/A5sAUZoCYFJRGF0FBKJ+1JjN43rNdsQzA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/data-urls/node_modules/whatwg-url": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-15.1.0.tgz", + "integrity": "sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/dateformat": { + "version": "4.6.3", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/decompress-response/node_modules/mimic-response": { + "version": "3.1.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/defer-to-connect": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/denque": { + "version": "2.1.0", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/detect-gpu": { + "version": "5.0.70", + "license": "MIT", + "dependencies": { + "webgl-constants": "^1.1.1" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/diff": { + "version": "8.0.2", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/diff-match-patch": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz", + "integrity": "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==", + "license": "Apache-2.0" + }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/draco3d": { + "version": "1.5.7", + "license": "Apache-2.0" + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/duplexify": { + "version": "4.1.3", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.4.1", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1", + "stream-shift": "^1.0.2" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "license": "MIT" + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/encoding": { + "version": "0.1.13", + "license": "MIT", + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "license": "MIT", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/engram-mcp": { + "resolved": "apps/mcp", + "link": true + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/err-code": { + "version": "2.0.3", + "license": "MIT" + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es6-error": { + "version": "4.1.1", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.27.1", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.1", + "@esbuild/android-arm": "0.27.1", + "@esbuild/android-arm64": "0.27.1", + "@esbuild/android-x64": "0.27.1", + "@esbuild/darwin-arm64": "0.27.1", + "@esbuild/darwin-x64": "0.27.1", + "@esbuild/freebsd-arm64": "0.27.1", + "@esbuild/freebsd-x64": "0.27.1", + "@esbuild/linux-arm": "0.27.1", + "@esbuild/linux-arm64": "0.27.1", + "@esbuild/linux-ia32": "0.27.1", + "@esbuild/linux-loong64": "0.27.1", + "@esbuild/linux-mips64el": "0.27.1", + "@esbuild/linux-ppc64": "0.27.1", + "@esbuild/linux-riscv64": "0.27.1", + "@esbuild/linux-s390x": "0.27.1", + "@esbuild/linux-x64": "0.27.1", + "@esbuild/netbsd-arm64": "0.27.1", + "@esbuild/netbsd-x64": "0.27.1", + "@esbuild/openbsd-arm64": "0.27.1", + "@esbuild/openbsd-x64": "0.27.1", + "@esbuild/openharmony-arm64": "0.27.1", + "@esbuild/sunos-x64": "0.27.1", + "@esbuild/win32-arm64": "0.27.1", + "@esbuild/win32-ia32": "0.27.1", + "@esbuild/win32-x64": "0.27.1" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/esprima": { + "version": "4.0.1", + "license": "BSD-2-Clause", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "license": "MIT" + }, + "node_modules/eventsource": { + "version": "3.0.7", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/exponential-backoff": { + "version": "3.1.3", + "license": "Apache-2.0" + }, + "node_modules/express": { + "version": "5.2.1", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "7.5.1", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "license": "MIT" + }, + "node_modules/falkordb": { + "version": "6.4.0", + "license": "MIT", + "workspaces": [ + "./packages/*" + ], + "dependencies": { + "@js-temporal/polyfill": "^0.5.1", + "@redis/client": "^1.6.0", + "cluster-key-slot": "1.1.2", + "generic-pool": "^3.9.0", + "lodash": "^4.17.21", + "redis": "^4.7.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/fast-copy": { + "version": "4.0.1", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "license": "MIT" + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "license": "MIT" + }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "license": "Unlicense" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fast-xml-parser": { + "version": "4.5.3", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^1.1.1" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/fflate": { + "version": "0.8.2", + "license": "MIT" + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/fill-range": { + "version": "7.1.1", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/find-up-simple": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/find-yarn-workspace-root": { + "version": "2.0.0", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "micromatch": "^4.0.2" + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "license": "Apache-2.0" + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/form-data": { + "version": "2.5.5", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.35", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/form-data/node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/form-data/node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "optional": true, + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fs-extra": { + "version": "10.1.0", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gauge": { + "version": "3.0.2", + "license": "ISC", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/gaxios": { + "version": "6.7.1", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/gaxios/node_modules/agent-base": { + "version": "7.1.4", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/gaxios/node_modules/https-proxy-agent": { + "version": "7.0.6", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/gaxios/node_modules/uuid": { + "version": "9.0.1", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/gcp-metadata": { + "version": "6.1.1", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^6.1.1", + "google-logging-utils": "^0.0.2", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/generic-pool": { + "version": "3.9.0", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.4.0", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.0", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "license": "BSD-2-Clause" + }, + "node_modules/global-agent": { + "version": "3.0.0", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "es6-error": "^4.1.1", + "matcher": "^3.0.0", + "roarr": "^2.15.3", + "semver": "^7.3.2", + "serialize-error": "^7.0.1" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glsl-noise": { + "version": "0.0.0", + "license": "MIT" + }, + "node_modules/google-auth-library": { + "version": "9.15.1", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-logging-utils": { + "version": "0.0.2", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/google-protobuf": { + "version": "3.21.4", + "license": "(BSD-3-Clause AND Apache-2.0)" + }, + "node_modules/gopd": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/got": { + "version": "11.8.6", + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.2", + "decompress-response": "^6.0.0", + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" + }, + "engines": { + "node": ">=10.19.0" + }, + "funding": { + "url": "https://github.com/sindresorhus/got?sponsor=1" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "license": "ISC" + }, + "node_modules/graphlib": { + "version": "2.1.8", + "license": "MIT", + "dependencies": { + "lodash": "^4.17.15" + } + }, + "node_modules/graphql": { + "version": "16.12.0", + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" + } + }, + "node_modules/graphql-yoga": { + "version": "5.17.1", + "license": "MIT", + "dependencies": { + "@envelop/core": "^5.3.0", + "@envelop/instrumentation": "^1.0.0", + "@graphql-tools/executor": "^1.5.0", + "@graphql-tools/schema": "^10.0.11", + "@graphql-tools/utils": "^10.11.0", + "@graphql-yoga/logger": "^2.0.1", + "@graphql-yoga/subscription": "^5.0.5", + "@whatwg-node/fetch": "^0.10.6", + "@whatwg-node/promise-helpers": "^1.3.2", + "@whatwg-node/server": "^0.10.14", + "lru-cache": "^10.0.0", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "graphql": "^15.2.0 || ^16.0.0" + } + }, + "node_modules/gtoken": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "license": "ISC" + }, + "node_modules/hasown": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/help-me": { + "version": "5.0.0", + "license": "MIT" + }, + "node_modules/hls.js": { + "version": "1.6.15", + "license": "Apache-2.0" + }, + "node_modules/hono": { + "version": "4.11.1", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.1.tgz", + "integrity": "sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/hosted-git-info": { + "version": "8.1.0", + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/html-entities": { + "version": "2.6.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT" + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/http-cache-semantics": { + "version": "4.2.0", + "license": "BSD-2-Clause" + }, + "node_modules/http-errors": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/http2-wrapper": { + "version": "1.0.3", + "license": "MIT", + "dependencies": { + "quick-lru": "^5.1.1", + "resolve-alpn": "^1.0.0" + }, + "engines": { + "node": ">=10.19.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/husky": { + "version": "9.1.7", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", + "integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==", + "dev": true, + "license": "MIT", + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.0", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore-walk": { + "version": "6.0.5", + "license": "ISC", + "dependencies": { + "minimatch": "^9.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/ignore-walk/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/ignore-walk/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/immediate": { + "version": "3.0.6", + "license": "MIT" + }, + "node_modules/import-in-the-middle": { + "version": "1.15.0", + "license": "Apache-2.0", + "dependencies": { + "acorn": "^8.14.0", + "acorn-import-attributes": "^1.9.5", + "cjs-module-lexer": "^1.2.2", + "module-details-from-path": "^1.0.3" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/ingestion-service": { + "resolved": "apps/ingestion", + "link": true + }, + "node_modules/inherits": { + "version": "2.0.4", + "license": "ISC" + }, + "node_modules/ini": { + "version": "5.0.0", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/interface-service": { + "resolved": "apps/interface", + "link": true + }, + "node_modules/ioredis": { + "version": "5.8.2", + "license": "MIT", + "dependencies": { + "@ioredis/commands": "1.4.0", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "node_modules/ip-address": { + "version": "10.1.0", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-docker": { + "version": "2.2.1", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-lambda": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/is-number": { + "version": "7.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-promise": { + "version": "4.0.0", + "license": "MIT" + }, + "node_modules/is-stream": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-wsl": { + "version": "2.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "license": "ISC" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-report/node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", + "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.23", + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/its-fine": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "@types/react-reconciler": "^0.28.9" + }, + "peerDependencies": { + "react": "^19.0.0" + } + }, + "node_modules/its-fine/node_modules/@types/react-reconciler": { + "version": "0.28.9", + "license": "MIT", + "peerDependencies": { + "@types/react": "*" + } + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/jose": { + "version": "6.1.3", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/js-cookie": { + "version": "3.0.5", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "3.14.2", + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsbi": { + "version": "4.3.2", + "license": "Apache-2.0" + }, + "node_modules/jsdom": { + "version": "27.3.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-27.3.0.tgz", + "integrity": "sha512-GtldT42B8+jefDUC4yUKAvsaOrH7PDHmZxZXNgF2xMmymjUbRYJvpAybZAKEmXDGTM0mCsz8duOa4vTm5AY2Kg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@acemir/cssom": "^0.9.28", + "@asamuzakjp/dom-selector": "^6.7.6", + "cssstyle": "^5.3.4", + "data-urls": "^6.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "parse5": "^8.0.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^15.1.0", + "ws": "^8.18.3", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/jsdom/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/jsdom/node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/jsdom/node_modules/webidl-conversions": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.0.tgz", + "integrity": "sha512-n4W4YFyz5JzOfQeA8oN7dUYpR+MBP3PIUsn2jLjWXwK5ASUzt0Jc/A5sAUZoCYFJRGF0FBKJ+1JjN43rNdsQzA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/jsdom/node_modules/whatwg-url": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-15.1.0.tgz", + "integrity": "sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/json-schema": { + "version": "0.4.0", + "license": "(AFL-2.1 OR BSD-3-Clause)" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/json-stable-stringify": { + "version": "1.3.0", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "isarray": "^2.0.5", + "jsonify": "^0.0.1", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/json-stringify-nice": { + "version": "1.1.4", + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "license": "ISC" + }, + "node_modules/jsondiffpatch": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/jsondiffpatch/-/jsondiffpatch-0.6.0.tgz", + "integrity": "sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==", + "license": "MIT", + "dependencies": { + "@types/diff-match-patch": "^1.0.36", + "chalk": "^5.3.0", + "diff-match-patch": "^1.0.5" + }, + "bin": { + "jsondiffpatch": "bin/jsondiffpatch.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/jsondiffpatch/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/jsonfile": { + "version": "6.2.0", + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonify": { + "version": "0.0.1", + "dev": true, + "license": "Public Domain", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "engines": [ + "node >= 0.2.0" + ], + "license": "MIT" + }, + "node_modules/just-diff": { + "version": "6.0.2", + "license": "MIT" + }, + "node_modules/just-diff-apply": { + "version": "5.5.0", + "license": "MIT" + }, + "node_modules/jwa": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/klaw-sync": { + "version": "6.0.0", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.11" + } + }, + "node_modules/lie": { + "version": "3.3.0", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "license": "MIT" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "license": "MIT" + }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "license": "MIT" + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "6.0.0", + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "is-unicode-supported": "^1.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "5.6.2", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/is-unicode-supported": { + "version": "1.3.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/long": { + "version": "5.3.2", + "license": "Apache-2.0" + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lowercase-keys": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "license": "ISC" + }, + "node_modules/lucide-react": { + "version": "0.556.0", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/maath": { + "version": "0.10.8", + "license": "MIT", + "peerDependencies": { + "@types/three": ">=0.134.0", + "three": ">=0.134.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz", + "integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.25.4", + "@babel/types": "^7.25.4", + "source-map-js": "^1.2.0" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/make-fetch-happen": { + "version": "13.0.1", + "license": "ISC", + "dependencies": { + "@npmcli/agent": "^2.0.0", + "cacache": "^18.0.0", + "http-cache-semantics": "^4.1.1", + "is-lambda": "^1.0.1", + "minipass": "^7.0.2", + "minipass-fetch": "^3.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.3", + "proc-log": "^4.2.0", + "promise-retry": "^2.0.1", + "ssri": "^10.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/make-fetch-happen/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/make-fetch-happen/node_modules/negotiator": { + "version": "0.6.4", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/make-fetch-happen/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/matcher": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/matcher/node_modules/escape-string-regexp": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mdn-data": { + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.12.2.tgz", + "integrity": "sha512-IEn+pegP1aManZuckezWCO+XZQDplx1366JoVhTpMpBB1sPey/SbveZQUosKiKiGYjg1wH4pMlNgXbCiYgihQA==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/media-typer": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/memory-service": { + "resolved": "apps/memory", + "link": true + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/meshline": { + "version": "3.3.1", + "license": "MIT", + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/meshoptimizer": { + "version": "0.22.0", + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.8", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mimic-response": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "5.0.0", + "license": "ISC", + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-collect": { + "version": "2.0.1", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-collect/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-fetch": { + "version": "3.0.5", + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^1.0.3", + "minizlib": "^2.1.2" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + }, + "optionalDependencies": { + "encoding": "^0.1.13" + } + }, + "node_modules/minipass-fetch/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-flush": { + "version": "1.0.5", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-flush/node_modules/minipass": { + "version": "3.3.6", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/minipass": { + "version": "3.3.6", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-sized": { + "version": "1.0.3", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-sized/node_modules/minipass": { + "version": "3.3.6", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "license": "MIT", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mock-socket": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/mock-socket/-/mock-socket-9.3.1.tgz", + "integrity": "sha512-qxBgB7Qa2sEQgHFjj0dSigq7fX4k6Saisd5Nelwp2q8mlbAFh5dHV9JTTlF8viYJLSSWgMCZFUom8PJcMNBoJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "license": "MIT" + }, + "node_modules/nan": { + "version": "2.24.0", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/negotiator": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/next": { + "version": "16.0.8", + "license": "MIT", + "dependencies": { + "@next/env": "16.0.8", + "@swc/helpers": "0.5.15", + "caniuse-lite": "^1.0.30001579", + "postcss": "8.4.31", + "styled-jsx": "5.1.6" + }, + "bin": { + "next": "dist/bin/next" + }, + "engines": { + "node": ">=20.9.0" + }, + "optionalDependencies": { + "@next/swc-darwin-arm64": "16.0.8", + "@next/swc-darwin-x64": "16.0.8", + "@next/swc-linux-arm64-gnu": "16.0.8", + "@next/swc-linux-arm64-musl": "16.0.8", + "@next/swc-linux-x64-gnu": "16.0.8", + "@next/swc-linux-x64-musl": "16.0.8", + "@next/swc-win32-arm64-msvc": "16.0.8", + "@next/swc-win32-x64-msvc": "16.0.8", + "sharp": "^0.34.4" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.1.0", + "@playwright/test": "^1.51.1", + "babel-plugin-react-compiler": "*", + "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "sass": "^1.3.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@playwright/test": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "sass": { + "optional": true + } + } + }, + "node_modules/next-openapi-gen": { + "version": "0.8.9", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.3", + "@babel/traverse": "^7.28.3", + "@babel/types": "^7.28.2", + "commander": "^14.0.0", + "fs-extra": "^11.3.1", + "js-yaml": "^4.1.0", + "ora": "^8.2.0" + }, + "bin": { + "next-openapi-gen": "dist/index.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/next-openapi-gen/node_modules/argparse": { + "version": "2.0.1", + "license": "Python-2.0" + }, + "node_modules/next-openapi-gen/node_modules/fs-extra": { + "version": "11.3.2", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/next-openapi-gen/node_modules/js-yaml": { + "version": "4.1.1", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-gyp": { + "version": "10.3.1", + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "glob": "^10.3.10", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^13.0.0", + "nopt": "^7.0.0", + "proc-log": "^4.1.0", + "semver": "^7.3.5", + "tar": "^6.2.1", + "which": "^4.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/node-gyp/node_modules/abbrev": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/node-gyp/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/node-gyp/node_modules/glob": { + "version": "10.5.0", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/node-gyp/node_modules/isexe": { + "version": "3.1.1", + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/node-gyp/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/node-gyp/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/node-gyp/node_modules/nopt": { + "version": "7.2.1", + "license": "ISC", + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/node-gyp/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/node-gyp/node_modules/which": { + "version": "4.0.0", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^16.13.0 || >=18.0.0" + } + }, + "node_modules/nopt": { + "version": "5.0.0", + "license": "ISC", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/normalize-package-data": { + "version": "6.0.2", + "license": "BSD-2-Clause", + "dependencies": { + "hosted-git-info": "^7.0.0", + "semver": "^7.3.5", + "validate-npm-package-license": "^3.0.4" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/normalize-package-data/node_modules/hosted-git-info": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/normalize-url": { + "version": "6.1.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-bundled": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "npm-normalize-package-bin": "^3.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm-install-checks": { + "version": "6.3.0", + "license": "BSD-2-Clause", + "dependencies": { + "semver": "^7.1.1" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm-normalize-package-bin": { + "version": "3.0.1", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm-package-arg": { + "version": "11.0.3", + "license": "ISC", + "dependencies": { + "hosted-git-info": "^7.0.0", + "proc-log": "^4.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^5.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm-package-arg/node_modules/hosted-git-info": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm-package-arg/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm-packlist": { + "version": "8.0.2", + "license": "ISC", + "dependencies": { + "ignore-walk": "^6.0.4" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm-pick-manifest": { + "version": "10.0.0", + "license": "ISC", + "dependencies": { + "npm-install-checks": "^7.1.0", + "npm-normalize-package-bin": "^4.0.0", + "npm-package-arg": "^12.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm-pick-manifest/node_modules/npm-install-checks": { + "version": "7.1.2", + "license": "BSD-2-Clause", + "dependencies": { + "semver": "^7.1.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm-pick-manifest/node_modules/npm-normalize-package-bin": { + "version": "4.0.0", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm-pick-manifest/node_modules/npm-package-arg": { + "version": "12.0.2", + "license": "ISC", + "dependencies": { + "hosted-git-info": "^8.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^6.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm-pick-manifest/node_modules/validate-npm-package-name": { + "version": "6.0.2", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm-registry-fetch": { + "version": "17.1.0", + "license": "ISC", + "dependencies": { + "@npmcli/redact": "^2.0.0", + "jsonparse": "^1.3.1", + "make-fetch-happen": "^13.0.0", + "minipass": "^7.0.2", + "minipass-fetch": "^3.0.0", + "minizlib": "^2.1.2", + "npm-package-arg": "^11.0.0", + "proc-log": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm-registry-fetch/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/npm-registry-fetch/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npmlog": { + "version": "5.0.1", + "license": "ISC", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/onnxruntime-common": { + "version": "1.23.2", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.23.2", + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "adm-zip": "^0.5.16", + "global-agent": "^3.0.0", + "onnxruntime-common": "1.23.2" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.22.0-dev.20250409-89f8206ba4", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.22.0-dev.20250409-89f8206ba4", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { + "version": "1.22.0-dev.20250409-89f8206ba4", + "license": "MIT" + }, + "node_modules/open": { + "version": "7.4.2", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0", + "is-wsl": "^2.1.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora": { + "version": "8.2.0", + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "cli-cursor": "^5.0.0", + "cli-spinners": "^2.9.2", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^2.0.0", + "log-symbols": "^6.0.0", + "stdin-discarder": "^0.2.2", + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/ansi-regex": { + "version": "6.2.2", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "5.6.2", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ora/node_modules/emoji-regex": { + "version": "10.6.0", + "license": "MIT" + }, + "node_modules/ora/node_modules/string-width": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/strip-ansi": { + "version": "7.1.2", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/p-cancelable": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue": { + "version": "8.1.1", + "license": "MIT", + "dependencies": { + "eventemitter3": "^5.0.1", + "p-timeout": "^6.1.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "6.1.4", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/package-directory": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "find-up-simple": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "license": "BlueOak-1.0.0" + }, + "node_modules/pacote": { + "version": "18.0.6", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^5.0.0", + "@npmcli/installed-package-contents": "^2.0.1", + "@npmcli/package-json": "^5.1.0", + "@npmcli/promise-spawn": "^7.0.0", + "@npmcli/run-script": "^8.0.0", + "cacache": "^18.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^11.0.0", + "npm-packlist": "^8.0.0", + "npm-pick-manifest": "^9.0.0", + "npm-registry-fetch": "^17.0.0", + "proc-log": "^4.0.0", + "promise-retry": "^2.0.1", + "sigstore": "^2.2.0", + "ssri": "^10.0.0", + "tar": "^6.1.11" + }, + "bin": { + "pacote": "bin/index.js" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/@npmcli/git": { + "version": "5.0.8", + "license": "ISC", + "dependencies": { + "@npmcli/promise-spawn": "^7.0.0", + "ini": "^4.1.3", + "lru-cache": "^10.0.1", + "npm-pick-manifest": "^9.0.0", + "proc-log": "^4.0.0", + "promise-inflight": "^1.0.1", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/@npmcli/package-json": { + "version": "5.2.1", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^5.0.0", + "glob": "^10.2.2", + "hosted-git-info": "^7.0.0", + "json-parse-even-better-errors": "^3.0.0", + "normalize-package-data": "^6.0.0", + "proc-log": "^4.0.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/@npmcli/promise-spawn": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "which": "^4.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/brace-expansion": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/pacote/node_modules/fs-minipass": { + "version": "3.0.3", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/glob": { + "version": "10.5.0", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/pacote/node_modules/hosted-git-info": { + "version": "7.0.2", + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/ini": { + "version": "4.1.3", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/isexe": { + "version": "3.1.1", + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/pacote/node_modules/json-parse-even-better-errors": { + "version": "3.0.2", + "license": "MIT", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/pacote/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/pacote/node_modules/npm-pick-manifest": { + "version": "9.1.0", + "license": "ISC", + "dependencies": { + "npm-install-checks": "^6.0.0", + "npm-normalize-package-bin": "^3.0.0", + "npm-package-arg": "^11.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/proc-log": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/pacote/node_modules/which": { + "version": "4.0.0", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^16.13.0 || >=18.0.0" + } + }, + "node_modules/parse-conflict-json": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "json-parse-even-better-errors": "^3.0.0", + "just-diff": "^6.0.0", + "just-diff-apply": "^5.2.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/parse-conflict-json/node_modules/json-parse-even-better-errors": { + "version": "3.0.2", + "license": "MIT", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/parse5": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.0.tgz", + "integrity": "sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/patch-package": { + "version": "8.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "@yarnpkg/lockfile": "^1.1.0", + "chalk": "^4.1.2", + "ci-info": "^3.7.0", + "cross-spawn": "^7.0.3", + "find-yarn-workspace-root": "^2.0.0", + "fs-extra": "^10.0.0", + "json-stable-stringify": "^1.0.2", + "klaw-sync": "^6.0.0", + "minimist": "^1.2.6", + "open": "^7.4.2", + "semver": "^7.5.3", + "slash": "^2.0.0", + "tmp": "^0.2.4", + "yaml": "^2.2.2" + }, + "bin": { + "patch-package": "index.js" + }, + "engines": { + "node": ">=14", + "npm": ">5" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "license": "MIT" + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pino": { + "version": "10.1.0", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-pretty": { + "version": "13.1.3", + "license": "MIT", + "dependencies": { + "colorette": "^2.0.7", + "dateformat": "^4.6.3", + "fast-copy": "^4.0.0", + "fast-safe-stringify": "^2.1.1", + "help-me": "^5.0.0", + "joycon": "^3.1.1", + "minimist": "^1.2.6", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pump": "^3.0.0", + "secure-json-parse": "^4.0.0", + "sonic-boom": "^4.0.1", + "strip-json-comments": "^5.0.2" + }, + "bin": { + "pino-pretty": "bin.js" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.0.0", + "license": "MIT" + }, + "node_modules/pino/node_modules/pino-abstract-transport": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino/node_modules/thread-stream": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/platform": { + "version": "1.3.6", + "license": "MIT" + }, + "node_modules/postcss": { + "version": "8.4.31", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.6", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/potpack": { + "version": "1.0.2", + "license": "ISC" + }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/proc-log": { + "version": "5.0.0", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/process-warning": { + "version": "5.0.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/proggy": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/prom-client": { + "version": "15.1.3", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.4.0", + "tdigest": "^0.1.1" + }, + "engines": { + "node": "^16 || ^18 || >=20" + } + }, + "node_modules/promise-all-reject-late": { + "version": "1.0.1", + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/promise-call-limit": { + "version": "3.0.2", + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/promise-inflight": { + "version": "1.0.1", + "license": "ISC" + }, + "node_modules/promise-retry": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "err-code": "^2.0.2", + "retry": "^0.12.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/promise-retry/node_modules/retry": { + "version": "0.12.0", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/promise-worker-transferable": { + "version": "1.0.4", + "license": "Apache-2.0", + "dependencies": { + "is-promise": "^2.1.0", + "lie": "^3.0.2" + } + }, + "node_modules/promise-worker-transferable/node_modules/is-promise": { + "version": "2.2.2", + "license": "MIT" + }, + "node_modules/protobufjs": { + "version": "7.5.4", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pump": { + "version": "3.0.3", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "license": "MIT" + }, + "node_modules/quick-lru": { + "version": "5.1.1", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/react": { + "version": "19.2.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.1", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.1" + } + }, + "node_modules/react-dom/node_modules/scheduler": { + "version": "0.27.0", + "license": "MIT" + }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT" + }, + "node_modules/react-reconciler": { + "version": "0.31.0", + "license": "MIT", + "dependencies": { + "scheduler": "^0.25.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^19.0.0" + } + }, + "node_modules/react-use-measure": { + "version": "2.1.7", + "license": "MIT", + "peerDependencies": { + "react": ">=16.13", + "react-dom": ">=16.13" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/read-cmd-shim": { + "version": "4.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/read-package-json-fast": { + "version": "3.0.2", + "license": "ISC", + "dependencies": { + "json-parse-even-better-errors": "^3.0.0", + "npm-normalize-package-bin": "^3.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/read-package-json-fast/node_modules/json-parse-even-better-errors": { + "version": "3.0.2", + "license": "MIT", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/redis": { + "version": "4.7.1", + "license": "MIT", + "workspaces": [ + "./packages/*" + ], + "dependencies": { + "@redis/bloom": "1.2.0", + "@redis/client": "1.6.1", + "@redis/graph": "1.1.1", + "@redis/json": "1.0.7", + "@redis/search": "1.2.0", + "@redis/time-series": "1.1.0" + } + }, + "node_modules/redis-errors": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-in-the-middle": { + "version": "7.5.2", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "module-details-from-path": "^1.0.3", + "resolve": "^1.22.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/resolve": { + "version": "1.22.11", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-alpn": { + "version": "1.2.1", + "license": "MIT" + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/responselike": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "lowercase-keys": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/onetime": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/retry-request": { + "version": "7.0.2", + "license": "MIT", + "dependencies": { + "@types/request": "^2.48.8", + "extend": "^3.0.2", + "teeny-request": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/rimraf": { + "version": "3.0.2", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/roarr": { + "version": "2.15.4", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "detect-node": "^2.0.4", + "globalthis": "^1.0.1", + "json-stringify-safe": "^5.0.1", + "semver-compare": "^1.0.0", + "sprintf-js": "^1.1.2" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/roarr/node_modules/sprintf-js": { + "version": "1.1.3", + "license": "BSD-3-Clause" + }, + "node_modules/rollup": { + "version": "4.53.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz", + "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.53.3", + "@rollup/rollup-android-arm64": "4.53.3", + "@rollup/rollup-darwin-arm64": "4.53.3", + "@rollup/rollup-darwin-x64": "4.53.3", + "@rollup/rollup-freebsd-arm64": "4.53.3", + "@rollup/rollup-freebsd-x64": "4.53.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.53.3", + "@rollup/rollup-linux-arm-musleabihf": "4.53.3", + "@rollup/rollup-linux-arm64-gnu": "4.53.3", + "@rollup/rollup-linux-arm64-musl": "4.53.3", + "@rollup/rollup-linux-loong64-gnu": "4.53.3", + "@rollup/rollup-linux-ppc64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-gnu": "4.53.3", + "@rollup/rollup-linux-riscv64-musl": "4.53.3", + "@rollup/rollup-linux-s390x-gnu": "4.53.3", + "@rollup/rollup-linux-x64-gnu": "4.53.3", + "@rollup/rollup-linux-x64-musl": "4.53.3", + "@rollup/rollup-openharmony-arm64": "4.53.3", + "@rollup/rollup-win32-arm64-msvc": "4.53.3", + "@rollup/rollup-win32-ia32-msvc": "4.53.3", + "@rollup/rollup-win32-x64-gnu": "4.53.3", + "@rollup/rollup-win32-x64-msvc": "4.53.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/router": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/scheduler": { + "version": "0.25.0", + "license": "MIT" + }, + "node_modules/search-service": { + "resolved": "apps/search", + "link": true + }, + "node_modules/secure-json-parse": { + "version": "4.1.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/semver": { + "version": "7.7.3", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-compare": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.0", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/serialize-error": { + "version": "7.0.1", + "license": "MIT", + "dependencies": { + "type-fest": "^0.13.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/serve-static": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/server-only": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "license": "ISC" + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "license": "ISC" + }, + "node_modules/sharp": { + "version": "0.34.5", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/shimmer": { + "version": "1.2.1", + "license": "BSD-2-Clause" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "license": "ISC" + }, + "node_modules/sigstore": { + "version": "2.3.1", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^2.3.2", + "@sigstore/core": "^1.0.0", + "@sigstore/protobuf-specs": "^0.3.2", + "@sigstore/sign": "^2.3.2", + "@sigstore/tuf": "^2.3.4", + "@sigstore/verify": "^1.2.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/slash": { + "version": "2.0.0", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.7", + "license": "MIT", + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/socks-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.0", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/spdx-correct": { + "version": "3.2.0", + "license": "Apache-2.0", + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.5.0", + "license": "CC-BY-3.0" + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.22", + "license": "CC0-1.0" + }, + "node_modules/split2": { + "version": "4.2.0", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "license": "BSD-3-Clause" + }, + "node_modules/ssri": { + "version": "10.0.6", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/ssri/node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/standardwebhooks": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/stats-gl": { + "version": "2.4.2", + "license": "MIT", + "dependencies": { + "@types/three": "*", + "three": "^0.170.0" + }, + "peerDependencies": { + "@types/three": "*", + "three": "*" + } + }, + "node_modules/stats-gl/node_modules/three": { + "version": "0.170.0", + "license": "MIT" + }, + "node_modules/stats.js": { + "version": "0.17.0", + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "3.10.0", + "license": "MIT" + }, + "node_modules/stdin-discarder": { + "version": "0.2.2", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/stream-events": { + "version": "1.0.5", + "license": "MIT", + "dependencies": { + "stubs": "^3.0.0" + } + }, + "node_modules/stream-shift": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "5.0.3", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/strip-literal/node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/strnum": { + "version": "1.1.2", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/stubs": { + "version": "3.0.0", + "license": "MIT" + }, + "node_modules/styled-jsx": { + "version": "5.1.6", + "license": "MIT", + "dependencies": { + "client-only": "0.0.1" + }, + "engines": { + "node": ">= 12.0.0" + }, + "peerDependencies": { + "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/suspend-react": { + "version": "0.1.3", + "license": "MIT", + "peerDependencies": { + "react": ">=17.0" + } + }, + "node_modules/swr": { + "version": "2.3.7", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.3", + "use-sync-external-store": "^1.4.0" + }, + "peerDependencies": { + "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tar": { + "version": "6.2.1", + "license": "ISC", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tdigest": { + "version": "0.1.2", + "license": "MIT", + "dependencies": { + "bintrees": "1.0.2" + } + }, + "node_modules/teeny-request": { + "version": "9.0.0", + "license": "Apache-2.0", + "dependencies": { + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.9", + "stream-events": "^1.0.5", + "uuid": "^9.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/teeny-request/node_modules/http-proxy-agent": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/teeny-request/node_modules/uuid": { + "version": "9.0.1", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/test-exclude": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.1.tgz", + "integrity": "sha512-pFYqmTw68LXVjeWJMST4+borgQP2AyMNbg1BpZh9LbyhUeNkeaPF9gzfPGUAnSMV3qPYdWUwDIjjCLiSDOl7vg==", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^10.4.1", + "minimatch": "^9.0.4" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/test-exclude/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/test-exclude/node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/test-exclude/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/test-exclude/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/thread-stream": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/three": { + "version": "0.181.2", + "license": "MIT" + }, + "node_modules/three-mesh-bvh": { + "version": "0.8.3", + "license": "MIT", + "peerDependencies": { + "three": ">= 0.159.0" + } + }, + "node_modules/three-stdlib": { + "version": "2.36.1", + "license": "MIT", + "dependencies": { + "@types/draco3d": "^1.4.0", + "@types/offscreencanvas": "^2019.6.4", + "@types/webxr": "^0.5.2", + "draco3d": "^1.4.1", + "fflate": "^0.6.9", + "potpack": "^1.0.1" + }, + "peerDependencies": { + "three": ">=0.128.0" + } + }, + "node_modules/three-stdlib/node_modules/fflate": { + "version": "0.6.10", + "license": "MIT" + }, + "node_modules/throttleit": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-2.1.0.tgz", + "integrity": "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz", + "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.0.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.19.tgz", + "integrity": "sha512-8PWx8tvC4jDB39BQw1m4x8y5MH1BcQ5xHeL2n7UVFulMPH/3Q0uiamahFJ3lXA0zO2SUyRXuVVbWSDmstlt9YA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.0.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.0.19", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.19.tgz", + "integrity": "sha512-lJX2dEWx0SGH4O6p+7FPwYmJ/bu1JbcGJ8RLaG9b7liIgZ85itUVEPbMtWRVrde/0fnDPEPHW10ZsKW3kVsE9A==", + "dev": true, + "license": "MIT" + }, + "node_modules/tmp": { + "version": "0.2.5", + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tough-cookie": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.0.tgz", + "integrity": "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "license": "MIT" + }, + "node_modules/treeverse": { + "version": "3.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/troika-three-text": { + "version": "0.52.4", + "license": "MIT", + "dependencies": { + "bidi-js": "^1.0.2", + "troika-three-utils": "^0.52.4", + "troika-worker-utils": "^0.52.0", + "webgl-sdf-generator": "1.1.1" + }, + "peerDependencies": { + "three": ">=0.125.0" + } + }, + "node_modules/troika-three-utils": { + "version": "0.52.4", + "license": "MIT", + "peerDependencies": { + "three": ">=0.125.0" + } + }, + "node_modules/troika-worker-utils": { + "version": "0.52.0", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "license": "0BSD" + }, + "node_modules/tsx": { + "version": "4.21.0", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.27.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/tuf-js": { + "version": "2.2.1", + "license": "MIT", + "dependencies": { + "@tufjs/models": "2.0.1", + "debug": "^4.3.4", + "make-fetch-happen": "^13.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/tunnel-rat": { + "version": "0.1.2", + "license": "MIT", + "dependencies": { + "zustand": "^4.3.2" + } + }, + "node_modules/tunnel-rat/node_modules/zustand": { + "version": "4.5.7", + "license": "MIT", + "dependencies": { + "use-sync-external-store": "^1.2.2" + }, + "engines": { + "node": ">=12.7.0" + }, + "peerDependencies": { + "@types/react": ">=16.8", + "immer": ">=9.0.6", + "react": ">=16.8" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/turbo": { + "version": "2.6.3", + "dev": true, + "license": "MIT", + "bin": { + "turbo": "bin/turbo" + }, + "optionalDependencies": { + "turbo-darwin-64": "2.6.3", + "turbo-darwin-arm64": "2.6.3", + "turbo-linux-64": "2.6.3", + "turbo-linux-arm64": "2.6.3", + "turbo-windows-64": "2.6.3", + "turbo-windows-arm64": "2.6.3" + } + }, + "node_modules/turbo-darwin-64": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/turbo-darwin-64/-/turbo-darwin-64-2.6.3.tgz", + "integrity": "sha512-BlJJDc1CQ7SK5Y5qnl7AzpkvKSnpkfPmnA+HeU/sgny3oHZckPV2776ebO2M33CYDSor7+8HQwaodY++IINhYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/turbo-darwin-arm64": { + "version": "2.6.3", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/turbo-linux-64": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/turbo-linux-64/-/turbo-linux-64-2.6.3.tgz", + "integrity": "sha512-cqpcw+dXxbnPtNnzeeSyWprjmuFVpHJqKcs7Jym5oXlu/ZcovEASUIUZVN3OGEM6Y/OTyyw0z09tOHNt5yBAVg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/turbo-linux-arm64": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/turbo-linux-arm64/-/turbo-linux-arm64-2.6.3.tgz", + "integrity": "sha512-MterpZQmjXyr4uM7zOgFSFL3oRdNKeflY7nsjxJb2TklsYqiu3Z9pQ4zRVFFH8n0mLGna7MbQMZuKoWqqHb45w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/turbo-windows-64": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/turbo-windows-64/-/turbo-windows-64-2.6.3.tgz", + "integrity": "sha512-biDU70v9dLwnBdLf+daoDlNJVvqOOP8YEjqNipBHzgclbQlXbsi6Gqqelp5er81Qo3BiRgmTNx79oaZQTPb07Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/turbo-windows-arm64": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/turbo-windows-arm64/-/turbo-windows-arm64-2.6.3.tgz", + "integrity": "sha512-dDHVKpSeukah3VsI/xMEKeTnV9V9cjlpFSUs4bmsUiLu3Yv2ENlgVEZv65wxbeE0bh0jjpmElDT+P1KaCxArQQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/type-fest": { + "version": "0.13.1", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ulid": { + "version": "3.0.2", + "license": "MIT", + "bin": { + "ulid": "dist/cli.js" + } + }, + "node_modules/undici": { + "version": "6.22.0", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "license": "MIT" + }, + "node_modules/unique-filename": { + "version": "3.0.0", + "license": "ISC", + "dependencies": { + "unique-slug": "^4.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/unique-slug": { + "version": "4.0.0", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/upath": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=4", + "yarn": "*" + } + }, + "node_modules/urlpattern-polyfill": { + "version": "10.1.0", + "license": "MIT" + }, + "node_modules/use-sync-external-store": { + "version": "1.6.0", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/utility-types": { + "version": "3.11.0", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "license": "Apache-2.0", + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/validate-npm-package-name": { + "version": "5.0.1", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vite": { + "version": "7.2.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.2.7.tgz", + "integrity": "sha512-ITcnkFeR3+fI8P1wMgItjGrR10170d8auB4EpMLPqmx6uxElH3a/hHGQabSHKdqd4FXWO1nFIp9rRn7JQ34ACQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vite/node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite/node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/vite/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/vite/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vite/node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/vitest": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", + "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.4", + "@vitest/mocker": "3.2.4", + "@vitest/pretty-format": "^3.2.4", + "@vitest/runner": "3.2.4", + "@vitest/snapshot": "3.2.4", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.4", + "@vitest/ui": "3.2.4", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vitest-websocket-mock": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/vitest-websocket-mock/-/vitest-websocket-mock-0.5.0.tgz", + "integrity": "sha512-vzBWeuF/kD/OCOFzB7WAclb7PxfI105qPkZtdOkPMwZdilBskQjJL4l319JtPtmeovDU7ZVhO3hTfGPjM4txQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "^3.0.0", + "mock-socket": "^9.2.1" + }, + "peerDependencies": { + "vitest": ">=3" + } + }, + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/walk-up-path": { + "version": "3.0.1", + "license": "ISC" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/webgl-constants": { + "version": "1.1.1" + }, + "node_modules/webgl-sdf-generator": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "license": "ISC", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "5.0.1", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/write-file-atomic/node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ws": { + "version": "8.18.3", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, + "node_modules/xstate": { + "version": "5.24.0", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/xstate" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.8.2", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.1.13", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.0", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + }, + "node_modules/zustand": { + "version": "5.0.9", + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + }, + "packages/benchmark": { + "name": "@engram/benchmark", + "version": "0.0.0", + "dependencies": { + "@ai-sdk/google": "^1.2.18", + "@engram/graph": "*", + "@engram/search": "*", + "@engram/storage": "*", + "@qdrant/js-client-rest": "^1.16.2", + "ai": "^4.3.16", + "commander": "^14.0.0", + "falkordb": "^6.4.1", + "zod": "^4.1.13" + }, + "bin": { + "engram-benchmark": "src/cli/index.ts" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + }, + "optionalDependencies": { + "@anthropic-ai/sdk": "^0.52.0", + "@google/genai": "^1.0.0" + } + }, + "packages/benchmark/node_modules/@ai-sdk/provider": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz", + "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==", + "license": "Apache-2.0", + "dependencies": { + "json-schema": "^0.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "packages/benchmark/node_modules/@ai-sdk/provider-utils": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-2.2.8.tgz", + "integrity": "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "nanoid": "^3.3.8", + "secure-json-parse": "^2.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.23.8" + } + }, + "packages/benchmark/node_modules/ai": { + "version": "4.3.19", + "resolved": "https://registry.npmjs.org/ai/-/ai-4.3.19.tgz", + "integrity": "sha512-dIE2bfNpqHN3r6IINp9znguYdhIOheKW2LDigAMrgt/upT3B8eBGPSCblENvaZGoq+hxaN9fSMzjWpbqloP+7Q==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "@ai-sdk/provider-utils": "2.2.8", + "@ai-sdk/react": "1.2.12", + "@ai-sdk/ui-utils": "1.2.11", + "@opentelemetry/api": "1.9.0", + "jsondiffpatch": "0.6.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "^18 || ^19 || ^19.0.0-rc", + "zod": "^3.23.8" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + } + } + }, + "packages/benchmark/node_modules/falkordb": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/falkordb/-/falkordb-6.4.1.tgz", + "integrity": "sha512-dBoTbRars4TR0SYAQvIV3zUloWG3HlDr6LOYK0V2CscOKbpFUyJ9oBRpYfGY1DmHmP5RfZs/3sjT8EUuzcbI+A==", + "license": "MIT", + "workspaces": [ + "./packages/*" + ], + "dependencies": { + "@js-temporal/polyfill": "^0.5.1", + "@redis/client": "^1.6.0", + "cluster-key-slot": "1.1.2", + "generic-pool": "^3.9.0", + "lodash": "^4.17.21", + "redis": "^4.7.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "packages/benchmark/node_modules/secure-json-parse": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", + "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", + "license": "BSD-3-Clause" + }, + "packages/common": { + "name": "@engram/common", + "version": "0.0.0", + "dependencies": { + "@engram/graph": "*", + "@engram/storage": "*" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3", + "vitest": "^3.2.3" + } + }, + "packages/events": { + "name": "@engram/events", + "version": "0.0.0", + "dependencies": { + "zod": "^3.23.4" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/execution-core": { + "name": "@engram/execution-core", + "version": "0.0.0", + "extraneous": true, + "dependencies": { + "@engram/storage": "*", + "@engram/vfs": "*", + "zod": "^3.25.76" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/graph": { + "name": "@engram/graph", + "version": "0.0.0", + "dependencies": { + "@engram/storage": "*", + "ulid": "^3.0.2", + "zod": "^4.1.13" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/infra": { + "name": "@engram/infra", + "version": "0.0.0", + "dependencies": { + "@pulumi/gcp": "^9.6.0", + "@pulumi/kubernetes": "^4.24.1", + "@pulumi/pulumi": "^3.210.0" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1" + } + }, + "packages/ingestion-core": { + "name": "@engram/ingestion-core", + "version": "0.0.0", + "extraneous": true, + "dependencies": { + "@engram/common": "*", + "@engram/events": "*", + "zod": "^4.1.13" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/logger": { + "name": "@engram/logger", + "version": "0.0.0", + "dependencies": { + "pino": "^10.1.0", + "pino-pretty": "^13.1.3" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/memory-core": { + "name": "@engram/memory-core", + "version": "0.0.0", + "extraneous": true, + "dependencies": { + "@engram/storage": "*", + "ulid": "^3.0.2", + "zod": "^4.1.13" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/parser": { + "name": "@engram/parser", + "version": "0.0.0", + "dependencies": { + "@engram/common": "*", + "@engram/events": "*", + "zod": "^4.1.13" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/search": { + "name": "@engram/search", + "version": "0.0.0", + "dependencies": { + "@ai-sdk/google": "^1.2.18", + "@engram/common": "*", + "@engram/logger": "*", + "@huggingface/transformers": "^3.8.1", + "@qdrant/js-client-rest": "^1.16.2", + "ai": "^4.3.16", + "chrono-node": "^2.9.0", + "ioredis": "^5.8.2", + "p-queue": "^8.0.1", + "prom-client": "^15.1.3", + "zod": "^4.1.13" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/search-core": { + "name": "@engram/search-core", + "version": "0.0.0", + "extraneous": true, + "dependencies": { + "@engram/common": "*", + "@engram/logger": "*", + "@huggingface/transformers": "^3.8.1", + "@qdrant/js-client-rest": "^1.16.2", + "chrono-node": "^2.9.0", + "ioredis": "^5.8.2", + "p-queue": "^8.0.1", + "prom-client": "^15.1.3", + "zod": "^4.1.13" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/search/node_modules/@ai-sdk/provider": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz", + "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==", + "license": "Apache-2.0", + "dependencies": { + "json-schema": "^0.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "packages/search/node_modules/@ai-sdk/provider-utils": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-2.2.8.tgz", + "integrity": "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "nanoid": "^3.3.8", + "secure-json-parse": "^2.7.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.23.8" + } + }, + "packages/search/node_modules/ai": { + "version": "4.3.19", + "resolved": "https://registry.npmjs.org/ai/-/ai-4.3.19.tgz", + "integrity": "sha512-dIE2bfNpqHN3r6IINp9znguYdhIOheKW2LDigAMrgt/upT3B8eBGPSCblENvaZGoq+hxaN9fSMzjWpbqloP+7Q==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "1.1.3", + "@ai-sdk/provider-utils": "2.2.8", + "@ai-sdk/react": "1.2.12", + "@ai-sdk/ui-utils": "1.2.11", + "@opentelemetry/api": "1.9.0", + "jsondiffpatch": "0.6.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "^18 || ^19 || ^19.0.0-rc", + "zod": "^3.23.8" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + } + } + }, + "packages/search/node_modules/secure-json-parse": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz", + "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==", + "license": "BSD-3-Clause" + }, + "packages/storage": { + "name": "@engram/storage", + "version": "0.0.0", + "dependencies": { + "@google-cloud/storage": "^7.14.0", + "falkordb": "^6.3.1", + "redis": "^5.10.0" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/storage/node_modules/@redis/bloom": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-5.10.0.tgz", + "integrity": "sha512-doIF37ob+l47n0rkpRNgU8n4iacBlKM9xLiP1LtTZTvz8TloJB8qx/MgvhMhKdYG+CvCY2aPBnN2706izFn/4A==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.10.0" + } + }, + "packages/storage/node_modules/@redis/client": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-5.10.0.tgz", + "integrity": "sha512-JXmM4XCoso6C75Mr3lhKA3eNxSzkYi3nCzxDIKY+YOszYsJjuKbFgVtguVPbLMOttN4iu2fXoc2BGhdnYhIOxA==", + "license": "MIT", + "dependencies": { + "cluster-key-slot": "1.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "packages/storage/node_modules/@redis/json": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-5.10.0.tgz", + "integrity": "sha512-B2G8XlOmTPUuZtD44EMGbtoepQG34RCDXLZbjrtON1Djet0t5Ri7/YPXvL9aomXqP8lLTreaprtyLKF4tmXEEA==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.10.0" + } + }, + "packages/storage/node_modules/@redis/search": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-5.10.0.tgz", + "integrity": "sha512-3SVcPswoSfp2HnmWbAGUzlbUPn7fOohVu2weUQ0S+EMiQi8jwjL+aN2p6V3TI65eNfVsJ8vyPvqWklm6H6esmg==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.10.0" + } + }, + "packages/storage/node_modules/@redis/time-series": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-5.10.0.tgz", + "integrity": "sha512-cPkpddXH5kc/SdRhF0YG0qtjL+noqFT0AcHbQ6axhsPsO7iqPi1cjxgdkE9TNeKiBUUdCaU1DbqkR/LzbzPBhg==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.10.0" + } + }, + "packages/storage/node_modules/redis": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/redis/-/redis-5.10.0.tgz", + "integrity": "sha512-0/Y+7IEiTgVGPrLFKy8oAEArSyEJkU0zvgV5xyi9NzNQ+SLZmyFbUsWIbgPcd4UdUh00opXGKlXJwMmsis5Byw==", + "license": "MIT", + "dependencies": { + "@redis/bloom": "5.10.0", + "@redis/client": "5.10.0", + "@redis/json": "5.10.0", + "@redis/search": "5.10.0", + "@redis/time-series": "5.10.0" + }, + "engines": { + "node": ">= 18" + } + }, + "packages/temporal": { + "name": "@engram/temporal", + "version": "0.0.0", + "dependencies": { + "@engram/storage": "*", + "@engram/vfs": "*", + "zod": "^3.25.76" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/tsconfig": { + "name": "@engram/tsconfig", + "version": "0.0.0" + }, + "packages/tuner": { + "name": "@engram/tuner", + "version": "0.0.0", + "dependencies": { + "@engram/benchmark": "*", + "@engram/common": "*", + "@engram/logger": "*", + "@engram/search": "*", + "commander": "^14.0.0", + "zod": "^4.1.13" + }, + "bin": { + "engram-tuner": "src/cli/index.ts" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + }, + "packages/vfs": { + "name": "@engram/vfs", + "version": "0.0.0", + "dependencies": { + "@types/diff": "^8.0.0", + "diff": "^8.0.2" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f0279af25aef9090d95a0d0f434cbb70d0ef1174 --- /dev/null +++ b/package.json @@ -0,0 +1,46 @@ +{ + "name": "engram", + "version": "0.0.0", + "private": true, + "workspaces": [ + "apps/*", + "packages/*", + "tooling/*" + ], + "overrides": { + "zod": "$zod" + }, + "scripts": { + "build": "turbo run build", + "typecheck": "turbo run typecheck", + "dev": "turbo run dev", + "lint": "biome check --write .", + "format": "biome format --write .", + "test": "vitest run", + "infra:up": "docker-compose -f docker-compose.dev.yml up -d", + "infra:down": "docker-compose -f docker-compose.dev.yml down", + "prepare": "husky" + }, + "devDependencies": { + "@biomejs/biome": "^2.3.8", + "@engram/events": "*", + "@engram/storage": "*", + "@modelcontextprotocol/sdk": "^1.24.3", + "@qdrant/js-client-rest": "^1.16.2", + "@vitest/coverage-v8": "^3.2.4", + "falkordb": "^6.3.1", + "husky": "^9.1.7", + "jsdom": "^27.3.0", + "patch-package": "^8.0.1", + "pino-pretty": "^13.1.3", + "tsx": "^4.21.0", + "turbo": "^2.6.3", + "typescript": "^5.9.3", + "vitest": "^3.2.3", + "zod": "^4.1.13" + }, + "packageManager": "npm@11.4.1", + "dependencies": { + "@confluentinc/kafka-javascript": "^1.7.0" + } +} diff --git a/packages/benchmark/Dockerfile b/packages/benchmark/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7d397e438a316a85d0ecb093121ef158c7f6dd32 --- /dev/null +++ b/packages/benchmark/Dockerfile @@ -0,0 +1,181 @@ +# ============================================================================= +# Engram Benchmark Container +# ============================================================================= +# GPU-enabled container for running LongMemEval benchmarks with all Engram +# features enabled. Uses NVIDIA L4 GPU in Cloud Run. +# +# Build: +# docker build -t engram-benchmark . +# +# Run locally (CPU): +# docker run --rm engram-benchmark --help +# +# Run with GPU: +# docker run --rm --gpus all engram-benchmark +# +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Stage 1: Build dependencies +# ----------------------------------------------------------------------------- +FROM node:24-bookworm-slim AS builder + +WORKDIR /app + +# Install build essentials for native modules +RUN apt-get update && apt-get install -y \ + python3 \ + make \ + g++ \ + git \ + && rm -rf /var/lib/apt/lists/* + +# Copy package files for dependency installation +COPY package*.json ./ +COPY packages/benchmark/package.json packages/benchmark/ +COPY packages/search/package.json packages/search/ +COPY packages/graph/package.json packages/graph/ +COPY packages/storage/package.json packages/storage/ +COPY packages/logger/package.json packages/logger/ +COPY packages/common/package.json packages/common/ +COPY packages/temporal/package.json packages/temporal/ + +# Install all dependencies +RUN npm install --include=dev + +# Copy source code +COPY packages/ packages/ +COPY biome.json ./ + +# Skip typecheck in Docker build (already validated locally) +# The onnxruntime-node types are provided by @huggingface/transformers at runtime + +# ----------------------------------------------------------------------------- +# Stage 2: Runtime image with CUDA support +# ----------------------------------------------------------------------------- +# Using CUDA 12.3.2 with cuDNN 9 for ONNX Runtime GPU support (embedding models, rerankers) +# cuDNN 9 is required by onnxruntime-node; only available with CUDA 12.3.2 on Ubuntu 22.04 +FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04 + +# Install Node.js 24 +RUN apt-get update && apt-get install -y \ + curl \ + ca-certificates \ + && curl -fsSL https://deb.nodesource.com/setup_24.x | bash - \ + && apt-get install -y nodejs \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +# Copy built application from builder +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/packages ./packages +COPY --from=builder /app/package*.json ./ + +# Reinstall native modules for the runtime platform (needed for cross-platform builds) +# sharp and onnxruntime-node have native bindings that must match the runtime architecture +RUN npm install --os=linux --cpu=x64 sharp + +# Model cache directory - set before preloading +ENV HF_HOME=/app/.cache +ENV TRANSFORMERS_CACHE=/app/.cache +ENV XDG_CACHE_HOME=/app/.cache + +# Pre-download HuggingFace models at build time to avoid runtime download issues +# Models are cached in /app/.cache and included in the image +# Download q8 quantized models for CPU mode (4x smaller than FP32, fits in 24GB RAM) +RUN mkdir -p /app/.cache && \ + node -e "const { pipeline } = require('@huggingface/transformers'); \ + (async () => { \ + console.log('Pre-downloading embedding models (q8 quantized for CPU)...'); \ + await pipeline('feature-extraction', 'Xenova/multilingual-e5-large', { dtype: 'q8' }); \ + await pipeline('feature-extraction', 'Xenova/multilingual-e5-small', { dtype: 'q8' }); \ + console.log('Pre-downloading reranker models...'); \ + await pipeline('text-classification', 'Xenova/ms-marco-MiniLM-L-6-v2', { dtype: 'q8' }); \ + console.log('Models pre-downloaded successfully'); \ + })().catch(e => { console.error('Model preload failed:', e); process.exit(1); });" + +# Create non-root user for security +RUN groupadd -r engram && useradd -r -g engram engram \ + && mkdir -p /data /results \ + && chown -R engram:engram /app /data /results + +USER engram + +# Environment configuration +ENV NODE_ENV=production +ENV BENCHMARK_VERBOSE=true +# Increase Node.js heap size (default ~4GB is too small for loading multiple models) +ENV NODE_OPTIONS="--max-old-space-size=16384" + +# Force CPU mode to avoid ONNX Runtime CUDA memory allocation issues +# The BFC arena in CUDAExecutionProvider allocates 4-10x model size +# which causes OOM even with 24GB VRAM when loading multiple models +# Use q8 quantized models (4x smaller than FP32) to fit in 24GB RAM +ENV EMBEDDER_DEVICE=cpu +ENV EMBEDDER_DTYPE=q8 + +# Default command runs full benchmark with ALL features enabled +ENTRYPOINT ["npx", "tsx", "packages/benchmark/src/cli/index.ts"] + +# ============================================================================= +# FULL ENGRAM BENCHMARK - ALL FEATURES ENABLED +# ============================================================================= +# This command enables every Engram optimization for maximum retrieval quality: +# +# Retrieval: +# - Dense embeddings (E5-large, 1024d) - SOTA multilingual +# - Sparse embeddings (SPLADE) +# - Hybrid search with RRF fusion +# - Multi-query expansion (3 variations) +# - Session-aware hierarchical retrieval +# - Temporal query parsing (chrono-node) +# +# Reranking: +# - Cross-encoder reranking (accurate tier) +# - Deep candidate pool (50 docs) +# +# Reading: +# - Chain-of-Note structured reasoning +# - Time-aware query expansion +# +# Abstention (3-layer): +# - Layer 1: Low retrieval confidence +# - Layer 2: NLI answer grounding +# - Layer 3: Hedging pattern detection +# +# Optimization: +# - Key expansion with fact extraction +# - Temporal analysis +# +# ============================================================================= +CMD ["run", "longmemeval", \ + "--dataset", "/data/longmemeval_oracle.json", \ + "--variant", "oracle", \ + "--embeddings", "engram", \ + "--llm", "gemini", \ + "--gemini-model", "gemini-3-flash-preview", \ + "--top-k", "10", \ + "--hybrid-search", \ + "--rerank", \ + "--rerank-tier", "accurate", \ + "--rerank-depth", "50", \ + "--multi-query", \ + "--multi-query-variations", "3", \ + "--session-aware", \ + "--top-sessions", "5", \ + "--turns-per-session", "3", \ + "--temporal-aware", \ + "--temporal-confidence-threshold", "0.5", \ + "--abstention", \ + "--abstention-threshold", "0.3", \ + "--abstention-hedging", \ + "--abstention-nli", \ + "--abstention-nli-threshold", "0.7", \ + "--key-expansion", \ + "--temporal-analysis", \ + "--chain-of-note", \ + "--time-aware", \ + "--embedding-model", "e5-small", \ + "--verbose", \ + "--output", "/results/benchmark-results.jsonl"] diff --git a/packages/benchmark/README.md b/packages/benchmark/README.md new file mode 100644 index 0000000000000000000000000000000000000000..88d3de97762ffc73446e3dfe0c97df24e961e269 --- /dev/null +++ b/packages/benchmark/README.md @@ -0,0 +1,269 @@ +# @engram/benchmark + +[![LongMemEval](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ccheney/engram/main/.github/benchmark-history/badge.json)](https://github.com/ccheney/engram/actions/workflows/benchmark.yml) + +Benchmark suite for evaluating Engram's memory system against industry-standard benchmarks. + +## Supported Benchmarks + +### LongMemEval (ICLR 2025) + +[LongMemEval](https://github.com/xiaowu0162/LongMemEval) tests 5 core memory abilities: + +| Ability | Code | Description | +|:--------|:-----|:------------| +| Information Extraction | IE | Recall specific facts from history | +| Multi-Session Reasoning | MR | Synthesize across sessions | +| Temporal Reasoning | TR | Use timestamps and temporal refs | +| Knowledge Update | KU | Handle contradictory info over time | +| Abstention | ABS | Recognize unanswerable questions | + +## Quick Start + +### 1. Download the Dataset + +```bash +cd packages/benchmark/data + +# Oracle dataset (smallest, ~500 questions with evidence only) +curl -L -o longmemeval_oracle.json \ + "https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned/resolve/main/longmemeval_oracle.json" + +# Small dataset (~115k tokens, ~40 sessions) +curl -L -o longmemeval_s_cleaned.json \ + "https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned/resolve/main/longmemeval_s_cleaned.json" +``` + +### 2. Validate the Dataset + +```bash +npx tsx src/cli/index.ts validate data/longmemeval_oracle.json +``` + +### 3. Run the Benchmark + +```bash +# Quick test with stub providers +npx tsx src/cli/index.ts run longmemeval \ + --dataset data/longmemeval_oracle.json \ + --limit 10 \ + --verbose + +# Full run with E5 embeddings +npx tsx src/cli/index.ts run longmemeval \ + --dataset data/longmemeval_oracle.json \ + --embeddings e5 \ + --llm anthropic \ + --chain-of-note \ + --key-expansion \ + --temporal-analysis \ + --output results/benchmark.jsonl +``` + +### Let Engram Cook (Full Pipeline) + +Run the complete Engram retrieval pipeline with **all optimizations enabled**: + +```bash +# Ensure infrastructure is running +docker ps | grep qdrant || npm run infra:up + +# Full Engram pipeline - EVERY FEATURE ENABLED +GOOGLE_GENERATIVE_AI_API_KEY="..." NODE_OPTIONS="--max-old-space-size=8192" \ +npx tsx src/cli/index.ts run longmemeval \ + --dataset data/longmemeval_oracle.json \ + --variant oracle \ + --embeddings engram \ + --llm gemini \ + --gemini-model gemini-3-flash-preview \ + --top-k 10 \ + --hybrid-search \ + --rerank \ + --rerank-tier accurate \ + --rerank-depth 50 \ + --multi-query \ + --multi-query-variations 3 \ + --session-aware \ + --top-sessions 5 \ + --turns-per-session 3 \ + --temporal-aware \ + --temporal-confidence-threshold 0.5 \ + --abstention \ + --abstention-threshold 0.3 \ + --abstention-hedging \ + --abstention-nli \ + --abstention-nli-threshold 0.7 \ + --key-expansion \ + --temporal-analysis \ + --chain-of-note \ + --time-aware \ + --embedding-model e5-small \ + --verbose \ + --debug-retrieval \ + --output results/engram-full-$(date +%Y%m%d).jsonl +``` + +**What this enables:** + +| Category | Feature | Description | +|:---------|:--------|:------------| +| **Retrieval** | Dense embeddings | E5-small (384d) | +| | Sparse embeddings | SPLADE learned sparse | +| | Hybrid search | Dense + Sparse + RRF fusion | +| | Multi-query | Query expansion with 3 variations | +| | Session-aware | Hierarchical session→turn retrieval | +| | Temporal parsing | chrono-node date extraction | +| **Reranking** | Cross-encoder | Accurate tier (deeper model) | +| | Rerank depth | 50 candidates before reranking | +| **Reading** | Chain-of-Note | Structured evidence reasoning | +| | Time-aware | Temporal query expansion | +| **Abstention** | Layer 1 | Low retrieval confidence detection | +| | Layer 2 | NLI answer grounding check | +| | Layer 3 | Hedging pattern detection | +| **Optimization** | Key expansion | Fact extraction (+9% recall) | +| | Temporal analysis | Time-aware queries (+7-11% TR) | +| **Debug** | Debug retrieval | Show retrieved vs expected docs | + +### 4. Evaluate Results + +```bash +npx tsx src/cli/index.ts evaluate \ + --hypothesis results/benchmark.jsonl \ + --ground-truth data/longmemeval_oracle.json \ + --output results/metrics.json +``` + +## CLI Options + +### `run` Command + +| Option | Description | Default | +|:-------|:------------|:--------| +| `-d, --dataset ` | Path to dataset file | Required | +| `-v, --variant ` | Dataset variant | `s` | +| `-o, --output ` | Output file for results | - | +| `-l, --limit ` | Limit number of instances | - | +| `-k, --top-k ` | Documents to retrieve | `10` | +| `--retriever ` | dense, bm25, hybrid | `dense` | +| `--chain-of-note` | Enable Chain-of-Note | `false` | +| `--time-aware` | Enable time-aware query expansion | `false` | +| `--key-expansion` | Enable key expansion (+9% recall) | `false` | +| `--temporal-analysis` | Enable temporal analysis (+7-11% TR) | `false` | +| `--embeddings ` | stub, qdrant, e5, engram | `stub` | +| `--llm ` | stub, anthropic, openai, ollama | `stub` | + +#### Engram Pipeline Options (when `--embeddings engram`) + +| Option | Description | Default | +|:-------|:------------|:--------| +| `--hybrid-search` | Enable hybrid search (dense + SPLADE + RRF) | `true` | +| `--rerank` | Enable cross-encoder reranking | `true` | +| `--rerank-tier ` | Reranker: fast, accurate, code, colbert | `fast` | +| `--rerank-depth ` | Candidates to fetch before reranking | `30` | +| `--qdrant-url ` | Qdrant server URL | `http://localhost:6333` | + +### `evaluate` Command + +| Option | Description | +|:-------|:------------| +| `-h, --hypothesis ` | Path to hypothesis JSONL | +| `-g, --ground-truth ` | Path to ground truth dataset | +| `-o, --output ` | Output file for metrics | +| `--llm-eval` | Use LLM-based evaluation | + +## Metrics + +### QA Metrics + +- **Overall Accuracy**: Percentage of correct answers +- **Per-Ability Accuracy**: Breakdown by IE, MR, TR, KU, ABS + +### Retrieval Metrics + +- **Recall@K**: Percentage of evidence retrieved at K={1,5,10} +- **NDCG@K**: Normalized Discounted Cumulative Gain +- **MRR**: Mean Reciprocal Rank + +### Abstention Metrics + +- **Precision**: Correct abstentions / Total abstentions +- **Recall**: Correct abstentions / Questions requiring abstention +- **F1 Score**: Harmonic mean of precision and recall + +## Optimizations + +Based on [LongMemEval paper](https://arxiv.org/abs/2410.10813) findings: + +| Optimization | Improvement | Flag | +|:-------------|:------------|:-----| +| Chain-of-Note | +10 points QA | `--chain-of-note` | +| Key Expansion | +9.4% recall | `--key-expansion` | +| Time-Aware Queries | +7-11% on TR | `--temporal-analysis` | + +## GPU Deployment (Hugging Face Spaces) + +For GPU-accelerated benchmark runs, deploy to Hugging Face Spaces with L4 GPU ($0.80/hr): + +```bash +# Install HF CLI +pip install huggingface_hub + +# Login +huggingface-cli login + +# Deploy +cd packages/benchmark/hf-space +./deploy.sh ccheney/engram-benchmark +``` + +Then: +1. Set `GOOGLE_GENERATIVE_AI_API_KEY` secret in Space settings +2. Select L4 GPU hardware +3. Wait for build +4. `POST /start` to run benchmark + +See `hf-space/README.md` for API documentation. + +## CI/CD + +The benchmark runs automatically: +- **Weekly**: Sunday at midnight (scheduled) +- **On PR**: When benchmark code changes +- **Manual**: Via workflow dispatch + +Results are stored as artifacts and tracked historically. + +## Development + +```bash +# Run tests +npm test + +# Type check +npm run typecheck + +# Build +npm run build +``` + +## Architecture + +``` +packages/benchmark/ +├── src/ +│ ├── longmemeval/ +│ │ ├── types.ts # Zod schemas & types +│ │ ├── loader.ts # Dataset loading +│ │ ├── mapper.ts # LongMemEval → Engram +│ │ ├── retriever.ts # Vector retrieval +│ │ ├── reader.ts # LLM answer generation +│ │ ├── evaluator.ts # Metrics computation +│ │ ├── pipeline.ts # Orchestration +│ │ ├── key-expansion.ts # Fact extraction +│ │ ├── temporal.ts # Time-aware queries +│ │ └── providers/ # Real provider integrations +│ └── cli/ +│ └── commands/ # CLI command handlers +├── tests/ # Test suites +└── data/ # Dataset storage +``` diff --git a/packages/benchmark/data/.gitignore b/packages/benchmark/data/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..13bf9e7a1238d04feaf74cbe675ad2d4f550bf90 --- /dev/null +++ b/packages/benchmark/data/.gitignore @@ -0,0 +1,12 @@ +# Downloaded datasets +*.json + +# Benchmark results +*.jsonl + +# Generated reports +*-report.md + +# Keep the gitkeep +!.gitkeep +!.gitignore diff --git a/packages/benchmark/data/.gitkeep b/packages/benchmark/data/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..51d315db7cf9a442c640d94975665ee8d3bd2b4d --- /dev/null +++ b/packages/benchmark/data/.gitkeep @@ -0,0 +1,7 @@ +# Download LongMemEval dataset from HuggingFace: +# https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned +# +# Place the following files here: +# - longmemeval_s_cleaned.json (~115k tokens, ~40 sessions) +# - longmemeval_m_cleaned.json (~1.5M tokens, ~500 sessions) +# - longmemeval_oracle.json (evidence-only sessions) diff --git a/packages/benchmark/data/longmemeval_oracle.json b/packages/benchmark/data/longmemeval_oracle.json new file mode 100644 index 0000000000000000000000000000000000000000..8e6e661d71203470ff689c4de74c678b5889f227 --- /dev/null +++ b/packages/benchmark/data/longmemeval_oracle.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:821a2034d219ab45846873dd14c14f12cfe7776e73527a483f9dac095d38620c +size 15388478 diff --git a/packages/benchmark/data/results-demo-report.md b/packages/benchmark/data/results-demo-report.md new file mode 100644 index 0000000000000000000000000000000000000000..608da06be3aadfa0841c1a19bdd57dea8af7a45d --- /dev/null +++ b/packages/benchmark/data/results-demo-report.md @@ -0,0 +1,26 @@ +# LongMemEval Benchmark Results + +## Overall +- Total: 5 +- Correct: 3 +- Accuracy: 60.0% + +## By Memory Ability + +| Ability | Total | Correct | Accuracy | +|:--------|------:|--------:|---------:| +| Information Extraction (IE) | 0 | 0 | 0.0% | +| Multi-Session Reasoning (MR) | 0 | 0 | 0.0% | +| Temporal Reasoning (TR) | 5 | 3 | 60.0% | +| Knowledge Update (KU) | 0 | 0 | 0.0% | +| Abstention (ABS) | 0 | 0 | 0.0% | + +## Retrieval Metrics + +- Turn Recall: 50.0% +- Session Recall: 50.0% + +### Recall@K +- Recall@1: 0.0% +- Recall@5: 0.0% +- Recall@10: 50.0% \ No newline at end of file diff --git a/packages/benchmark/data/results-demo.jsonl b/packages/benchmark/data/results-demo.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..857e5d7f62d70ee71b589538ce292144639dd615 --- /dev/null +++ b/packages/benchmark/data/results-demo.jsonl @@ -0,0 +1,5 @@ +{"question_id":"gpt4_2655b836","hypothesis":"I cannot answer \"What was the first issue I had with my new car after its first service?\" without a real LLM provider configured."} +{"question_id":"gpt4_2487a7cb","hypothesis":"I cannot answer \"Which event did I attend first, the 'Effective Time Management' workshop or the 'Data Analysis using Python' webinar?\" without a real LLM provider configured."} +{"question_id":"gpt4_76048e76","hypothesis":"I cannot answer \"Which vehicle did I take care of first in February, the bike or the car?\" without a real LLM provider configured."} +{"question_id":"gpt4_2312f94c","hypothesis":"I cannot answer \"Which device did I got first, the Samsung Galaxy S22 or the Dell XPS 13?\" without a real LLM provider configured."} +{"question_id":"0bb5a684","hypothesis":"I cannot answer \"How many days before the team meeting I was preparing for did I attend the workshop on 'Effective Communication in the Workplace'?\" without a real LLM provider configured."} \ No newline at end of file diff --git a/packages/benchmark/data/results-full-report.md b/packages/benchmark/data/results-full-report.md new file mode 100644 index 0000000000000000000000000000000000000000..b73a244d551b8bce5a1e352032235e1bbb00e85f --- /dev/null +++ b/packages/benchmark/data/results-full-report.md @@ -0,0 +1,38 @@ +# LongMemEval Benchmark Results + +## Overall +- Total: 500 +- Correct: 39 +- Accuracy: 7.8% + +## By Memory Ability + +| Ability | Total | Correct | Accuracy | +|:--------|------:|--------:|---------:| +| Information Extraction (IE) | 150 | 6 | 4.0% | +| Multi-Session Reasoning (MR) | 121 | 1 | 0.8% | +| Temporal Reasoning (TR) | 127 | 31 | 24.4% | +| Knowledge Update (KU) | 72 | 1 | 1.4% | +| Abstention (ABS) | 30 | 0 | 0.0% | + +## Retrieval Metrics + +- Turn Recall: 53.0% +- Session Recall: 53.0% +- MRR: 0.530 + +### Recall@K + +| K | Recall | +|--:|-------:| +| 1 | 0.0% | +| 5 | 0.0% | +| 10 | 53.0% | + +### NDCG@K + +| K | NDCG | +|--:|-----:| +| 1 | 0.000 | +| 5 | 0.000 | +| 10 | 0.530 | \ No newline at end of file diff --git a/packages/benchmark/data/results-full.jsonl b/packages/benchmark/data/results-full.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..99f2924c8dc43ccdd0ce73ea89ed0c4dc75fc29a --- /dev/null +++ b/packages/benchmark/data/results-full.jsonl @@ -0,0 +1,500 @@ +{"question_id":"gpt4_2655b836","hypothesis":"Unable to answer: \"What was the first issue I had with my new car after its first service?\""} +{"question_id":"gpt4_2487a7cb","hypothesis":"Unable to answer: \"Which event did I attend first, the 'Effective Time Management' workshop or the 'Data Analysis using Python' webinar?\""} +{"question_id":"gpt4_76048e76","hypothesis":"Unable to answer: \"Which vehicle did I take care of first in February, the bike or the car?\""} +{"question_id":"gpt4_2312f94c","hypothesis":"Unable to answer: \"Which device did I got first, the Samsung Galaxy S22 or the Dell XPS 13?\""} +{"question_id":"0bb5a684","hypothesis":"Unable to answer: \"How many days before the team meeting I was preparing for did I attend the workshop on 'Effective Communication in the Workplace'?\""} +{"question_id":"08f4fc43","hypothesis":"Unable to answer: \"How many days had passed between the Sunday mass at St. Mary's Church and the Ash Wednesday service at the cathedral?\""} +{"question_id":"2c63a862","hypothesis":"Unable to answer: \"How many days did it take for me to find a house I loved after starting to work with Rachel?\""} +{"question_id":"gpt4_385a5000","hypothesis":"Unable to answer: \"Which seeds were started first, the tomatoes or the marigolds?\""} +{"question_id":"2a1811e2","hypothesis":"Unable to answer: \"How many days had passed between the Hindu festival of Holi and the Sunday mass at St. Mary's Church?\""} +{"question_id":"bbf86515","hypothesis":"Unable to answer: \"How many days before the 'Rack Fest' did I participate in the 'Turbocharged Tuesdays' event?\""} +{"question_id":"gpt4_5dcc0aab","hypothesis":"Unable to answer: \"Which pair of shoes did I clean last month?\""} +{"question_id":"gpt4_0b2f1d21","hypothesis":"Unable to answer: \"Which event happened first, the purchase of the coffee maker or the malfunction of the stand mixer?\""} +{"question_id":"f0853d11","hypothesis":"Unable to answer: \"How many days had passed between the 'Walk for Hunger' event and the 'Coastal Cleanup' event?\""} +{"question_id":"gpt4_6ed717ea","hypothesis":"Unable to answer: \"Which item did I purchase first, the dog bed for Max or the training pads for Luna?\""} +{"question_id":"gpt4_70e84552","hypothesis":"Unable to answer: \"Which task did I complete first, fixing the fence or trimming the goats' hooves?\""} +{"question_id":"a3838d2b","hypothesis":"Unable to answer: \"How many charity events did I participate in before the 'Run for the Cure' event?\""} +{"question_id":"gpt4_93159ced","hypothesis":"Unable to answer: \"How long have I been working before I started my current job at NovaTech?\""} +{"question_id":"gpt4_2d58bcd6","hypothesis":"Unable to answer: \"Which book did I finish reading first, 'The Hate U Give' or 'The Nightingale'?\""} +{"question_id":"gpt4_65aabe59","hypothesis":"Unable to answer: \"Which device did I set up first, the smart thermostat or the mesh network system?\""} +{"question_id":"982b5123","hypothesis":"Unable to answer: \"How many months ago did I book the Airbnb in San Francisco?\""} +{"question_id":"b9cfe692","hypothesis":"Unable to answer: \"How long did I take to finish 'The Seven Husbands of Evelyn Hugo' and 'The Nightingale' combined?\""} +{"question_id":"gpt4_4edbafa2","hypothesis":"Unable to answer: \"What was the date on which I attended the first BBQ event in June?\""} +{"question_id":"c8090214","hypothesis":"Unable to answer: \"How many days before I bought the iPhone 13 Pro did I attend the Holiday Market?\""} +{"question_id":"gpt4_483dd43c","hypothesis":"Unable to answer: \"Which show did I start watching first, 'The Crown' or 'Game of Thrones'?\""} +{"question_id":"e4e14d04","hypothesis":"Unable to answer: \"How long had I been a member of 'Book Lovers Unite' when I attended the meetup?\""} +{"question_id":"c9f37c46","hypothesis":"Unable to answer: \"How long had I been watching stand-up comedy specials regularly when I attended the open mic night at the local comedy club?\""} +{"question_id":"gpt4_2c50253f","hypothesis":"Unable to answer: \"What time do I wake up on Tuesdays and Thursdays?\""} +{"question_id":"dcfa8644","hypothesis":"Unable to answer: \"How many days had passed since I bought my Adidas running shoes when I realized one of the shoelaces on my old Converse sneakers had broken?\""} +{"question_id":"gpt4_b4a80587","hypothesis":"Unable to answer: \"Which event happened first, the road trip to the coast or the arrival of the new prime lens?\""} +{"question_id":"gpt4_9a159967","hypothesis":"Unable to answer: \"Which airline did I fly with the most in March and April?\""} +{"question_id":"cc6d1ec1","hypothesis":"Unable to answer: \"How long had I been bird watching when I attended the bird watching workshop?\""} +{"question_id":"gpt4_8c8961ae","hypothesis":"Unable to answer: \"Which trip did I take first, the one to Europe with family or the solo trip to Thailand?\""} +{"question_id":"gpt4_d9af6064","hypothesis":"Unable to answer: \"Which device did I set up first, the smart thermostat or the new router?\""} +{"question_id":"gpt4_7de946e7","hypothesis":"Unable to answer: \"Which health issue did I deal with first, the persistent cough or the skin tag removal?\""} +{"question_id":"d01c6aa8","hypothesis":"Unable to answer: \"How old was I when I moved to the United States?\""} +{"question_id":"993da5e2","hypothesis":"Unable to answer: \"How long had I been using the new area rug when I rearranged my living room furniture?\""} +{"question_id":"a3045048","hypothesis":"Unable to answer: \"How many days before my best friend's birthday party did I order her gift?\""} +{"question_id":"gpt4_d31cdae3","hypothesis":"Unable to answer: \"Which trip did the narrator take first, the solo trip to Europe or the family road trip across the American Southwest?\""} +{"question_id":"gpt4_cd90e484","hypothesis":"Unable to answer: \"How long did I use my new binoculars before I saw the American goldfinches returning to the area?\""} +{"question_id":"gpt4_88806d6e","hypothesis":"Unable to answer: \"Who did I meet first, Mark and Sarah or Tom?\""} +{"question_id":"gpt4_4cd9eba1","hypothesis":"Unable to answer: \"How many weeks have I been accepted into the exchange program when I started attending the pre-departure orientation sessions?\""} +{"question_id":"gpt4_93f6379c","hypothesis":"Unable to answer: \"Which group did I join first, 'Page Turners' or 'Marketing Professionals'?\""} +{"question_id":"b29f3365","hypothesis":"Unable to answer: \"How long had I been taking guitar lessons when I bought the new guitar amp?\""} +{"question_id":"gpt4_2f56ae70","hypothesis":"Unable to answer: \"Which streaming service did I start using most recently?\""} +{"question_id":"6613b389","hypothesis":"Unable to answer: \"How many months before my anniversary did Rachel get engaged?\""} +{"question_id":"gpt4_78cf46a3","hypothesis":"Unable to answer: \"Which event happened first, the narrator losing their phone charger or the narrator receiving their new phone case?\""} +{"question_id":"gpt4_0a05b494","hypothesis":"Unable to answer: \"Who did I meet first, the woman selling jam at the farmer's market or the tourist from Australia?\""} +{"question_id":"gpt4_1a1dc16d","hypothesis":"Unable to answer: \"Which event happened first, the meeting with Rachel or the pride parade?\""} +{"question_id":"gpt4_2f584639","hypothesis":"Unable to answer: \"Which gift did I buy first, the necklace for my sister or the photo album for my mom?\""} +{"question_id":"gpt4_213fd887","hypothesis":"Unable to answer: \"Which event did I participate in first, the volleyball league or the charity 5K run to raise money for a local children's hospital?\""} +{"question_id":"gpt4_5438fa52","hypothesis":"Unable to answer: \"Which event happened first, my attendance at a cultural festival or the start of my Spanish classes?\""} +{"question_id":"gpt4_c27434e8","hypothesis":"Unable to answer: \"Which project did I start first, the Ferrari model or the Japanese Zero fighter plane model?\""} +{"question_id":"gpt4_fe651585","hypothesis":"Unable to answer: \"Who became a parent first, Rachel or Alex?\""} +{"question_id":"8c18457d","hypothesis":"Unable to answer: \"How many days had passed between the day I bought a gift for my brother's graduation ceremony and the day I bought a birthday gift for my best friend?\""} +{"question_id":"gpt4_70e84552_abs","hypothesis":"Unable to answer: \"Which task did I complete first, fixing the fence or purchasing three cows from Peter?\""} +{"question_id":"gpt4_93159ced_abs","hypothesis":"Unable to answer: \"How long have I been working before I started my current job at Google?\""} +{"question_id":"982b5123_abs","hypothesis":"Unable to answer: \"When did I book the Airbnb in Sacramento?\""} +{"question_id":"c8090214_abs","hypothesis":"Unable to answer: \"How many days before I bought my iPad did I attend the Holiday Market?\""} +{"question_id":"gpt4_c27434e8_abs","hypothesis":"Unable to answer: \"Which project did I start first, the Ferrari model or the Porsche 991 Turbo S model?\""} +{"question_id":"gpt4_fe651585_abs","hypothesis":"Unable to answer: \"Who became a parent first, Tom or Alex?\""} +{"question_id":"0a995998","hypothesis":"Unable to answer: \"How many items of clothing do I need to pick up or return from a store?\""} +{"question_id":"6d550036","hypothesis":"Unable to answer: \"How many projects have I led or am currently leading?\""} +{"question_id":"gpt4_59c863d7","hypothesis":"Unable to answer: \"How many model kits have I worked on or bought?\""} +{"question_id":"b5ef892d","hypothesis":"Unable to answer: \"How many days did I spend on camping trips in the United States this year?\""} +{"question_id":"e831120c","hypothesis":"Unable to answer: \"How many weeks did it take me to watch all the Marvel Cinematic Universe movies and the main Star Wars films?\""} +{"question_id":"3a704032","hypothesis":"Unable to answer: \"How many plants did I acquire in the last month?\""} +{"question_id":"gpt4_d84a3211","hypothesis":"Unable to answer: \"How much total money have I spent on bike-related expenses since the start of the year?\""} +{"question_id":"aae3761f","hypothesis":"Unable to answer: \"How many hours in total did I spend driving to my three road trip destinations combined?\""} +{"question_id":"gpt4_f2262a51","hypothesis":"Unable to answer: \"How many different doctors did I visit?\""} +{"question_id":"dd2973ad","hypothesis":"Unable to answer: \"What time did I go to bed on the day before I had a doctor's appointment?\""} +{"question_id":"c4a1ceb8","hypothesis":"Unable to answer: \"How many different types of citrus fruits have I used in my cocktail recipes?\""} +{"question_id":"gpt4_a56e767c","hypothesis":"Unable to answer: \"How many movie festivals that I attended?\""} +{"question_id":"6cb6f249","hypothesis":"Unable to answer: \"How many days did I take social media breaks in total?\""} +{"question_id":"46a3abf7","hypothesis":"Unable to answer: \"How many tanks do I currently have, including the one I set up for my friend's kid?\""} +{"question_id":"36b9f61e","hypothesis":"Unable to answer: \"What is the total amount I spent on luxury items in the past few months?\""} +{"question_id":"28dc39ac","hypothesis":"Unable to answer: \"How many hours have I spent playing games in total?\""} +{"question_id":"gpt4_2f8be40d","hypothesis":"Unable to answer: \"How many weddings have I attended in this year?\""} +{"question_id":"2e6d26dc","hypothesis":"Unable to answer: \"How many babies were born to friends and family members in the last few months?\""} +{"question_id":"gpt4_15e38248","hypothesis":"Unable to answer: \"How many pieces of furniture did I buy, assemble, sell, or fix in the past few months?\""} +{"question_id":"88432d0a","hypothesis":"Unable to answer: \"How many times did I bake something in the past two weeks?\""} +{"question_id":"80ec1f4f","hypothesis":"Unable to answer: \"How many different museums or galleries did I visit in the month of February?\""} +{"question_id":"d23cf73b","hypothesis":"Unable to answer: \"How many different cuisines have I learned to cook or tried out in the past few months?\""} +{"question_id":"gpt4_7fce9456","hypothesis":"Unable to answer: \"How many properties did I view before making an offer on the townhouse in the Brookside neighborhood?\""} +{"question_id":"d682f1a2","hypothesis":"Unable to answer: \"How many different types of food delivery services have I used recently?\""} +{"question_id":"7024f17c","hypothesis":"Unable to answer: \"How many hours of jogging and yoga did I do last week?\""} +{"question_id":"gpt4_5501fe77","hypothesis":"Unable to answer: \"Which social media platform did I gain the most followers on over the past month?\""} +{"question_id":"gpt4_2ba83207","hypothesis":"Unable to answer: \"Which grocery store did I spend the most money at in the past month?\""} +{"question_id":"2318644b","hypothesis":"Unable to answer: \"How much more did I spend on accommodations per night in Hawaii compared to Tokyo?\""} +{"question_id":"2ce6a0f2","hypothesis":"Unable to answer: \"How many different art-related events did I attend in the past month?\""} +{"question_id":"gpt4_d12ceb0e","hypothesis":"Unable to answer: \"What is the average age of me, my parents, and my grandparents?\""} +{"question_id":"00ca467f","hypothesis":"Unable to answer: \"How many doctor's appointments did I go to in March?\""} +{"question_id":"b3c15d39","hypothesis":"Unable to answer: \"How many days did it take for me to receive the new remote shutter release after I ordered it?\""} +{"question_id":"gpt4_31ff4165","hypothesis":"Unable to answer: \"How many health-related devices do I use in a day?\""} +{"question_id":"eeda8a6d","hypothesis":"Unable to answer: \"How many fish are there in total in both of my aquariums?\""} +{"question_id":"2788b940","hypothesis":"Unable to answer: \"How many fitness classes do I attend in a typical week?\""} +{"question_id":"60bf93ed","hypothesis":"Unable to answer: \"How many days did it take for my laptop backpack to arrive after I bought it?\""} +{"question_id":"9d25d4e0","hypothesis":"Unable to answer: \"How many pieces of jewelry did I acquire in the last two months?\""} +{"question_id":"129d1232","hypothesis":"Unable to answer: \"How much money did I raise in total through all the charity events I participated in?\""} +{"question_id":"60472f9c","hypothesis":"Unable to answer: \"How many projects have I been working on simultaneously, excluding my thesis?\""} +{"question_id":"gpt4_194be4b3","hypothesis":"Unable to answer: \"How many musical instruments do I currently own?\""} +{"question_id":"a9f6b44c","hypothesis":"Unable to answer: \"How many bikes did I service or plan to service in March?\""} +{"question_id":"d851d5ba","hypothesis":"Unable to answer: \"How much money did I raise for charity in total?\""} +{"question_id":"5a7937c8","hypothesis":"Unable to answer: \"How many days did I spend participating in faith-related activities in December?\""} +{"question_id":"gpt4_ab202e7f","hypothesis":"Unable to answer: \"How many kitchen items did I replace or fix?\""} +{"question_id":"gpt4_e05b82a6","hypothesis":"Unable to answer: \"How many times did I ride rollercoasters across all the events I attended from July to October?\""} +{"question_id":"gpt4_731e37d7","hypothesis":"Unable to answer: \"How much total money did I spend on attending workshops in the last four months?\""} +{"question_id":"edced276","hypothesis":"Unable to answer: \"How many days did I spend in total traveling in Hawaii and in New York City?\""} +{"question_id":"10d9b85a","hypothesis":"Unable to answer: \"How many days did I spend attending workshops, lectures, and conferences in April?\""} +{"question_id":"e3038f8c","hypothesis":"Unable to answer: \"How many rare items do I have in total?\""} +{"question_id":"2b8f3739","hypothesis":"Unable to answer: \"What is the total amount of money I earned from selling my products at the markets?\""} +{"question_id":"1a8a66a6","hypothesis":"Unable to answer: \"How many magazine subscriptions do I currently have?\""} +{"question_id":"c2ac3c61","hypothesis":"Unable to answer: \"How many online courses have I completed in total?\""} +{"question_id":"bf659f65","hypothesis":"Unable to answer: \"How many music albums or EPs have I purchased or downloaded?\""} +{"question_id":"gpt4_372c3eed","hypothesis":"Unable to answer: \"How many years in total did I spend in formal education from high school to the completion of my Bachelor's degree?\""} +{"question_id":"gpt4_2f91af09","hypothesis":"Unable to answer: \"How many total pieces of writing have I completed since I started writing again three weeks ago, including short stories, poems, and pieces for the writing challenge?\""} +{"question_id":"81507db6","hypothesis":"Unable to answer: \"How many graduation ceremonies have I attended in the past three months?\""} +{"question_id":"88432d0a_abs","hypothesis":"Unable to answer: \"How many times did I bake egg tarts in the past two weeks?\""} +{"question_id":"80ec1f4f_abs","hypothesis":"Unable to answer: \"How many different museums or galleries did I visit in December?\""} +{"question_id":"eeda8a6d_abs","hypothesis":"Unable to answer: \"How many fish are there in my 30-gallon tank?\""} +{"question_id":"60bf93ed_abs","hypothesis":"Unable to answer: \"How many days did it take for my iPad case to arrive after I bought it?\""} +{"question_id":"edced276_abs","hypothesis":"Unable to answer: \"How many days did I spend in total traveling in Hawaii and in Seattle?\""} +{"question_id":"gpt4_372c3eed_abs","hypothesis":"Unable to answer: \"How many years in total did I spend in formal education from high school to the completion of my Master's degree?\""} +{"question_id":"6a1eabeb","hypothesis":"Unable to answer: \"What was my personal best time in the charity 5K run?\""} +{"question_id":"6aeb4375","hypothesis":"Unable to answer: \"How many Korean restaurants have I tried in my city?\""} +{"question_id":"830ce83f","hypothesis":"Unable to answer: \"Where did Rachel move to after her recent relocation?\""} +{"question_id":"852ce960","hypothesis":"Unable to answer: \"What was the amount I was pre-approved for when I got my mortgage from Wells Fargo?\""} +{"question_id":"945e3d21","hypothesis":"Unable to answer: \"How often do I attend yoga classes to help with my anxiety?\""} +{"question_id":"d7c942c3","hypothesis":"Unable to answer: \"Is my mom using the same grocery list method as me?\""} +{"question_id":"71315a70","hypothesis":"Unable to answer: \"How many hours have I spent on my abstract ocean sculpture?\""} +{"question_id":"89941a93","hypothesis":"Unable to answer: \"How many bikes do I currently own?\""} +{"question_id":"ce6d2d27","hypothesis":"Unable to answer: \"What day of the week do I take a cocktail-making class?\""} +{"question_id":"9ea5eabc","hypothesis":"Unable to answer: \"Where did I go on my most recent family trip?\""} +{"question_id":"07741c44","hypothesis":"Unable to answer: \"Where do I initially keep my old sneakers?\""} +{"question_id":"a1eacc2a","hypothesis":"Unable to answer: \"How many short stories have I written since I started writing regularly?\""} +{"question_id":"184da446","hypothesis":"Unable to answer: \"How many pages of 'A Short History of Nearly Everything' have I read so far?\""} +{"question_id":"031748ae","hypothesis":"Unable to answer: \"How many engineers do I lead when I just started my new role as Senior Software Engineer? How many engineers do I lead now?\""} +{"question_id":"4d6b87c8","hypothesis":"Unable to answer: \"How many titles are currently on my to-watch list?\""} +{"question_id":"0f05491a","hypothesis":"Unable to answer: \"How many stars do I need to reach the gold level on my Starbucks Rewards app?\""} +{"question_id":"08e075c7","hypothesis":"Unable to answer: \"How long have I been using my Fitbit Charge 3?\""} +{"question_id":"f9e8c073","hypothesis":"Unable to answer: \"How many sessions of the bereavement support group did I attend?\""} +{"question_id":"41698283","hypothesis":"Unable to answer: \"What type of camera lens did I purchase most recently?\""} +{"question_id":"2698e78f","hypothesis":"Unable to answer: \"How often do I see my therapist, Dr. Smith?\""} +{"question_id":"b6019101","hypothesis":"Unable to answer: \"How many MCU films did I watch in the last 3 months?\""} +{"question_id":"45dc21b6","hypothesis":"Unable to answer: \"How many of Emma's recipes have I tried out?\""} +{"question_id":"5a4f22c0","hypothesis":"Unable to answer: \"What company is Rachel, an old colleague from my previous company, currently working at?\""} +{"question_id":"6071bd76","hypothesis":"Unable to answer: \"For the coffee-to-water ratio in my French press, did I switch to more water per tablespoon of coffee, or less?\""} +{"question_id":"e493bb7c","hypothesis":"Unable to answer: \"Where is the painting 'Ethereal Dreams' by Emma Taylor currently hanging?\""} +{"question_id":"618f13b2","hypothesis":"Unable to answer: \"How many times have I worn my new black Converse Chuck Taylor All Star sneakers?\""} +{"question_id":"72e3ee87","hypothesis":"Unable to answer: \"How many episodes of the Science series have I completed on Crash Course?\""} +{"question_id":"c4ea545c","hypothesis":"Unable to answer: \"Do I go to the gym more frequently than I did previously?\""} +{"question_id":"01493427","hypothesis":"Unable to answer: \"How many new postcards have I added to my collection since I started collecting again?\""} +{"question_id":"6a27ffc2","hypothesis":"Unable to answer: \"How many videos of Corey Schafer's Python programming series have I completed so far?\""} +{"question_id":"2133c1b5","hypothesis":"Unable to answer: \"How long have I been living in my current apartment in Harajuku?\""} +{"question_id":"18bc8abd","hypothesis":"Unable to answer: \"What brand of BBQ sauce am I currently obsessed with?\""} +{"question_id":"db467c8c","hypothesis":"Unable to answer: \"How long have my parents been staying with me in the US?\""} +{"question_id":"7a87bd0c","hypothesis":"Unable to answer: \"How long have I been sticking to my daily tidying routine?\""} +{"question_id":"e61a7584","hypothesis":"Unable to answer: \"How long have I had my cat, Luna?\""} +{"question_id":"1cea1afa","hypothesis":"Unable to answer: \"How many Instagram followers do I currently have?\""} +{"question_id":"ed4ddc30","hypothesis":"Unable to answer: \"How many dozen eggs do we currently have stocked up in our refrigerator?\""} +{"question_id":"8fb83627","hypothesis":"Unable to answer: \"How many issues of National Geographic have I finished reading?\""} +{"question_id":"b01defab","hypothesis":"Unable to answer: \"Did I finish reading 'The Nightingale' by Kristin Hannah?\""} +{"question_id":"22d2cb42","hypothesis":"Unable to answer: \"Where did I get my guitar serviced?\""} +{"question_id":"0e4e4c46","hypothesis":"Unable to answer: \"What is my current highest score in Ticket to Ride?\""} +{"question_id":"4b24c848","hypothesis":"Unable to answer: \"How many tops have I bought from H&M so far?\""} +{"question_id":"7e974930","hypothesis":"Unable to answer: \"How much did I earn at the Downtown Farmers Market on my most recent visit?\""} +{"question_id":"603deb26","hypothesis":"Unable to answer: \"How many times have I tried making a Negroni at home since my friend Emma showed me how to make it?\""} +{"question_id":"59524333","hypothesis":"Unable to answer: \"What time do I usually go to the gym?\""} +{"question_id":"5831f84d","hypothesis":"Unable to answer: \"How many Crash Course videos have I watched in the past few weeks?\""} +{"question_id":"eace081b","hypothesis":"Unable to answer: \"Where am I planning to stay for my birthday trip to Hawaii?\""} +{"question_id":"affe2881","hypothesis":"Unable to answer: \"How many different species of birds have I seen in my local park?\""} +{"question_id":"50635ada","hypothesis":"Unable to answer: \"What was my previous frequent flyer status on United Airlines before I got the current status?\""} +{"question_id":"e66b632c","hypothesis":"Unable to answer: \"What was my previous personal best time for the charity 5K run?\""} +{"question_id":"0ddfec37","hypothesis":"Unable to answer: \"How many autographed baseballs have I added to my collection in the first three months of collection?\""} +{"question_id":"f685340e","hypothesis":"Unable to answer: \"How often do I play tennis with my friends at the local park previously? How often do I play now?\""} +{"question_id":"cc5ded98","hypothesis":"Unable to answer: \"How much time do I dedicate to coding exercises each day?\""} +{"question_id":"dfde3500","hypothesis":"Unable to answer: \"What day of the week did I meet with my previous language exchange tutor Juan?\""} +{"question_id":"69fee5aa","hypothesis":"Unable to answer: \"How many pre-1920 American coins do I have in my collection?\""} +{"question_id":"7401057b","hypothesis":"Unable to answer: \"How many free night's stays can I redeem at any Hilton property with my accumulated points?\""} +{"question_id":"cf22b7bf","hypothesis":"Unable to answer: \"How much weight have I lost since I started going to the gym consistently?\""} +{"question_id":"a2f3aa27","hypothesis":"Unable to answer: \"How many followers do I have on Instagram now?\""} +{"question_id":"c7dc5443","hypothesis":"Unable to answer: \"What is my current record in the recreational volleyball league?\""} +{"question_id":"06db6396","hypothesis":"Unable to answer: \"How many projects have I completed since starting painting classes?\""} +{"question_id":"3ba21379","hypothesis":"Unable to answer: \"What type of vehicle model am I currently working on?\""} +{"question_id":"9bbe84a2","hypothesis":"Unable to answer: \"What was my previous goal for my Apex Legends level before I updated my goal?\""} +{"question_id":"10e09553","hypothesis":"Unable to answer: \"How many largemouth bass did I catch with Alex on the earlier fishing trip to Lake Michigan before the 7/22 trip?\""} +{"question_id":"dad224aa","hypothesis":"Unable to answer: \"What time do I wake up on Saturday mornings?\""} +{"question_id":"ba61f0b9","hypothesis":"Unable to answer: \"How many women are on the team led by my former manager Rachel?\""} +{"question_id":"42ec0761","hypothesis":"Unable to answer: \"Do I have a spare screwdriver for opening up my laptop?\""} +{"question_id":"5c40ec5b","hypothesis":"Unable to answer: \"How many times have I met up with Alex from Germany?\""} +{"question_id":"c6853660","hypothesis":"Unable to answer: \"Did I mostly recently increase or decrease the limit on the number of cups of coffee in the morning?\""} +{"question_id":"26bdc477","hypothesis":"Unable to answer: \"How many trips have I taken my Canon EOS 80D camera on?\""} +{"question_id":"0977f2af","hypothesis":"Unable to answer: \"What new kitchen gadget did I invest in before getting the Air Fryer?\""} +{"question_id":"6aeb4375_abs","hypothesis":"Unable to answer: \"How many Italian restaurants have I tried in my city?\""} +{"question_id":"031748ae_abs","hypothesis":"Unable to answer: \"How many engineers do I lead when I just started my new role as Software Engineer Manager?\""} +{"question_id":"2698e78f_abs","hypothesis":"Unable to answer: \"How often do I see Dr. Johnson?\""} +{"question_id":"2133c1b5_abs","hypothesis":"Unable to answer: \"How long have I been living in my current apartment in Shinjuku?\""} +{"question_id":"0ddfec37_abs","hypothesis":"Unable to answer: \"How many autographed football have I added to my collection in the first three months of collection?\""} +{"question_id":"f685340e_abs","hypothesis":"Unable to answer: \"How often do I play table tennis with my friends at the local park?\""} +{"question_id":"89941a94","hypothesis":"Unable to answer: \"Before I purchased the gravel bike, do I have other bikes in addition to my mountain bike and my commuter bike?\""} +{"question_id":"07741c45","hypothesis":"Unable to answer: \"Where do I currently keep my old sneakers?\""} +{"question_id":"8a2466db","hypothesis":"Unable to answer: \"Can you recommend some resources where I can learn more about video editing?\""} +{"question_id":"06878be2","hypothesis":"Unable to answer: \"Can you suggest some accessories that would complement my current photography setup?\""} +{"question_id":"75832dbd","hypothesis":"Unable to answer: \"Can you recommend some recent publications or conferences that I might find interesting?\""} +{"question_id":"0edc2aef","hypothesis":"Unable to answer: \"Can you suggest a hotel for my upcoming trip to Miami?\""} +{"question_id":"35a27287","hypothesis":"Unable to answer: \"Can you recommend some interesting cultural events happening around me this weekend?\""} +{"question_id":"32260d93","hypothesis":"Unable to answer: \"Can you recommend a show or movie for me to watch tonight?\""} +{"question_id":"195a1a1b","hypothesis":"Unable to answer: \"Can you suggest some activities that I can do in the evening?\""} +{"question_id":"afdc33df","hypothesis":"Unable to answer: \"My kitchen's becoming a bit of a mess again. Any tips for keeping it clean?\""} +{"question_id":"caf03d32","hypothesis":"Unable to answer: \"I've been struggling with my slow cooker recipes. Any advice on getting better results?\""} +{"question_id":"54026fce","hypothesis":"Unable to answer: \"I've been thinking about ways to stay connected with my colleagues. Any suggestions?\""} +{"question_id":"06f04340","hypothesis":"Unable to answer: \"What should I serve for dinner this weekend with my homegrown ingredients?\""} +{"question_id":"6b7dfb22","hypothesis":"Unable to answer: \"I've been feeling a bit stuck with my paintings lately. Do you have any ideas on how I can find new inspiration?\""} +{"question_id":"1a1907b4","hypothesis":"Unable to answer: \"I've been thinking about making a cocktail for an upcoming get-together, but I'm not sure which one to choose. Any suggestions?\""} +{"question_id":"09d032c9","hypothesis":"Unable to answer: \"I've been having trouble with the battery life on my phone lately. Any tips?\""} +{"question_id":"38146c39","hypothesis":"Unable to answer: \"I've been feeling like my chocolate chip cookies need something extra. Any advice?\""} +{"question_id":"d24813b1","hypothesis":"Unable to answer: \"I'm thinking of inviting my colleagues over for a small gathering. Any tips on what to bake?\""} +{"question_id":"57f827a0","hypothesis":"Unable to answer: \"I was thinking about rearranging the furniture in my bedroom this weekend. Any tips?\""} +{"question_id":"95228167","hypothesis":"Unable to answer: \"I'm getting excited about my visit to the music store this weekend. Any tips on what to look for in a new guitar?\""} +{"question_id":"505af2f5","hypothesis":"Unable to answer: \"I was thinking of trying a new coffee creamer recipe. Any recommendations?\""} +{"question_id":"75f70248","hypothesis":"Unable to answer: \"I've been sneezing quite a bit lately. Do you think it might be my living room?\""} +{"question_id":"d6233ab6","hypothesis":"Unable to answer: \"I've been feeling nostalgic lately. Do you think it would be a good idea to attend my high school reunion?\""} +{"question_id":"1da05512","hypothesis":"Unable to answer: \"I'm trying to decide whether to buy a NAS device now or wait. What do you think?\""} +{"question_id":"fca70973","hypothesis":"Unable to answer: \"I am planning another theme park weekend; do you have any suggestions?\""} +{"question_id":"b6025781","hypothesis":"Unable to answer: \"I'm planning my meal prep next week, any suggestions for new recipes?\""} +{"question_id":"a89d7624","hypothesis":"Unable to answer: \"I'm planning a trip to Denver soon. Any suggestions on what to do there?\""} +{"question_id":"b0479f84","hypothesis":"Unable to answer: \"I've got some free time tonight, any documentary recommendations?\""} +{"question_id":"1d4e3b97","hypothesis":"Unable to answer: \"I noticed my bike seems to be performing even better during my Sunday group rides. Could there be a reason for this?\""} +{"question_id":"07b6f563","hypothesis":"Unable to answer: \"Can you suggest some useful accessories for my phone?\""} +{"question_id":"1c0ddc50","hypothesis":"Unable to answer: \"Can you suggest some activities I can do during my commute to work?\""} +{"question_id":"0a34ad58","hypothesis":"Unable to answer: \"I’m a bit anxious about getting around Tokyo. Do you have any helpful tips?\""} +{"question_id":"7161e7e2","hypothesis":"Unable to answer: \"I'm checking our previous chat about the shift rotation sheet for GM social media agents. Can you remind me what was the rotation for Admon on a Sunday?\""} +{"question_id":"c4f10528","hypothesis":"Unable to answer: \"I'm planning to visit Bandung again and I was wondering if you could remind me of the name of that restaurant in Cihampelas Walk that serves a great Nasi Goreng?\""} +{"question_id":"89527b6b","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about the children's book on dinosaurs. Can you remind me what color was the scaly body of the Plesiosaur in the image?\""} +{"question_id":"e9327a54","hypothesis":"Unable to answer: \"I'm planning to revisit Orlando. I was wondering if you could remind me of that unique dessert shop with the giant milkshakes we talked about last time?\""} +{"question_id":"4c36ccef","hypothesis":"Unable to answer: \"Can you remind me of the name of the romantic Italian restaurant in Rome you recommended for dinner?\""} +{"question_id":"6ae235be","hypothesis":"Unable to answer: \"I remember you told me about the refining processes at CITGO's three refineries earlier. Can you remind me what kind of processes are used at the Lake Charles Refinery?\""} +{"question_id":"7e00a6cb","hypothesis":"Unable to answer: \"I'm planning my trip to Amsterdam again and I was wondering, what was the name of that hostel near the Red Light District that you recommended last time?\""} +{"question_id":"1903aded","hypothesis":"Unable to answer: \"I think we discussed work from home jobs for seniors earlier. Can you remind me what was the 7th job in the list you provided?\""} +{"question_id":"ceb54acb","hypothesis":"Unable to answer: \"In our previous chat, you suggested 'sexual compulsions' and a few other options for alternative terms for certain behaviors. Can you remind me what the other four options were?\""} +{"question_id":"f523d9fe","hypothesis":"Unable to answer: \"I wanted to check back on our previous conversation about Netflix. I mentioned that I wanted to be able to access all seasons of old shows? Do you remember what show I used as an example, the one that only had the last season available?\""} +{"question_id":"0e5e2d1a","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about binaural beats for anxiety and depression. Can you remind me how many subjects were in the study published in the journal Music and Medicine that found significant reductions in symptoms of depression, anxiety, and stress?\""} +{"question_id":"fea54f57","hypothesis":"Unable to answer: \"I was thinking about our previous conversation about the Fifth Album, and I was wondering if you could remind me what song you said best exemplified the band's growth and development as artists?\""} +{"question_id":"cc539528","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about front-end and back-end development. Can you remind me of the specific back-end programming languages you recommended I learn?\""} +{"question_id":"dc439ea3","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about Native American powwows and I was wondering, which traditional game did you say was often performed by skilled dancers at powwows?\""} +{"question_id":"18dcd5a5","hypothesis":"Unable to answer: \"I'm going back to our previous chat about the Lost Temple of the Djinn one-shot. Can you remind me how many mummies the party will face in the temple?\""} +{"question_id":"488d3006","hypothesis":"Unable to answer: \"I'm planning to go back to the Natural Park of Moncayo mountain in Aragón and I was wondering, what was the name of that hiking trail you recommended that takes you through the park's most stunning landscapes and offers panoramic views of the surrounding mountainside?\""} +{"question_id":"58470ed2","hypothesis":"Unable to answer: \"I was going through our previous conversation about The Library of Babel, and I wanted to confirm - what did Borges say about the center and circumference of the Library?\""} +{"question_id":"8cf51dda","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about the grant aim page on molecular subtypes and endometrial cancer. Can you remind me what were the three objectives we outlined for the project?\""} +{"question_id":"1d4da289","hypothesis":"Unable to answer: \"I was thinking about our previous conversation about data privacy and security. You mentioned that companies use two-factor authentication to enhance security. Can you remind me what kind of two-factor authentication methods you were referring to?\""} +{"question_id":"8464fc84","hypothesis":"Unable to answer: \"I'm planning to visit the Vatican again and I was wondering if you could remind me of the name of that famous deli near the Vatican that serves the best cured meats and cheeses?\""} +{"question_id":"8aef76bc","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about DIY home decor projects using recycled materials. Can you remind me what sealant you recommended for the newspaper flower vase?\""} +{"question_id":"71a3fd6b","hypothesis":"Unable to answer: \"I'm planning my trip to Speyer again and I wanted to confirm, what's the phone number of the Speyer tourism board that you provided me earlier?\""} +{"question_id":"2bf43736","hypothesis":"Unable to answer: \"I was going through our previous chat and I wanted to clarify something about the prayer of beginners in Tanqueray's Spiritual Life treatise. Can you remind me which chapter of the second part discusses vocal prayer and meditation?\""} +{"question_id":"70b3e69b","hypothesis":"Unable to answer: \"I was going through our previous conversation about the impact of the political climate in Catalonia on its literature and music. Can you remind me of the example you gave of a Spanish-Catalan singer-songwriter who supports unity between Catalonia and Spain?\""} +{"question_id":"8752c811","hypothesis":"Unable to answer: \"I remember you provided a list of 100 prompt parameters that I can specify to influence your output. Can you remind me what was the 27th parameter on that list?\""} +{"question_id":"3249768e","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation about building a cocktail bar. You recommended five bottles to make the widest variety of gin-based cocktails. Can you remind me what the fifth bottle was?\""} +{"question_id":"1b9b7252","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about mindfulness techniques. You mentioned some great resources for guided imagery exercises, can you remind me of the website that had free exercises like 'The Mountain Meditation' and 'The Body Scan Meditation'?\""} +{"question_id":"1568498a","hypothesis":"Unable to answer: \"I'm looking back at our previous chess game and I was wondering, what was the move you made after 27. Kg2 Bd5+?\""} +{"question_id":"6222b6eb","hypothesis":"Unable to answer: \"I was going through our previous conversation about atmospheric correction methods, and I wanted to confirm - you mentioned that 6S, MAJA, and Sen2Cor are all algorithms for atmospheric correction of remote sensing images. Can you remind me which one is implemented in the SIAC_GEE tool?\""} +{"question_id":"e8a79c70","hypothesis":"Unable to answer: \"I was going through our previous conversation about making a classic French omelette, and I wanted to confirm - how many eggs did you say we need for the recipe?\""} +{"question_id":"d596882b","hypothesis":"Unable to answer: \"I'm planning another trip to New York City and I was wondering if you could remind me of that vegan eatery you recommended last time, the one with multiple locations throughout the city?\""} +{"question_id":"e3fc4d6e","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about the fusion breakthrough at Lawrence Livermore National Laboratory. Can you remind me who is the President's Chief Advisor for Science and Technology mentioned in the article?\""} +{"question_id":"51b23612","hypothesis":"Unable to answer: \"I was going through our previous conversation about political propaganda and humor, and I was wondering if you could remind me of that Soviet cartoon you mentioned that mocked Western culture?\""} +{"question_id":"3e321797","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about natural remedies for dark circles under the eyes. You mentioned applying tomato juice mixed with lemon juice, how long did you say I should leave it on for?\""} +{"question_id":"e982271f","hypothesis":"Unable to answer: \"I was going through our previous chat. Can you remind me of the name of the last venue you recommended in the list of popular venues in Portland for indie music shows?\""} +{"question_id":"352ab8bd","hypothesis":"Unable to answer: \"Can you remind me what was the average improvement in framerate when using the Hardware-Aware Modular Training (HAMT) agent in the 'To Adapt or Not to Adapt? Real-Time Adaptation for Semantic Segmentation' submission?\""} +{"question_id":"fca762bc","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about language learning apps. You mentioned a few options, and I was wondering if you could remind me of the one that uses mnemonics to help learners memorize words and phrases?\""} +{"question_id":"7a8d0b71","hypothesis":"Unable to answer: \"I'm looking back at our previous chat about the DHL Wellness Retreats campaign. Can you remind me how much was allocated for influencer marketing in the campaign plan?\""} +{"question_id":"a40e080f","hypothesis":"Unable to answer: \"I was going through our previous conversation and I was wondering if you could remind me of the two companies you mentioned that prioritize employee safety and well-being like Triumvirate?\""} +{"question_id":"8b9d4367","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about private sector businesses in Chaudhary. Can you remind me of the company that employs over 40,000 people in the rug-manufacturing industry?\""} +{"question_id":"5809eb10","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation about the Bajimaya v Reward Homes Pty Ltd case. Can you remind me what year the construction of the house began?\""} +{"question_id":"41275add","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about YouTube videos for workplace posture. Can you remind me of the Mayo Clinic video you recommended?\""} +{"question_id":"4388e9dd","hypothesis":"Unable to answer: \"I was going through our previous chat and I was wondering, what was Andy wearing in the script you wrote for the comedy movie scene?\""} +{"question_id":"4baee567","hypothesis":"Unable to answer: \"I was looking back at our previous chat and I wanted to confirm, how many times did the Chiefs play the Jaguars at Arrowhead Stadium?\""} +{"question_id":"561fabcd","hypothesis":"Unable to answer: \"I was thinking back to our previous conversation about the Radiation Amplified zombie, and I was wondering if you remembered what we finally decided to name it?\""} +{"question_id":"b759caee","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about buying unique engagement rings directly from designers. Can you remind me of the Instagram handle of the UK-based designer who works with unusual gemstones?\""} +{"question_id":"ac031881","hypothesis":"Unable to answer: \"I'm trying to recall what the designation on my jumpsuit was that helped me find the file number in the records room?\""} +{"question_id":"28bcfaac","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about music theory. You mentioned some online resources for learning music theory. Can you remind me of the website you recommended for free lessons and exercises?\""} +{"question_id":"16c90bf4","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation about the Seco de Cordero recipe from Ancash. You mentioned using a light or medium-bodied beer, but I was wondering if you could remind me what type of beer you specifically recommended?\""} +{"question_id":"c8f1aeed","hypothesis":"Unable to answer: \"I wanted to follow up on our previous conversation about fracking in the Marcellus Shale region. You mentioned that some states require fracking companies to monitor groundwater quality at nearby wells before drilling and for a certain period after drilling is complete. Can you remind me which state you mentioned as an example that has this requirement?\""} +{"question_id":"eaca4986","hypothesis":"Unable to answer: \"I'm looking back at our previous conversation where you created two sad songs for me. Can you remind me what was the chord progression for the chorus in the second song?\""} +{"question_id":"c7cf7dfd","hypothesis":"Unable to answer: \"I'm going back to our previous conversation about traditional Indian embroidery and tailoring techniques. Can you remind me of the name of that online store based in India that sells traditional Indian fabrics, threads, and embellishments?\""} +{"question_id":"e48988bc","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about environmentally responsible supply chain practices, and I was wondering if you could remind me of the company you mentioned that's doing a great job with sustainability?\""} +{"question_id":"1de5cff2","hypothesis":"Unable to answer: \"I was going through our previous conversation about high-end fashion brands, and I was wondering if you could remind me of the brand that uses wild rubber sourced from the Amazon rainforest?\""} +{"question_id":"65240037","hypothesis":"Unable to answer: \"I remember you told me to dilute tea tree oil with a carrier oil before applying it to my skin. Can you remind me what the recommended ratio is?\""} +{"question_id":"778164c6","hypothesis":"Unable to answer: \"I was looking back at our previous conversation about Caribbean dishes and I was wondering, what was the name of that Jamaican dish you recommended I try with snapper that has fruit in it?\""} +{"question_id":"e47becba","hypothesis":"Unable to answer: \"What degree did I graduate with?\""} +{"question_id":"118b2229","hypothesis":"Unable to answer: \"How long is my daily commute to work?\""} +{"question_id":"51a45a95","hypothesis":"Unable to answer: \"Where did I redeem a $5 coupon on coffee creamer?\""} +{"question_id":"58bf7951","hypothesis":"Unable to answer: \"What play did I attend at the local community theater?\""} +{"question_id":"1e043500","hypothesis":"Unable to answer: \"What is the name of the playlist I created on Spotify?\""} +{"question_id":"c5e8278d","hypothesis":"Unable to answer: \"What was my last name before I changed it?\""} +{"question_id":"6ade9755","hypothesis":"Unable to answer: \"Where do I take yoga classes?\""} +{"question_id":"6f9b354f","hypothesis":"Unable to answer: \"What color did I repaint my bedroom walls?\""} +{"question_id":"58ef2f1c","hypothesis":"Unable to answer: \"When did I volunteer at the local animal shelter's fundraising dinner?\""} +{"question_id":"f8c5f88b","hypothesis":"Unable to answer: \"Where did I buy my new tennis racket from?\""} +{"question_id":"5d3d2817","hypothesis":"Unable to answer: \"What was my previous occupation?\""} +{"question_id":"7527f7e2","hypothesis":"Unable to answer: \"How much did I spend on a designer handbag?\""} +{"question_id":"c960da58","hypothesis":"Unable to answer: \"How many playlists do I have on Spotify?\""} +{"question_id":"3b6f954b","hypothesis":"Unable to answer: \"Where did I attend for my study abroad program?\""} +{"question_id":"726462e0","hypothesis":"Unable to answer: \"What was the discount I got on my first purchase from the new clothing brand?\""} +{"question_id":"94f70d80","hypothesis":"Unable to answer: \"How long did it take me to assemble the IKEA bookshelf?\""} +{"question_id":"66f24dbb","hypothesis":"Unable to answer: \"What did I buy for my sister's birthday gift?\""} +{"question_id":"ad7109d1","hypothesis":"Unable to answer: \"What speed is my new internet plan?\""} +{"question_id":"af8d2e46","hypothesis":"Unable to answer: \"How many shirts did I pack for my 5-day trip to Costa Rica?\""} +{"question_id":"dccbc061","hypothesis":"Unable to answer: \"What was my previous stance on spirituality?\""} +{"question_id":"c8c3f81d","hypothesis":"Unable to answer: \"What brand are my favorite running shoes?\""} +{"question_id":"8ebdbe50","hypothesis":"Unable to answer: \"What certification did I complete last month?\""} +{"question_id":"6b168ec8","hypothesis":"Unable to answer: \"How many bikes do I own?\""} +{"question_id":"75499fd8","hypothesis":"Unable to answer: \"What breed is my dog?\""} +{"question_id":"21436231","hypothesis":"Unable to answer: \"How many largemouth bass did I catch on my fishing trip to Lake Michigan?\""} +{"question_id":"95bcc1c8","hypothesis":"Unable to answer: \"How many amateur comedians did I watch perform at the open mic night?\""} +{"question_id":"0862e8bf","hypothesis":"Unable to answer: \"What is the name of my cat?\""} +{"question_id":"853b0a1d","hypothesis":"Unable to answer: \"How old was I when my grandma gave me the silver necklace?\""} +{"question_id":"a06e4cfe","hypothesis":"Unable to answer: \"What is my preferred gin-to-vermouth ratio for a classic gin martini?\""} +{"question_id":"37d43f65","hypothesis":"Unable to answer: \"How much RAM did I upgrade my laptop to?\""} +{"question_id":"b86304ba","hypothesis":"Unable to answer: \"How much is the painting of a sunset worth in terms of the amount I paid for it?\""} +{"question_id":"d52b4f67","hypothesis":"Unable to answer: \"Where did I attend my cousin's wedding?\""} +{"question_id":"25e5aa4f","hypothesis":"Unable to answer: \"Where did I complete my Bachelor's degree in Computer Science?\""} +{"question_id":"caf9ead2","hypothesis":"Unable to answer: \"How long did it take to move to the new apartment?\""} +{"question_id":"8550ddae","hypothesis":"Unable to answer: \"What type of cocktail recipe did I try last weekend?\""} +{"question_id":"60d45044","hypothesis":"Unable to answer: \"What type of rice is my favorite?\""} +{"question_id":"3f1e9474","hypothesis":"Unable to answer: \"Who did I have a conversation with about destiny?\""} +{"question_id":"86b68151","hypothesis":"Unable to answer: \"Where did I buy my new bookshelf from?\""} +{"question_id":"577d4d32","hypothesis":"Unable to answer: \"What time do I stop checking work emails and messages?\""} +{"question_id":"ec81a493","hypothesis":"Unable to answer: \"How many copies of my favorite artist's debut album were released worldwide?\""} +{"question_id":"15745da0","hypothesis":"Unable to answer: \"How long have I been collecting vintage cameras?\""} +{"question_id":"e01b8e2f","hypothesis":"Unable to answer: \"Where did I go on a week-long trip with my family?\""} +{"question_id":"bc8a6e93","hypothesis":"Unable to answer: \"What did I bake for my niece's birthday party?\""} +{"question_id":"ccb36322","hypothesis":"Unable to answer: \"What is the name of the music streaming service have I been using lately?\""} +{"question_id":"001be529","hypothesis":"Unable to answer: \"How long did I wait for the decision on my asylum application?\""} +{"question_id":"b320f3f8","hypothesis":"Unable to answer: \"What type of action figure did I buy from a thrift store?\""} +{"question_id":"19b5f2b3","hypothesis":"Unable to answer: \"How long was I in Japan for?\""} +{"question_id":"4fd1909e","hypothesis":"Unable to answer: \"Where did I attend the Imagine Dragons concert?\""} +{"question_id":"545bd2b5","hypothesis":"Unable to answer: \"How much screen time have I been averaging on Instagram per day?\""} +{"question_id":"8a137a7f","hypothesis":"Unable to answer: \"What type of bulb did I replace in my bedside lamp?\""} +{"question_id":"76d63226","hypothesis":"Unable to answer: \"What size is my new Samsung TV?\""} +{"question_id":"86f00804","hypothesis":"Unable to answer: \"What book am I currently reading?\""} +{"question_id":"8e9d538c","hypothesis":"Unable to answer: \"How many skeins of worsted weight yarn did I find in my stash?\""} +{"question_id":"311778f1","hypothesis":"Unable to answer: \"How many hours did I spend watching documentaries on Netflix last month?\""} +{"question_id":"c19f7a0b","hypothesis":"Unable to answer: \"What time do I usually get home from work on weeknights?\""} +{"question_id":"4100d0a0","hypothesis":"Unable to answer: \"What is my ethnicity?\""} +{"question_id":"29f2956b","hypothesis":"Unable to answer: \"How much time do I dedicate to practicing guitar every day?\""} +{"question_id":"1faac195","hypothesis":"Unable to answer: \"Where does my sister Emily live?\""} +{"question_id":"faba32e5","hypothesis":"Unable to answer: \"How long did Alex marinate the BBQ ribs in special sauce?\""} +{"question_id":"f4f1d8a4","hypothesis":"Unable to answer: \"Who gave me a new stand mixer as a birthday gift?\""} +{"question_id":"c14c00dd","hypothesis":"Unable to answer: \"What brand of shampoo do I currently use?\""} +{"question_id":"36580ce8","hypothesis":"Unable to answer: \"What health issue did I initially think was just a cold?\""} +{"question_id":"3d86fd0a","hypothesis":"Unable to answer: \"Where did I meet Sophia?\""} +{"question_id":"a82c026e","hypothesis":"Unable to answer: \"What game did I finally beat last weekend?\""} +{"question_id":"0862e8bf_abs","hypothesis":"Unable to answer: \"What is the name of my hamster?\""} +{"question_id":"15745da0_abs","hypothesis":"Unable to answer: \"How long have I been collecting vintage films?\""} +{"question_id":"bc8a6e93_abs","hypothesis":"Unable to answer: \"What did I bake for my uncle's birthday party?\""} +{"question_id":"19b5f2b3_abs","hypothesis":"Unable to answer: \"How long was I in Korea for?\""} +{"question_id":"29f2956b_abs","hypothesis":"Unable to answer: \"How much time do I dedicate to practicing violin every day?\""} +{"question_id":"f4f1d8a4_abs","hypothesis":"Unable to answer: \"What did my dad gave me as a birthday gift?\""} +{"question_id":"gpt4_59149c77","hypothesis":"Unable to answer: \"How many days passed between my visit to the Museum of Modern Art (MoMA) and the 'Ancient Civilizations' exhibit at the Metropolitan Museum of Art?\""} +{"question_id":"gpt4_f49edff3","hypothesis":"Unable to answer: \"Which three events happened in the order from first to last: the day I helped my friend prepare the nursery, the day I helped my cousin pick out stuff for her baby shower, and the day I ordered a customized phone case for my friend's birthday?\""} +{"question_id":"71017276","hypothesis":"Unable to answer: \"How many weeks ago did I meet up with my aunt and receive the crystal chandelier?\""} +{"question_id":"b46e15ed","hypothesis":"Unable to answer: \"How many months have passed since I participated in two charity events in a row, on consecutive days?\""} +{"question_id":"gpt4_fa19884c","hypothesis":"Unable to answer: \"How many days passed between the day I started playing along to my favorite songs on my old keyboard and the day I discovered a bluegrass band?\""} +{"question_id":"0bc8ad92","hypothesis":"Unable to answer: \"How many months have passed since I last visited a museum with a friend?\""} +{"question_id":"af082822","hypothesis":"Unable to answer: \"How many weeks ago did I attend the friends and family sale at Nordstrom?\""} +{"question_id":"gpt4_4929293a","hypothesis":"Unable to answer: \"Which event happened first, my cousin's wedding or Michael's engagement party?\""} +{"question_id":"gpt4_b5700ca9","hypothesis":"Unable to answer: \"How many days ago did I attend the Maundy Thursday service at the Episcopal Church?\""} +{"question_id":"9a707b81","hypothesis":"Unable to answer: \"How many days ago did I attend a baking class at a local culinary school when I made my friend's birthday cake?\""} +{"question_id":"gpt4_1d4ab0c9","hypothesis":"Unable to answer: \"How many days passed between the day I started watering my herb garden and the day I harvested my first batch of fresh herbs?\""} +{"question_id":"gpt4_e072b769","hypothesis":"Unable to answer: \"How many weeks ago did I start using the cashback app 'Ibotta'?\""} +{"question_id":"0db4c65d","hypothesis":"Unable to answer: \"How many days had passed since I finished reading 'The Seven Husbands of Evelyn Hugo' when I attended the book reading event at the local library, where the author of 'The Silent Patient' is discussing her latest thriller novel?\""} +{"question_id":"gpt4_1d80365e","hypothesis":"Unable to answer: \"How many days did I spend on my solo camping trip to Yosemite National Park?\""} +{"question_id":"gpt4_7f6b06db","hypothesis":"Unable to answer: \"What is the order of the three trips I took in the past three months, from earliest to latest?\""} +{"question_id":"gpt4_6dc9b45b","hypothesis":"Unable to answer: \"How many months ago did I attend the Seattle International Film Festival?\""} +{"question_id":"gpt4_8279ba02","hypothesis":"Unable to answer: \"How many days ago did I buy a smoker?\""} +{"question_id":"gpt4_18c2b244","hypothesis":"Unable to answer: \"What is the order of the three events: 'I signed up for the rewards program at ShopRite', 'I used a Buy One Get One Free coupon on Luvs diapers at Walmart', and 'I redeemed $12 cashback for a $10 Amazon gift card from Ibotta'?\""} +{"question_id":"gpt4_a1b77f9c","hypothesis":"Unable to answer: \"How many weeks in total do I spent on reading 'The Nightingale' and listening to 'Sapiens: A Brief History of Humankind' and 'The Power'?\""} +{"question_id":"gpt4_1916e0ea","hypothesis":"Unable to answer: \"How many days passed between the day I cancelled my FarmFresh subscription and the day I did my online grocery shopping from Instacart?\""} +{"question_id":"gpt4_7a0daae1","hypothesis":"Unable to answer: \"How many weeks passed between the day I bought my new tennis racket and the day I received it?\""} +{"question_id":"gpt4_468eb063","hypothesis":"Unable to answer: \"How many days ago did I meet Emma?\""} +{"question_id":"gpt4_7abb270c","hypothesis":"Unable to answer: \"What is the order of the six museums I visited from earliest to latest?\""} +{"question_id":"gpt4_1e4a8aeb","hypothesis":"Unable to answer: \"How many days passed between the day I attended the gardening workshop and the day I planted the tomato saplings?\""} +{"question_id":"gpt4_4fc4f797","hypothesis":"Unable to answer: \"How many days passed between the day I received feedback about my car's suspension and the day I tested my new suspension setup?\""} +{"question_id":"4dfccbf7","hypothesis":"Unable to answer: \"How many days had passed since I started taking ukulele lessons when I decided to take my acoustic guitar to the guitar tech for servicing?\""} +{"question_id":"gpt4_61e13b3c","hypothesis":"Unable to answer: \"How many weeks passed between the time I sold homemade baked goods at the Farmers' Market for the last time and the time I participated in the Spring Fling Market?\""} +{"question_id":"gpt4_45189cb4","hypothesis":"Unable to answer: \"What is the order of the sports events I watched in January?\""} +{"question_id":"2ebe6c90","hypothesis":"Unable to answer: \"How many days did it take me to finish 'The Nightingale' by Kristin Hannah?\""} +{"question_id":"gpt4_e061b84f","hypothesis":"Unable to answer: \"What is the order of the three sports events I participated in during the past month, from earliest to latest?\""} +{"question_id":"370a8ff4","hypothesis":"Unable to answer: \"How many weeks had passed since I recovered from the flu when I went on my 10th jog outdoors?\""} +{"question_id":"gpt4_d6585ce8","hypothesis":"Unable to answer: \"What is the order of the concerts and musical events I attended in the past two months, starting from the earliest?\""} +{"question_id":"gpt4_4ef30696","hypothesis":"Unable to answer: \"How many days passed between the day I finished reading 'The Nightingale' and the day I started reading 'The Hitchhiker's Guide to the Galaxy'?\""} +{"question_id":"gpt4_ec93e27f","hypothesis":"Unable to answer: \"Which mode of transport did I use most recently, a bus or a train?\""} +{"question_id":"6e984301","hypothesis":"Unable to answer: \"How many weeks have I been taking sculpting classes when I invested in my own set of sculpting tools?\""} +{"question_id":"8077ef71","hypothesis":"Unable to answer: \"How many days ago did I attend a networking event?\""} +{"question_id":"gpt4_f420262c","hypothesis":"Unable to answer: \"What is the order of airlines I flew with from earliest to latest before today?\""} +{"question_id":"gpt4_8e165409","hypothesis":"Unable to answer: \"How many days passed between the day I repotted the previous spider plant and the day I gave my neighbor, Mrs. Johnson, a few cuttings from my spider plant?\""} +{"question_id":"gpt4_74aed68e","hypothesis":"Unable to answer: \"How many days passed between the day I replaced my spark plugs and the day I participated in the Turbocharged Tuesdays auto racking event?\""} +{"question_id":"bcbe585f","hypothesis":"Unable to answer: \"How many weeks ago did I attend a bird watching workshop at the local Audubon society?\""} +{"question_id":"gpt4_21adecb5","hypothesis":"Unable to answer: \"How many months passed between the completion of my undergraduate degree and the submission of my master's thesis?\""} +{"question_id":"5e1b23de","hypothesis":"Unable to answer: \"How many months ago did I attend the photography workshop?\""} +{"question_id":"gpt4_98f46fc6","hypothesis":"Unable to answer: \"Which event did I participate in first, the charity gala or the charity bake sale?\""} +{"question_id":"gpt4_af6db32f","hypothesis":"Unable to answer: \"How many days ago did I watch the Super Bowl?\""} +{"question_id":"eac54adc","hypothesis":"Unable to answer: \"How many days ago did I launch my website when I signed a contract with my first client?\""} +{"question_id":"gpt4_7ddcf75f","hypothesis":"Unable to answer: \"How many days ago did I go on a whitewater rafting trip in the Oregon mountains?\""} +{"question_id":"gpt4_a2d1d1f6","hypothesis":"Unable to answer: \"How many days ago did I harvest my first batch of fresh herbs from the herb garden kit?\""} +{"question_id":"gpt4_85da3956","hypothesis":"Unable to answer: \"How many weeks ago did I attend the 'Summer Nights' festival at Universal Studios Hollywood?\""} +{"question_id":"gpt4_b0863698","hypothesis":"Unable to answer: \"How many days ago did I participate in the 5K charity run?\""} +{"question_id":"gpt4_68e94287","hypothesis":"Unable to answer: \"Which event happened first, my participation in the #PlankChallenge or my post about vegan chili recipe?\""} +{"question_id":"gpt4_e414231e","hypothesis":"Unable to answer: \"How many days passed between the day I fixed my mountain bike and the day I decided to upgrade my road bike's pedals?\""} +{"question_id":"gpt4_7ca326fa","hypothesis":"Unable to answer: \"Who graduated first, second and third among Emma, Rachel and Alex?\""} +{"question_id":"gpt4_7bc6cf22","hypothesis":"Unable to answer: \"How many days ago did I read the March 15th issue of The New Yorker?\""} +{"question_id":"2ebe6c92","hypothesis":"Unable to answer: \"Which book did I finish a week ago?\""} +{"question_id":"gpt4_e061b84g","hypothesis":"Unable to answer: \"I mentioned participating in a sports event two weeks ago. What was the event?\""} +{"question_id":"71017277","hypothesis":"Unable to answer: \"I received a piece of jewelry last Saturday from whom?\""} +{"question_id":"b46e15ee","hypothesis":"Unable to answer: \"What charity event did I participate in a month ago?\""} +{"question_id":"gpt4_d6585ce9","hypothesis":"Unable to answer: \"Who did I go with to the music event last Saturday?\""} +{"question_id":"gpt4_1e4a8aec","hypothesis":"Unable to answer: \"What gardening-related activity did I do two weeks ago?\""} +{"question_id":"gpt4_f420262d","hypothesis":"Unable to answer: \"What was the airline that I flied with on Valentine's day?\""} +{"question_id":"gpt4_59149c78","hypothesis":"Unable to answer: \"I mentioned that I participated in an art-related event two weeks ago. Where was that event held at?\""} +{"question_id":"gpt4_e414231f","hypothesis":"Unable to answer: \"Which bike did I fixed or serviced the past weekend?\""} +{"question_id":"gpt4_4929293b","hypothesis":"Unable to answer: \"What was the the life event of one of my relatives that I participated in a week ago?\""} +{"question_id":"gpt4_468eb064","hypothesis":"Unable to answer: \"Who did I meet with during the lunch last Tuesday?\""} +{"question_id":"gpt4_fa19884d","hypothesis":"Unable to answer: \"What is the artist that I started to listen to last Friday?\""} +{"question_id":"9a707b82","hypothesis":"Unable to answer: \"I mentioned cooking something for my friend a couple of days ago. What was it?\""} +{"question_id":"eac54add","hypothesis":"Unable to answer: \"What was the significant buisiness milestone I mentioned four weeks ago?\""} +{"question_id":"4dfccbf8","hypothesis":"Unable to answer: \"What did I do with Rachel on the Wednesday two months ago?\""} +{"question_id":"0bc8ad93","hypothesis":"Unable to answer: \"I mentioned visiting a museum two months ago. Did I visit with a friend or not?\""} +{"question_id":"6e984302","hypothesis":"Unable to answer: \"I mentioned an investment for a competition four weeks ago? What did I buy?\""} +{"question_id":"gpt4_8279ba03","hypothesis":"Unable to answer: \"What kitchen appliance did I buy 10 days ago?\""} +{"question_id":"gpt4_b5700ca0","hypothesis":"Unable to answer: \"Where did I attend the religious activity last week?\""} +{"question_id":"gpt4_68e94288","hypothesis":"Unable to answer: \"What was the social media activity I participated 5 days ago?\""} +{"question_id":"d3ab962e","hypothesis":"Unable to answer: \"What is the total distance of the hikes I did on two consecutive weekends?\""} +{"question_id":"2311e44b","hypothesis":"Unable to answer: \"How many pages do I have left to read in 'The Nightingale'?\""} +{"question_id":"cc06de0d","hypothesis":"Unable to answer: \"For my daily commute, how much more expensive was the taxi ride compared to the train fare?\""} +{"question_id":"a11281a2","hypothesis":"Unable to answer: \"What was the approximate increase in Instagram followers I experienced in two weeks?\""} +{"question_id":"4f54b7c9","hypothesis":"Unable to answer: \"How many antique items did I inherit or acquire from my family members?\""} +{"question_id":"85fa3a3f","hypothesis":"Unable to answer: \"What is the total cost of the new food bowl, measuring cup, dental chews, and flea and tick collar I got for Max?\""} +{"question_id":"9aaed6a3","hypothesis":"Unable to answer: \"How much cashback did I earn at SaveMart last Thursday?\""} +{"question_id":"1f2b8d4f","hypothesis":"Unable to answer: \"What is the difference in price between my luxury boots and the similar pair found at the budget store?\""} +{"question_id":"e6041065","hypothesis":"Unable to answer: \"What percentage of packed shoes did I wear on my last trip?\""} +{"question_id":"51c32626","hypothesis":"Unable to answer: \"When did I submit my research paper on sentiment analysis?\""} +{"question_id":"d905b33f","hypothesis":"Unable to answer: \"What percentage discount did I get on the book from my favorite author?\""} +{"question_id":"7405e8b1","hypothesis":"Unable to answer: \"Did I receive a higher percentage discount on my first order from HelloFresh, compared to my first UberEats order?\""} +{"question_id":"f35224e0","hypothesis":"Unable to answer: \"What is the total number of episodes I've listened to from 'How I Built This' and 'My Favorite Murder'?\""} +{"question_id":"6456829e","hypothesis":"Unable to answer: \"How many plants did I initially plant for tomatoes and cucumbers?\""} +{"question_id":"a4996e51","hypothesis":"Unable to answer: \"How many hours do I work in a typical week during peak campaign seasons?\""} +{"question_id":"3c1045c8","hypothesis":"Unable to answer: \"How much older am I than the average age of employees in my department?\""} +{"question_id":"60036106","hypothesis":"Unable to answer: \"What was the total number of people reached by my Facebook ad campaign and Instagram influencer collaboration?\""} +{"question_id":"681a1674","hypothesis":"Unable to answer: \"How many Marvel movies did I re-watch?\""} +{"question_id":"e25c3b8d","hypothesis":"Unable to answer: \"How much did I save on the designer handbag at TK Maxx?\""} +{"question_id":"4adc0475","hypothesis":"Unable to answer: \"What is the total number of goals and assists I have in the recreational indoor soccer league?\""} +{"question_id":"4bc144e2","hypothesis":"Unable to answer: \"How much did I spend on car wash and parking ticket?\""} +{"question_id":"ef66a6e5","hypothesis":"Unable to answer: \"How many sports have I played competitively in the past?\""} +{"question_id":"5025383b","hypothesis":"Unable to answer: \"What are the two hobbies that led me to join online communities?\""} +{"question_id":"a1cc6108","hypothesis":"Unable to answer: \"How old was I when Alex was born?\""} +{"question_id":"9ee3ecd6","hypothesis":"Unable to answer: \"How many points do I need to earn to redeem a free skincare product at Sephora?\""} +{"question_id":"3fdac837","hypothesis":"Unable to answer: \"What is the total number of days I spent in Japan and Chicago?\""} +{"question_id":"91b15a6e","hypothesis":"Unable to answer: \"What is the minimum amount I could get if I sold the vintage diamond necklace and the antique vanity?\""} +{"question_id":"27016adc","hypothesis":"Unable to answer: \"What percentage of the countryside property's price is the cost of the renovations I plan to do on my current house?\""} +{"question_id":"720133ac","hypothesis":"Unable to answer: \"What is the total cost of Lola's vet visit and flea medication?\""} +{"question_id":"77eafa52","hypothesis":"Unable to answer: \"How much more did I have to pay for the trip after the initial quote?\""} +{"question_id":"8979f9ec","hypothesis":"Unable to answer: \"What is the total number of lunch meals I got from the chicken fajitas and lentil soup?\""} +{"question_id":"0100672e","hypothesis":"Unable to answer: \"How much did I spend on each coffee mug for my coworkers?\""} +{"question_id":"a96c20ee","hypothesis":"Unable to answer: \"At which university did I present a poster on my thesis research?\""} +{"question_id":"92a0aa75","hypothesis":"Unable to answer: \"How long have I been working in my current role?\""} +{"question_id":"3fe836c9","hypothesis":"Unable to answer: \"How much more was the pre-approval amount than the final sale price of the house?\""} +{"question_id":"1c549ce4","hypothesis":"Unable to answer: \"What is the total cost of the car cover and detailing spray I purchased?\""} +{"question_id":"6c49646a","hypothesis":"Unable to answer: \"What is the total distance I covered in my four road trips?\""} +{"question_id":"1192316e","hypothesis":"Unable to answer: \"What is the total time it takes I to get ready and commute to work?\""} +{"question_id":"0ea62687","hypothesis":"Unable to answer: \"How much more miles per gallon was my car getting a few months ago compared to now?\""} +{"question_id":"67e0d0f2","hypothesis":"Unable to answer: \"What is the total number of online courses I've completed?\""} +{"question_id":"bb7c3b45","hypothesis":"Unable to answer: \"How much did I save on the Jimmy Choo heels?\""} +{"question_id":"ba358f49","hypothesis":"Unable to answer: \"How many years will I be when my friend Rachel gets married?\""} +{"question_id":"61f8c8f8","hypothesis":"Unable to answer: \"How much faster did I finish the 5K run compared to my previous year's time?\""} +{"question_id":"60159905","hypothesis":"Unable to answer: \"How many dinner parties have I attended in the past month?\""} +{"question_id":"ef9cf60a","hypothesis":"Unable to answer: \"How much did I spend on gifts for my sister?\""} +{"question_id":"73d42213","hypothesis":"Unable to answer: \"What time did I reach the clinic on Monday?\""} +{"question_id":"bc149d6b","hypothesis":"Unable to answer: \"What is the total weight of the new feed I purchased in the past two months?\""} +{"question_id":"099778bb","hypothesis":"Unable to answer: \"What percentage of leadership positions do women hold in the my company?\""} +{"question_id":"09ba9854","hypothesis":"Unable to answer: \"How much will I save by taking the train from the airport to my hotel instead of a taxi?\""} +{"question_id":"d6062bb9","hypothesis":"Unable to answer: \"What is the total number of views on my most popular videos on YouTube and TikTok?\""} +{"question_id":"157a136e","hypothesis":"Unable to answer: \"How many years older is my grandma than me?\""} +{"question_id":"c18a7dc8","hypothesis":"Unable to answer: \"How many years older am I than when I graduated from college?\""} +{"question_id":"a3332713","hypothesis":"Unable to answer: \"What is the total amount I spent on gifts for my coworker and brother?\""} +{"question_id":"55241a1f","hypothesis":"Unable to answer: \"What is the total number of comments on my recent Facebook Live session and my most popular YouTube video?\""} +{"question_id":"a08a253f","hypothesis":"Unable to answer: \"How many days a week do I attend fitness classes?\""} +{"question_id":"f0e564bc","hypothesis":"Unable to answer: \"What is the total amount I spent on the designer handbag and high-end skincare products?\""} +{"question_id":"078150f1","hypothesis":"Unable to answer: \"How much more money did I raise than my initial goal in the charity cycling event?\""} +{"question_id":"8cf4d046","hypothesis":"Unable to answer: \"What is the average GPA of my undergraduate and graduate studies?\""} +{"question_id":"a346bb18","hypothesis":"Unable to answer: \"How many minutes did I exceed my target time by in the marathon?\""} +{"question_id":"37f165cf","hypothesis":"Unable to answer: \"What was the page count of the two novels I finished in January and March?\""} +{"question_id":"8e91e7d9","hypothesis":"Unable to answer: \"What is the total number of siblings I have?\""} +{"question_id":"87f22b4a","hypothesis":"Unable to answer: \"How much have I made from selling eggs this month?\""} +{"question_id":"e56a43b9","hypothesis":"Unable to answer: \"How much discount will I get on my next purchase at FreshMart?\""} +{"question_id":"efc3f7c2","hypothesis":"Unable to answer: \"How much earlier do I wake up on Fridays compared to other weekdays?\""} +{"question_id":"21d02d0d","hypothesis":"Unable to answer: \"How many fun runs did I miss in March due to work commitments?\""} +{"question_id":"2311e44b_abs","hypothesis":"Unable to answer: \"How many pages do I have left to read in 'Sapiens'?\""} +{"question_id":"6456829e_abs","hypothesis":"Unable to answer: \"How many plants did I initially plant for tomatoes and chili peppers?\""} +{"question_id":"e5ba910e_abs","hypothesis":"Unable to answer: \"What is the total cost of my recently purchased headphones and the iPad?\""} +{"question_id":"a96c20ee_abs","hypothesis":"Unable to answer: \"At which university did I present a poster for my undergrad course research project?\""} +{"question_id":"ba358f49_abs","hypothesis":"Unable to answer: \"How old will Rachel be when I get married?\""} +{"question_id":"09ba9854_abs","hypothesis":"Unable to answer: \"How much will I save by taking the bus from the airport to my hotel instead of a taxi?\""} \ No newline at end of file diff --git a/packages/benchmark/hf-space/Dockerfile b/packages/benchmark/hf-space/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3028a71c38fd240500ad0b8ea862a94d1dae141c --- /dev/null +++ b/packages/benchmark/hf-space/Dockerfile @@ -0,0 +1,125 @@ +# ============================================================================= +# Engram Benchmark - Hugging Face Spaces +# ============================================================================= +# GPU-enabled container for running LongMemEval benchmarks with L4 GPU. +# Designed for Hugging Face Spaces Docker deployment. +# +# Usage: +# 1. Push this to HF Spaces (engram/benchmark) +# 2. Select L4 GPU hardware ($0.80/hr) +# 3. Access web UI to trigger benchmark runs +# +# ============================================================================= + +# ----------------------------------------------------------------------------- +# Stage 1: Build dependencies +# ----------------------------------------------------------------------------- +FROM node:22-bookworm-slim AS builder + +WORKDIR /app + +# Install build essentials for native modules +RUN apt-get update && apt-get install -y \ + python3 \ + make \ + g++ \ + git \ + && rm -rf /var/lib/apt/lists/* + +# Copy monorepo package files +COPY package*.json ./ +COPY packages/benchmark/package.json packages/benchmark/ +COPY packages/search/package.json packages/search/ +COPY packages/graph/package.json packages/graph/ +COPY packages/storage/package.json packages/storage/ +COPY packages/logger/package.json packages/logger/ +COPY packages/common/package.json packages/common/ +COPY packages/temporal/package.json packages/temporal/ + +# Install all dependencies +RUN npm install --include=dev + +# Copy source code +COPY packages/ packages/ +COPY biome.json ./ + +# ----------------------------------------------------------------------------- +# Stage 2: Runtime image with CUDA support +# ----------------------------------------------------------------------------- +FROM nvidia/cuda:12.3.2-cudnn9-runtime-ubuntu22.04 + +# Install Node.js 22 LTS and system dependencies +RUN apt-get update && apt-get install -y \ + curl \ + ca-certificates \ + wget \ + jq \ + && curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \ + && apt-get install -y nodejs \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +# Copy built application from builder +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/packages ./packages +COPY --from=builder /app/package*.json ./ + +# Reinstall native modules for the runtime platform +RUN npm install --os=linux --cpu=x64 sharp + +# Model cache directory +ENV HF_HOME=/app/.cache +ENV TRANSFORMERS_CACHE=/app/.cache +ENV XDG_CACHE_HOME=/app/.cache + +# Create cache directory for models (downloaded on first run) +# Skipping model preload during Docker build to avoid build failures +# Models will be cached after first run +RUN mkdir -p /app/.cache + +# Install Qdrant for local vector search +RUN wget -q https://github.com/qdrant/qdrant/releases/download/v1.16.2/qdrant-x86_64-unknown-linux-gnu.tar.gz \ + && tar xzf qdrant-x86_64-unknown-linux-gnu.tar.gz -C /usr/local/bin \ + && rm qdrant-x86_64-unknown-linux-gnu.tar.gz \ + && mkdir -p /app/qdrant-storage + +# Install Redis 7.4+ for FalkorDB (Ubuntu 22.04 has old Redis, install from source) +RUN apt-get update && apt-get install -y \ + libgomp1 \ + build-essential \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir -p /app/falkordb-data \ + && wget -q https://github.com/redis/redis/archive/refs/tags/7.4.2.tar.gz \ + && tar xzf 7.4.2.tar.gz \ + && cd redis-7.4.2 && make -j$(nproc) && make install \ + && cd .. && rm -rf redis-7.4.2 7.4.2.tar.gz + +# Download FalkorDB module (v4.14.10 - latest) +RUN mkdir -p /opt/falkordb \ + && wget -q https://github.com/FalkorDB/FalkorDB/releases/download/v4.14.10/falkordb-x64.so -O /opt/falkordb/falkordb.so \ + && chmod +x /opt/falkordb/falkordb.so + +# Copy HF Space runner script +COPY packages/benchmark/hf-space/run.sh /app/run.sh +RUN chmod +x /app/run.sh + +# Create directories for data and results +RUN mkdir -p /data /results + +# Environment configuration +ENV NODE_ENV=production +ENV BENCHMARK_VERBOSE=true +ENV NODE_OPTIONS="--max-old-space-size=24576" + +# GPU mode with FP16 for L4 +ENV EMBEDDER_DEVICE=cuda +ENV EMBEDDER_DTYPE=fp16 +ENV QDRANT_URL=http://localhost:6333 +ENV FALKORDB_URL=redis://localhost:6379 + +# HF Spaces requires port 7860 +EXPOSE 7860 + +# Run the benchmark server +CMD ["/app/run.sh"] diff --git a/packages/benchmark/hf-space/README.md b/packages/benchmark/hf-space/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35708755091af9157d466dca31cca3b78b24031d --- /dev/null +++ b/packages/benchmark/hf-space/README.md @@ -0,0 +1,117 @@ +--- +title: Engram Benchmark +emoji: 🧠 +colorFrom: purple +colorTo: blue +sdk: docker +app_port: 7860 +suggested_hardware: l4x1 +suggested_storage: small +--- + +# Engram LongMemEval Benchmark + +GPU-accelerated benchmark runner for evaluating the Engram memory retrieval system on LongMemEval dataset. + +**Full Engram Stack:** FalkorDB (bitemporal graph) + Qdrant (vectors) running in-container. + +## Hardware + +This Space requires **L4 GPU** ($0.80/hr) for optimal performance: +- 24GB VRAM for embedding models (E5-large, fp16) +- CUDA 12.3 with cuDNN 9 for ONNX Runtime + +## API Endpoints + +| Endpoint | Method | Description | +|----------|--------|-------------| +| `/` | GET | Health check (shows FalkorDB + Qdrant status) | +| `/ingest` | POST | Ingest dataset into FalkorDB + Qdrant | +| `/start` | POST | Start benchmark (requires ingest first) | +| `/status` | GET | Get current status and output | +| `/results` | GET | Download results (when complete) | + +## Usage + +```bash +# Check health +curl https://engram-benchmark.hf.space/ + +# Step 1: Ingest data into FalkorDB (graph) + Qdrant (vectors) +curl -X POST https://engram-benchmark.hf.space/ingest + +# Wait for ingest to complete... +curl https://engram-benchmark.hf.space/status + +# Step 2: Run benchmark with full Engram pipeline +curl -X POST https://engram-benchmark.hf.space/start + +# Check status +curl https://engram-benchmark.hf.space/status + +# Step 3: Download results +curl https://engram-benchmark.hf.space/results > results.jsonl +``` + +## Architecture + +The benchmark runs the **full Engram stack**: + +``` +LongMemEval Dataset + ↓ + FalkorDB (bitemporal graph) + - Session nodes with timestamps + - Turn nodes with content + - Memory nodes for retrieval + ↓ + Qdrant (vector index) + - E5-large embeddings (fp16) + - Hybrid search (dense + sparse) + ↓ + Engram Retrieval Pipeline + - Graph traversal + vector search + - Session-aware hierarchical retrieval + - Temporal query parsing + ↓ + Gemini (answer generation) + ↓ + Results +``` + +## Configuration + +Set these secrets in the Space settings: + +| Secret | Description | +|--------|-------------| +| `GOOGLE_GENERATIVE_AI_API_KEY` | Gemini API key for answer generation | + +## Benchmark Features + +Full Engram pipeline with all optimizations: + +**Retrieval:** +- Dense embeddings (E5-large, 1024d, fp16) +- Sparse embeddings (SPLADE) +- Hybrid search with RRF fusion +- Multi-query expansion +- Session-aware hierarchical retrieval +- Temporal query parsing + +**Reranking:** +- Cross-encoder reranking (accurate tier) +- Deep candidate pool (50 docs) + +**Reading:** +- Chain-of-Note structured reasoning +- Time-aware query expansion + +**Abstention (3-layer):** +- Low retrieval confidence +- NLI answer grounding +- Hedging pattern detection + +## Results + +Results are saved to `/results/benchmark-results.jsonl` and can be downloaded via the `/results` endpoint. diff --git a/packages/benchmark/hf-space/deploy.sh b/packages/benchmark/hf-space/deploy.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e1438f276c86d868689ae90cbff3fe1e761cc24 --- /dev/null +++ b/packages/benchmark/hf-space/deploy.sh @@ -0,0 +1,97 @@ +#!/bin/bash +# ============================================================================= +# Deploy Engram Benchmark to Hugging Face Spaces +# ============================================================================= +# Prerequisites: +# - huggingface-cli installed: pip install huggingface_hub +# - Logged in: huggingface-cli login +# - HF_TOKEN environment variable set (for programmatic access) +# +# Usage: +# ./deploy.sh # Deploy to ccheney/engram-benchmark +# ./deploy.sh myorg/myspace # Deploy to custom space +# ============================================================================= + +set -euo pipefail + +SPACE_NAME="${1:-ccheney/engram-benchmark}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" + +echo "=== Deploying Engram Benchmark to HF Spaces ===" +echo "Space: $SPACE_NAME" +echo "Repo root: $REPO_ROOT" +echo "" + +# Check if hf CLI is installed +if ! command -v hf &> /dev/null; then + echo "Error: hf CLI not found" + echo "Install with: pip install huggingface_hub[cli]" + exit 1 +fi + +# Create temp directory for deployment +DEPLOY_DIR=$(mktemp -d) +trap "rm -rf $DEPLOY_DIR" EXIT + +echo "Preparing deployment in $DEPLOY_DIR..." + +# Copy HF Space files +cp "$SCRIPT_DIR/Dockerfile" "$DEPLOY_DIR/" +cp "$SCRIPT_DIR/README.md" "$DEPLOY_DIR/" +cp "$SCRIPT_DIR/run.sh" "$DEPLOY_DIR/" + +# Copy monorepo files needed for Docker build +cp "$REPO_ROOT/package.json" "$DEPLOY_DIR/" +cp "$REPO_ROOT/package-lock.json" "$DEPLOY_DIR/" 2>/dev/null || true +cp "$REPO_ROOT/biome.json" "$DEPLOY_DIR/" + +# Copy packages (only what's needed) +mkdir -p "$DEPLOY_DIR/packages" +for pkg in benchmark search graph storage logger common temporal; do + if [ -d "$REPO_ROOT/packages/$pkg" ]; then + echo " Copying packages/$pkg..." + cp -r "$REPO_ROOT/packages/$pkg" "$DEPLOY_DIR/packages/" + fi +done + +# Remove node_modules and build artifacts to reduce size +find "$DEPLOY_DIR" -name "node_modules" -type d -exec rm -rf {} + 2>/dev/null || true +find "$DEPLOY_DIR" -name ".turbo" -type d -exec rm -rf {} + 2>/dev/null || true +find "$DEPLOY_DIR" -name "*.tsbuildinfo" -delete 2>/dev/null || true + +# Copy benchmark dataset if available +if [ -f "$REPO_ROOT/packages/benchmark/data/longmemeval_oracle.json" ]; then + mkdir -p "$DEPLOY_DIR/packages/benchmark/data" + echo " Copying benchmark dataset..." + cp "$REPO_ROOT/packages/benchmark/data/longmemeval_oracle.json" "$DEPLOY_DIR/packages/benchmark/data/" +fi + +echo "" +echo "Deployment directory prepared. Contents:" +ls -la "$DEPLOY_DIR" +echo "" + +# Create or update the Space +echo "Pushing to Hugging Face Spaces..." +cd "$DEPLOY_DIR" + +# Initialize git if needed +git init -q +git add -A +git commit -q -m "Deploy Engram Benchmark" + +# Push to HF Spaces +hf upload "$SPACE_NAME" . . --repo-type space + +echo "" +echo "=== Deployment Complete ===" +echo "" +echo "Space URL: https://huggingface.co/spaces/$SPACE_NAME" +echo "" +echo "Next steps:" +echo " 1. Go to Space settings and set GOOGLE_GENERATIVE_AI_API_KEY secret" +echo " 2. Select L4 GPU hardware (\$0.80/hr)" +echo " 3. Wait for build to complete" +echo " 4. POST to /start to run benchmark" +echo "" diff --git a/packages/benchmark/hf-space/run.sh b/packages/benchmark/hf-space/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..34ce2319ab2d51e34d44c3655d515588f217a0fa --- /dev/null +++ b/packages/benchmark/hf-space/run.sh @@ -0,0 +1,303 @@ +#!/bin/bash +# ============================================================================= +# Engram Benchmark Runner for HF Spaces +# ============================================================================= +# Starts FalkorDB, Qdrant and runs the benchmark, serving status on port 7860 +# Full Engram stack: FalkorDB (graph) + Qdrant (vectors) +# ============================================================================= + +set -euo pipefail + +echo "=== Engram Benchmark Runner ===" +echo "Starting at $(date)" + +# ----------------------------------------------------------------------------- +# Start FalkorDB (Redis + FalkorDB module) +# ----------------------------------------------------------------------------- +echo "Starting FalkorDB..." +mkdir -p /app/falkordb-data + +# FalkorDB module path +FALKORDB_MODULE="/opt/falkordb/falkordb.so" +if [ ! -f "$FALKORDB_MODULE" ]; then + echo "ERROR: FalkorDB module not found at $FALKORDB_MODULE" + exit 1 +fi + +# Start Redis with FalkorDB module +echo "Starting redis-server with FalkorDB module..." +redis-server --daemonize yes \ + --port 6379 \ + --bind 127.0.0.1 \ + --dir /app/falkordb-data \ + --loadmodule "$FALKORDB_MODULE" \ + --loglevel verbose \ + --logfile /app/redis.log \ + --save "" \ + --appendonly no + +# Check if redis started +sleep 2 +if [ -f /app/redis.log ]; then + echo "Redis log (first 20 lines):" + head -20 /app/redis.log +fi + +# Wait for FalkorDB to be ready +echo "Waiting for FalkorDB..." +FALKOR_READY=0 +for i in $(seq 1 30); do + if redis-cli -h 127.0.0.1 ping 2>/dev/null | grep -q PONG; then + echo "FalkorDB is ready!" + redis-cli -h 127.0.0.1 MODULE LIST + FALKOR_READY=1 + break + fi + echo " Attempt $i: waiting..." + sleep 1 +done + +if [ "$FALKOR_READY" -eq 0 ]; then + echo "ERROR: FalkorDB failed to start!" + echo "Redis log:" + cat /app/redis.log 2>/dev/null || echo "No log file" + echo "Checking redis process:" + ps aux | grep redis || echo "No redis process" + exit 1 +fi + +# ----------------------------------------------------------------------------- +# Start Qdrant +# ----------------------------------------------------------------------------- +echo "Starting Qdrant..." +mkdir -p /app/qdrant-storage +cat > /app/qdrant-config.yaml << 'EOF' +storage: + storage_path: /app/qdrant-storage +service: + http_port: 6333 + grpc_port: 6334 +telemetry_disabled: true +EOF + +/usr/local/bin/qdrant --config-path /app/qdrant-config.yaml & +QDRANT_PID=$! + +echo "Waiting for Qdrant..." +for i in {1..30}; do + if curl -s http://localhost:6333/readyz > /dev/null 2>&1; then + echo "Qdrant is ready!" + break + fi + sleep 2 +done + +# ----------------------------------------------------------------------------- +# Check/Download Dataset +# ----------------------------------------------------------------------------- +if [ ! -f /data/longmemeval_oracle.json ]; then + echo "Checking for benchmark dataset..." + if [ -f /app/packages/benchmark/data/longmemeval_oracle.json ]; then + cp /app/packages/benchmark/data/longmemeval_oracle.json /data/ + echo "Dataset copied from app bundle" + else + echo "WARNING: No dataset found at /data/longmemeval_oracle.json" + echo "Upload dataset or include in packages/benchmark/data/" + fi +fi + +# ----------------------------------------------------------------------------- +# Create Server with Ingest + Benchmark APIs +# ----------------------------------------------------------------------------- +cat > /app/server.js << 'SERVEREOF' +const http = require("http"); +const { spawn } = require("child_process"); +const fs = require("fs"); + +let status = "idle"; +let ingestStatus = "not_started"; +let output = []; +let currentProcess = null; + +const server = http.createServer((req, res) => { + res.setHeader("Content-Type", "application/json"); + res.setHeader("Access-Control-Allow-Origin", "*"); + + // Health check + if (req.url === "/health" || req.url === "/") { + res.end(JSON.stringify({ + status: "ok", + benchmark: status, + ingest: ingestStatus, + falkordb: "redis://localhost:6379", + qdrant: "http://localhost:6333" + })); + return; + } + + // Ingest data into FalkorDB + if (req.url === "/ingest" && req.method === "POST") { + if (ingestStatus === "running") { + res.statusCode = 400; + res.end(JSON.stringify({ error: "Ingest already running" })); + return; + } + + ingestStatus = "running"; + output = []; + + // Run ingest script + const args = [ + "tsx", "packages/benchmark/src/cli/index.ts", + "ingest", + "--dataset", "/data/longmemeval_oracle.json", + "--falkor-url", "redis://localhost:6379", + "--qdrant-url", "http://localhost:6333", + "--verbose" + ]; + + currentProcess = spawn("npx", args, { cwd: "/app" }); + + currentProcess.stdout.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.log("[ingest]", line); + }); + + currentProcess.stderr.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.error("[ingest]", line); + }); + + currentProcess.on("close", (code) => { + ingestStatus = code === 0 ? "completed" : "failed"; + console.log(`Ingest finished with code ${code}`); + currentProcess = null; + }); + + res.end(JSON.stringify({ status: "ingest_started" })); + return; + } + + // Start benchmark + if (req.url === "/start" && req.method === "POST") { + if (status === "running") { + res.statusCode = 400; + res.end(JSON.stringify({ error: "Benchmark already running" })); + return; + } + + if (ingestStatus !== "completed") { + res.statusCode = 400; + res.end(JSON.stringify({ + error: "Data not ingested. POST /ingest first.", + ingestStatus + })); + return; + } + + status = "running"; + output = []; + + const args = [ + "tsx", "packages/benchmark/src/cli/index.ts", + "run", "longmemeval", + "--dataset", "/data/longmemeval_oracle.json", + "--variant", "oracle", + "--embeddings", "engram", + "--llm", "gemini", + "--gemini-model", "gemini-2.5-flash-preview-05-20", + "--falkor-url", "redis://127.0.0.1:6379", + "--qdrant-url", "http://localhost:6333", + "--top-k", "10", + "--hybrid-search", + "--rerank", + "--rerank-tier", "accurate", + "--rerank-depth", "50", + "--multi-query", + "--session-aware", + "--temporal-aware", + "--abstention", + "--abstention-hedging", + "--abstention-nli", + "--key-expansion", + "--temporal-analysis", + "--chain-of-note", + "--time-aware", + "--embedding-model", "e5-large", + "--verbose", + "--output", "/results/benchmark-results.jsonl" + ]; + + currentProcess = spawn("npx", args, { cwd: "/app" }); + + currentProcess.stdout.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.log("[benchmark]", line); + }); + + currentProcess.stderr.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.error("[benchmark]", line); + }); + + currentProcess.on("close", (code) => { + status = code === 0 ? "completed" : "failed"; + console.log(`Benchmark finished with code ${code}`); + currentProcess = null; + }); + + res.end(JSON.stringify({ status: "started" })); + return; + } + + // Get status + if (req.url === "/status") { + res.end(JSON.stringify({ + benchmark: status, + ingest: ingestStatus, + output: output.slice(-100).join(""), + resultsExist: fs.existsSync("/results/benchmark-results.jsonl") + })); + return; + } + + // Download results + if (req.url === "/results" && status === "completed") { + if (fs.existsSync("/results/benchmark-results.jsonl")) { + res.setHeader("Content-Type", "application/jsonl"); + fs.createReadStream("/results/benchmark-results.jsonl").pipe(res); + return; + } + res.statusCode = 404; + res.end(JSON.stringify({ error: "Results not found" })); + return; + } + + // 404 + res.statusCode = 404; + res.end(JSON.stringify({ error: "Not found" })); +}); + +server.listen(7860, "0.0.0.0", () => { + console.log("Engram Benchmark Server running on http://0.0.0.0:7860"); + console.log(""); + console.log("API Endpoints:"); + console.log(" GET / - Health check"); + console.log(" POST /ingest - Ingest dataset into FalkorDB + Qdrant"); + console.log(" POST /start - Start benchmark (requires ingest first)"); + console.log(" GET /status - Get current status"); + console.log(" GET /results - Download results (when complete)"); + console.log(""); + console.log("Workflow:"); + console.log(" 1. POST /ingest - Load data into graph + vectors"); + console.log(" 2. POST /start - Run benchmark with full Engram pipeline"); + console.log(" 3. GET /results - Download results"); +}); +SERVEREOF + +echo "Starting benchmark server..." +node /app/server.js diff --git a/packages/benchmark/package.json b/packages/benchmark/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a87192056340df419d42050d3a95f7174150dc23 --- /dev/null +++ b/packages/benchmark/package.json @@ -0,0 +1,35 @@ +{ + "name": "@engram/benchmark", + "version": "0.0.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "bin": { + "engram-benchmark": "./src/cli/index.ts" + }, + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + }, + "dependencies": { + "@ai-sdk/google": "^1.2.18", + "@engram/graph": "*", + "@engram/search": "*", + "@engram/storage": "*", + "@qdrant/js-client-rest": "^1.16.2", + "ai": "^4.3.16", + "commander": "^14.0.0", + "falkordb": "^6.4.1", + "zod": "^4.1.13" + }, + "optionalDependencies": { + "@anthropic-ai/sdk": "^0.52.0", + "@google/genai": "^1.0.0" + }, + "scripts": { + "build": "echo 'Build success'", + "typecheck": "tsc --noEmit", + "benchmark": "tsx src/cli/index.ts" + } +} diff --git a/packages/benchmark/results/benchmark-50-gpt4o-report.md b/packages/benchmark/results/benchmark-50-gpt4o-report.md new file mode 100644 index 0000000000000000000000000000000000000000..7c21c97c304e61b0338ab01eeb514ba6caa05d79 --- /dev/null +++ b/packages/benchmark/results/benchmark-50-gpt4o-report.md @@ -0,0 +1,38 @@ +# LongMemEval Benchmark Results + +## Overall +- Total: 50 +- Correct: 36 +- Accuracy: 72.0% + +## By Memory Ability + +| Ability | Total | Correct | Accuracy | +|:--------|------:|--------:|---------:| +| Information Extraction (IE) | 0 | 0 | 0.0% | +| Multi-Session Reasoning (MR) | 0 | 0 | 0.0% | +| Temporal Reasoning (TR) | 50 | 36 | 72.0% | +| Knowledge Update (KU) | 0 | 0 | 0.0% | +| Abstention (ABS) | 0 | 0 | 0.0% | + +## Retrieval Metrics + +- Turn Recall: 90.7% +- Session Recall: 90.7% +- MRR: 0.907 + +### Recall@K + +| K | Recall | +|--:|-------:| +| 1 | 0.0% | +| 5 | 0.0% | +| 10 | 90.7% | + +### NDCG@K + +| K | NDCG | +|--:|-----:| +| 1 | 0.000 | +| 5 | 0.000 | +| 10 | 0.907 | \ No newline at end of file diff --git a/packages/benchmark/results/benchmark-50-gpt4o.jsonl b/packages/benchmark/results/benchmark-50-gpt4o.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2040517f68089512106ea21b2f6ba87f038d0f15 --- /dev/null +++ b/packages/benchmark/results/benchmark-50-gpt4o.jsonl @@ -0,0 +1,50 @@ +{"question_id":"gpt4_2655b836","hypothesis":"The first issue the user had with their new car after its first service was a GPS system issue."} +{"question_id":"gpt4_2487a7cb","hypothesis":"The 'Data Analysis using Python' webinar was attended first."} +{"question_id":"gpt4_76048e76","hypothesis":"The bike was taken care of first in February."} +{"question_id":"gpt4_2312f94c","hypothesis":"The Samsung Galaxy S22."} +{"question_id":"0bb5a684","hypothesis":"7 days"} +{"question_id":"08f4fc43","hypothesis":"30 days"} +{"question_id":"2c63a862","hypothesis":"It took 14 days for you to find a house you loved after starting to work with Rachel."} +{"question_id":"gpt4_385a5000","hypothesis":"There is no information on when the tomato seeds were started, so we cannot determine which seeds were started first."} +{"question_id":"2a1811e2","hypothesis":"21 days"} +{"question_id":"bbf86515","hypothesis":"4 days"} +{"question_id":"gpt4_5dcc0aab","hypothesis":"White Adidas sneakers"} +{"question_id":"gpt4_0b2f1d21","hypothesis":"The malfunction of the stand mixer happened first."} +{"question_id":"f0853d11","hypothesis":"14 days"} +{"question_id":"gpt4_6ed717ea","hypothesis":"The training pads for Luna were purchased first."} +{"question_id":"gpt4_70e84552","hypothesis":"You completed fixing the fence first."} +{"question_id":"a3838d2b","hypothesis":"2"} +{"question_id":"gpt4_93159ced","hypothesis":"The user has been working for 4 years and 9 months before starting at NovaTech."} +{"question_id":"gpt4_2d58bcd6","hypothesis":"'The Hate U Give'"} +{"question_id":"gpt4_65aabe59","hypothesis":"The smart thermostat was set up first."} +{"question_id":"982b5123","hypothesis":"5 months ago"} +{"question_id":"b9cfe692","hypothesis":"The user took a combined total of 5.5 weeks to finish 'The Seven Husbands of Evelyn Hugo' and 'The Nightingale'."} +{"question_id":"gpt4_4edbafa2","hypothesis":"The date on which you attended the first BBQ event in June was the 3rd of June."} +{"question_id":"c8090214","hypothesis":"The user attended the Holiday Market 7 days before purchasing the iPhone 13 Pro."} +{"question_id":"gpt4_483dd43c","hypothesis":"Cannot determine which show was started first based on the provided information."} +{"question_id":"e4e14d04","hypothesis":"The user had been a member of 'Book Lovers Unite' for two weeks when they attended the meetup."} +{"question_id":"c9f37c46","hypothesis":"The user had been watching stand-up comedy specials regularly for about 2 months when they attended the open mic night at the local comedy club."} +{"question_id":"gpt4_2c50253f","hypothesis":"6:45 AM"} +{"question_id":"dcfa8644","hypothesis":"14 days"} +{"question_id":"gpt4_b4a80587","hypothesis":"The arrival of the new prime lens happened first."} +{"question_id":"gpt4_9a159967","hypothesis":"United Airlines"} +{"question_id":"cc6d1ec1","hypothesis":"The user had been bird watching for about three months when they attended the bird watching workshop."} +{"question_id":"gpt4_8c8961ae","hypothesis":"The solo trip to Thailand was taken first."} +{"question_id":"gpt4_d9af6064","hypothesis":"The new router was set up first."} +{"question_id":"gpt4_7de946e7","hypothesis":"The persistent cough was dealt with first."} +{"question_id":"d01c6aa8","hypothesis":"You were 27 years old when you moved to the United States."} +{"question_id":"993da5e2","hypothesis":"You had been using the new area rug for about one week when you rearranged your living room furniture."} +{"question_id":"a3045048","hypothesis":"The user ordered the gift 7 days before the birthday party."} +{"question_id":"gpt4_d31cdae3","hypothesis":"The family road trip across the American Southwest was taken first."} +{"question_id":"gpt4_cd90e484","hypothesis":"The user used their new binoculars for two weeks before seeing the American goldfinches returning to the area."} +{"question_id":"gpt4_88806d6e","hypothesis":"You met Tom first."} +{"question_id":"gpt4_4cd9eba1","hypothesis":"1 week"} +{"question_id":"gpt4_93f6379c","hypothesis":"'Page Turners'"} +{"question_id":"b29f3365","hypothesis":"You had been taking guitar lessons for 4 weeks when you bought the new guitar amp."} +{"question_id":"gpt4_2f56ae70","hypothesis":"Apple TV+"} +{"question_id":"6613b389","hypothesis":"Rachel got engaged approximately two months before the user's anniversary."} +{"question_id":"gpt4_78cf46a3","hypothesis":"The narrator received their new phone case first."} +{"question_id":"gpt4_0a05b494","hypothesis":"The user met the woman selling jam at the farmer's market first."} +{"question_id":"gpt4_1a1dc16d","hypothesis":"The meeting with Rachel happened first."} +{"question_id":"gpt4_2f584639","hypothesis":"The photo album for your mom was bought first."} +{"question_id":"gpt4_213fd887","hypothesis":"You participated in the volleyball league first."} \ No newline at end of file diff --git a/packages/benchmark/results/full-run-20251218-report.md b/packages/benchmark/results/full-run-20251218-report.md new file mode 100644 index 0000000000000000000000000000000000000000..b80f2ab6f8163083b4aaf9eee86255758c8aeeb7 --- /dev/null +++ b/packages/benchmark/results/full-run-20251218-report.md @@ -0,0 +1,38 @@ +# LongMemEval Benchmark Results + +## Overall +- Total: 500 +- Correct: 379 +- Accuracy: 75.8% + +## By Memory Ability + +| Ability | Total | Correct | Accuracy | +|:--------|------:|--------:|---------:| +| Information Extraction (IE) | 150 | 140 | 93.3% | +| Multi-Session Reasoning (MR) | 121 | 90 | 74.4% | +| Temporal Reasoning (TR) | 127 | 91 | 71.7% | +| Knowledge Update (KU) | 72 | 55 | 76.4% | +| Abstention (ABS) | 30 | 3 | 10.0% | + +## Retrieval Metrics + +- Turn Recall: 79.5% +- Session Recall: 79.5% +- MRR: 0.795 + +### Recall@K + +| K | Recall | +|--:|-------:| +| 1 | 0.0% | +| 5 | 0.0% | +| 10 | 79.5% | + +### NDCG@K + +| K | NDCG | +|--:|-----:| +| 1 | 0.000 | +| 5 | 0.000 | +| 10 | 0.795 | \ No newline at end of file diff --git a/packages/benchmark/results/full-run-20251218.jsonl b/packages/benchmark/results/full-run-20251218.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..96b0ef548c936b2e1081be8046c435d763a45b6e --- /dev/null +++ b/packages/benchmark/results/full-run-20251218.jsonl @@ -0,0 +1,500 @@ +{"question_id":"gpt4_2655b836","hypothesis":"The car's GPS system failed (on 3/22), requiring the dealership to replace the entire system."} +{"question_id":"gpt4_2487a7cb","hypothesis":"The 'Data Analysis using Python' webinar was attended first (about two months ago); the 'Effective Time Management' workshop was attended more recently (last Saturday)."} +{"question_id":"gpt4_76048e76","hypothesis":"The bike"} +{"question_id":"gpt4_2312f94c","hypothesis":"Samsung Galaxy S22"} +{"question_id":"0bb5a684","hypothesis":"7 days"} +{"question_id":"08f4fc43","hypothesis":"30 days"} +{"question_id":"2c63a862","hypothesis":""} +{"question_id":"gpt4_385a5000","hypothesis":"Cannot determine from the conversation history (no start date given for tomato seeds)."} +{"question_id":"2a1811e2","hypothesis":"21 days"} +{"question_id":"bbf86515","hypothesis":"4 days"} +{"question_id":"gpt4_5dcc0aab","hypothesis":"white Adidas sneakers"} +{"question_id":"gpt4_0b2f1d21","hypothesis":"The malfunction of the stand mixer happened first."} +{"question_id":"f0853d11","hypothesis":"14 days"} +{"question_id":"gpt4_6ed717ea","hypothesis":"The training pads for Luna were purchased first."} +{"question_id":"gpt4_70e84552","hypothesis":"Fixing the fence was completed first."} +{"question_id":"a3838d2b","hypothesis":""} +{"question_id":"gpt4_93159ced","hypothesis":"Cannot be determined from the conversation history."} +{"question_id":"gpt4_2d58bcd6","hypothesis":"The Hate U Give"} +{"question_id":"gpt4_65aabe59","hypothesis":"Cannot determine from the conversation history which device was set up first (smart thermostat vs. mesh network)."} +{"question_id":"982b5123","hypothesis":"5 months ago"} +{"question_id":"b9cfe692","hypothesis":"5.5 weeks (about 38.5 days)."} +{"question_id":"gpt4_4edbafa2","hypothesis":"June 3rd"} +{"question_id":"c8090214","hypothesis":"7 days"} +{"question_id":"gpt4_483dd43c","hypothesis":""} +{"question_id":"e4e14d04","hypothesis":"Cannot be determined from the conversation history; no explicit information about how long you had been a member is provided."} +{"question_id":"c9f37c46","hypothesis":"Cannot determine from the conversation history. The user did not state how long they had been watching stand-up comedy specials regularly."} +{"question_id":"gpt4_2c50253f","hypothesis":"6:45 AM"} +{"question_id":"dcfa8644","hypothesis":"14 days"} +{"question_id":"gpt4_b4a80587","hypothesis":"The arrival of the new prime lens happened before the road trip to the coast."} +{"question_id":"gpt4_9a159967","hypothesis":""} +{"question_id":"cc6d1ec1","hypothesis":"I cannot determine how long you had been bird watching when you attended the workshop from the conversation history."} +{"question_id":"gpt4_8c8961ae","hypothesis":"The solo trip to Thailand was first."} +{"question_id":"gpt4_d9af6064","hypothesis":"The new router was set up first."} +{"question_id":"gpt4_7de946e7","hypothesis":"The persistent cough came first."} +{"question_id":"d01c6aa8","hypothesis":"Cannot determine from the conversation history; the user's age when they moved to the United States is not provided."} +{"question_id":"993da5e2","hypothesis":"About one week."} +{"question_id":"a3045048","hypothesis":"7 days"} +{"question_id":"gpt4_d31cdae3","hypothesis":"The family road trip across the American Southwest happened before the solo trip to Europe."} +{"question_id":"gpt4_cd90e484","hypothesis":""} +{"question_id":"gpt4_88806d6e","hypothesis":"Cannot be determined from the conversation history."} +{"question_id":"gpt4_4cd9eba1","hypothesis":"1 week"} +{"question_id":"gpt4_93f6379c","hypothesis":""} +{"question_id":"b29f3365","hypothesis":"4 weeks"} +{"question_id":"gpt4_2f56ae70","hypothesis":"Apple TV+"} +{"question_id":"6613b389","hypothesis":"About 2 months (roughly 2 months and 1 week)."} +{"question_id":"gpt4_78cf46a3","hypothesis":"The narrator receiving their new phone case happened first."} +{"question_id":"gpt4_0a05b494","hypothesis":"The woman (jam maker) at the farmer's market was met first."} +{"question_id":"gpt4_1a1dc16d","hypothesis":"The meeting with Rachel happened first (April 10), and the pride parade occurred later (May 1)."} +{"question_id":"gpt4_2f584639","hypothesis":"Cannot determine from the conversation. The photo album was ordered two weeks ago, but the conversation does not state when the Tiffany's necklace was purchased, so we cannot tell which was bought first."} +{"question_id":"gpt4_213fd887","hypothesis":"The volleyball league."} +{"question_id":"gpt4_5438fa52","hypothesis":"The start of your Spanish classes happened before your attendance at the cultural festival."} +{"question_id":"gpt4_c27434e8","hypothesis":"The Japanese Zero fighter plane model was started before the Ferrari model."} +{"question_id":"gpt4_fe651585","hypothesis":"Rachel"} +{"question_id":"8c18457d","hypothesis":"7 days"} +{"question_id":"gpt4_70e84552_abs","hypothesis":"Cannot determine — the conversation records the fence was fixed three weeks ago, but contains no information that you purchased three cows from Peter."} +{"question_id":"gpt4_93159ced_abs","hypothesis":"Cannot determine — the conversation history does not state any employment at Google or a start date there, so there is insufficient information to calculate how long you had been working before starting a job at Google."} +{"question_id":"982b5123_abs","hypothesis":"I cannot determine when you booked the Airbnb in Sacramento because the conversation history contains no information about an Airbnb in Sacramento or its booking date."} +{"question_id":"c8090214_abs","hypothesis":"Cannot answer — the conversation does not state when (or if) you bought an iPad."} +{"question_id":"gpt4_c27434e8_abs","hypothesis":"Cannot determine — the conversation contains a start date for the Ferrari 288 GTO (about three weeks ago) but contains no information about a Porsche 991 Turbo S project or when it was started."} +{"question_id":"gpt4_fe651585_abs","hypothesis":"Cannot determine from the conversation history — Alex's adoption in January is mentioned, but there is no information about Tom."} +{"question_id":"0a995998","hypothesis":""} +{"question_id":"6d550036","hypothesis":"Cannot determine from the conversation history — no information about the number of projects led or currently being led is provided."} +{"question_id":"gpt4_59c863d7","hypothesis":""} +{"question_id":"b5ef892d","hypothesis":"8 days"} +{"question_id":"e831120c","hypothesis":"Marvel Cinematic Universe: ~2 weeks; Main Star Wars films: ~1.5 weeks. Combined total: ~3.5 weeks."} +{"question_id":"3a704032","hypothesis":"3"} +{"question_id":"gpt4_d84a3211","hypothesis":"$65"} +{"question_id":"aae3761f","hypothesis":""} +{"question_id":"gpt4_f2262a51","hypothesis":""} +{"question_id":"dd2973ad","hypothesis":"2 AM"} +{"question_id":"c4a1ceb8","hypothesis":""} +{"question_id":"gpt4_a56e767c","hypothesis":""} +{"question_id":"6cb6f249","hypothesis":"17 days"} +{"question_id":"46a3abf7","hypothesis":"2"} +{"question_id":"36b9f61e","hypothesis":"$2,500"} +{"question_id":"28dc39ac","hypothesis":""} +{"question_id":"gpt4_2f8be40d","hypothesis":""} +{"question_id":"2e6d26dc","hypothesis":"5"} +{"question_id":"gpt4_15e38248","hypothesis":""} +{"question_id":"88432d0a","hypothesis":""} +{"question_id":"80ec1f4f","hypothesis":"1"} +{"question_id":"d23cf73b","hypothesis":""} +{"question_id":"gpt4_7fce9456","hypothesis":"One property (the 3-bedroom townhouse in Brookside)."} +{"question_id":"d682f1a2","hypothesis":"3"} +{"question_id":"7024f17c","hypothesis":""} +{"question_id":"gpt4_5501fe77","hypothesis":"TikTok"} +{"question_id":"gpt4_2ba83207","hypothesis":"Walmart (about $120)"} +{"question_id":"2318644b","hypothesis":"You spent more than $270 more per night in Hawaii than in Tokyo."} +{"question_id":"2ce6a0f2","hypothesis":""} +{"question_id":"gpt4_d12ceb0e","hypothesis":"59.6 years"} +{"question_id":"00ca467f","hypothesis":"2"} +{"question_id":"b3c15d39","hypothesis":"5 days"} +{"question_id":"gpt4_31ff4165","hypothesis":"1"} +{"question_id":"eeda8a6d","hypothesis":"Cannot determine total number of fish. The conversation only specifies one fish by number (Bubbles the betta). Counts for neon tetras, gouramis, pleco, and any others are not provided."} +{"question_id":"2788b940","hypothesis":""} +{"question_id":"60bf93ed","hypothesis":"5 days"} +{"question_id":"9d25d4e0","hypothesis":"2"} +{"question_id":"129d1232","hypothesis":""} +{"question_id":"60472f9c","hypothesis":"2"} +{"question_id":"gpt4_194be4b3","hypothesis":"3"} +{"question_id":"a9f6b44c","hypothesis":""} +{"question_id":"d851d5ba","hypothesis":"Over $3,500 total (at least $3,500 based on the reported amounts: $500 + $2,000 + over $1,000)."} +{"question_id":"5a7937c8","hypothesis":"3 days"} +{"question_id":"gpt4_ab202e7f","hypothesis":"2"} +{"question_id":"gpt4_e05b82a6","hypothesis":"7 rollercoaster rides"} +{"question_id":"gpt4_731e37d7","hypothesis":"Cannot determine — the conversation does not state any money amounts or prices for the workshops, so total spend in the last four months is unknown."} +{"question_id":"edced276","hypothesis":"Cannot determine total days because the duration of the Hawaii trip is not provided. The New York City trip was 5 days."} +{"question_id":"10d9b85a","hypothesis":"3 days"} +{"question_id":"e3038f8c","hypothesis":""} +{"question_id":"2b8f3739","hypothesis":"$495"} +{"question_id":"1a8a66a6","hypothesis":""} +{"question_id":"c2ac3c61","hypothesis":"5"} +{"question_id":"bf659f65","hypothesis":""} +{"question_id":"gpt4_372c3eed","hypothesis":""} +{"question_id":"gpt4_2f91af09","hypothesis":"23 pieces"} +{"question_id":"81507db6","hypothesis":""} +{"question_id":"88432d0a_abs","hypothesis":"Cannot determine — the conversation contains no information about how many times you baked egg tarts in the past two weeks."} +{"question_id":"80ec1f4f_abs","hypothesis":"Cannot determine — no visits in December are mentioned in the conversation history."} +{"question_id":"eeda8a6d_abs","hypothesis":""} +{"question_id":"60bf93ed_abs","hypothesis":"Cannot determine — the conversation history contains no information about an iPad case purchase or arrival."} +{"question_id":"edced276_abs","hypothesis":"Cannot determine total. The conversation implies the Hawaii family trip was 10 days, but the number of days spent in Seattle is not mentioned, so the combined total cannot be calculated from the given history."} +{"question_id":"gpt4_372c3eed_abs","hypothesis":"Cannot answer — the conversation does not provide the number of years spent in high school nor confirm completion or duration of a Master's degree, so total years cannot be determined."} +{"question_id":"6a1eabeb","hypothesis":"27:12"} +{"question_id":"6aeb4375","hypothesis":"4"} +{"question_id":"830ce83f","hypothesis":"Chicago"} +{"question_id":"852ce960","hypothesis":"Cannot determine from the conversation — the history contains two different explicit claims: $350,000 and $400,000."} +{"question_id":"945e3d21","hypothesis":"Three times a week."} +{"question_id":"d7c942c3","hypothesis":"Yes — according to the conversation, your mom is now using the same grocery list app as you."} +{"question_id":"71315a70","hypothesis":"10-12 hours"} +{"question_id":"89941a93","hypothesis":""} +{"question_id":"ce6d2d27","hypothesis":"Cannot determine from the conversation history (both Thursday and Friday are stated)."} +{"question_id":"9ea5eabc","hypothesis":"Paris"} +{"question_id":"07741c44","hypothesis":"Under the bed."} +{"question_id":"a1eacc2a","hypothesis":"7 short stories"} +{"question_id":"184da446","hypothesis":"220 pages"} +{"question_id":"031748ae","hypothesis":"When you just started your new role you led 4 engineers. Now you lead 5 engineers."} +{"question_id":"4d6b87c8","hypothesis":"25"} +{"question_id":"0f05491a","hypothesis":""} +{"question_id":"08e075c7","hypothesis":"9 months"} +{"question_id":"f9e8c073","hypothesis":"Cannot determine from the conversation history (user stated both 3 sessions and 5 sessions at different times)."} +{"question_id":"41698283","hypothesis":"50mm prime lens"} +{"question_id":"2698e78f","hypothesis":"You see Dr. Smith every week."} +{"question_id":"b6019101","hypothesis":"5 MCU films"} +{"question_id":"45dc21b6","hypothesis":"3"} +{"question_id":"5a4f22c0","hypothesis":"TechCorp"} +{"question_id":"6071bd76","hypothesis":"You switched to less water per tablespoon (from 6 oz/tbsp down to 5 oz/tbsp)."} +{"question_id":"e493bb7c","hypothesis":"Above the bed in the user's bedroom."} +{"question_id":"618f13b2","hypothesis":"6 times"} +{"question_id":"72e3ee87","hypothesis":"50"} +{"question_id":"c4ea545c","hypothesis":"Yes — you go to the gym more frequently now (4 times per week) than previously (3 times per week)."} +{"question_id":"01493427","hypothesis":"25 new postcards"} +{"question_id":"6a27ffc2","hypothesis":"30 videos"} +{"question_id":"2133c1b5","hypothesis":""} +{"question_id":"18bc8abd","hypothesis":"Kansas City Masterpiece BBQ sauce"} +{"question_id":"db467c8c","hypothesis":"Nine months."} +{"question_id":"7a87bd0c","hypothesis":"4 weeks"} +{"question_id":"e61a7584","hypothesis":"About 9 months (as of 2023-11-30)."} +{"question_id":"1cea1afa","hypothesis":"600 followers"} +{"question_id":"ed4ddc30","hypothesis":"20 dozen"} +{"question_id":"8fb83627","hypothesis":"3"} +{"question_id":"b01defab","hypothesis":"Yes — you finished reading 'The Nightingale' by Kristin Hannah."} +{"question_id":"22d2cb42","hypothesis":"At a music shop on Main St. (You mentioned 'Rhythm Central' as a likely shop, but you did not explicitly confirm it was the one that serviced your guitar.)"} +{"question_id":"0e4e4c46","hypothesis":"132 points"} +{"question_id":"4b24c848","hypothesis":"5"} +{"question_id":"7e974930","hypothesis":"$420"} +{"question_id":"603deb26","hypothesis":"10 times"} +{"question_id":"59524333","hypothesis":""} +{"question_id":"5831f84d","hypothesis":"15"} +{"question_id":"eace081b","hypothesis":"Oahu"} +{"question_id":"affe2881","hypothesis":"32 species"} +{"question_id":"50635ada","hypothesis":"Premier Silver"} +{"question_id":"e66b632c","hypothesis":""} +{"question_id":"0ddfec37","hypothesis":"15 autographed baseballs"} +{"question_id":"f685340e","hypothesis":""} +{"question_id":"cc5ded98","hypothesis":"About two hours each day (based on the user's most recent messages on 2023-05-27)."} +{"question_id":"dfde3500","hypothesis":"Wednesday"} +{"question_id":"69fee5aa","hypothesis":"37"} +{"question_id":"7401057b","hypothesis":"Two free nights"} +{"question_id":"cf22b7bf","hypothesis":"10 pounds"} +{"question_id":"a2f3aa27","hypothesis":"1250"} +{"question_id":"c7dc5443","hypothesis":"5-2"} +{"question_id":"06db6396","hypothesis":"5 projects"} +{"question_id":"3ba21379","hypothesis":"Ford F-150 pickup truck"} +{"question_id":"9bbe84a2","hypothesis":"Level 100"} +{"question_id":"10e09553","hypothesis":"7 largemouth bass"} +{"question_id":"dad224aa","hypothesis":"8:30 am"} +{"question_id":"ba61f0b9","hypothesis":"Cannot determine from conversation: the history contains conflicting statements (5 women and 6 women are both stated)."} +{"question_id":"42ec0761","hypothesis":"Yes — according to your later message (2023-08-15), you have a spare screwdriver available for opening your laptop."} +{"question_id":"5c40ec5b","hypothesis":"Twice (2 times)"} +{"question_id":"c6853660","hypothesis":"You most recently increased the limit (to two cups)."} +{"question_id":"26bdc477","hypothesis":"5 trips"} +{"question_id":"0977f2af","hypothesis":"Instant Pot"} +{"question_id":"6aeb4375_abs","hypothesis":"Cannot determine from the conversation history — no Italian restaurants are mentioned."} +{"question_id":"031748ae_abs","hypothesis":"4 engineers"} +{"question_id":"2698e78f_abs","hypothesis":"I cannot answer — there is no information in the conversation history about Dr. Johnson or how often you see them."} +{"question_id":"2133c1b5_abs","hypothesis":"Cannot determine from the conversation history — there is no information about the duration of living in a Shinjuku apartment."} +{"question_id":"0ddfec37_abs","hypothesis":"Cannot be determined from the conversation history (no mention of autographed footballs)."} +{"question_id":"f685340e_abs","hypothesis":"I cannot answer — the conversation contains no explicit information about how often you play table tennis at the local park. It only mentions (regular) tennis, with conflicting mentions of 'every other week' and 'weekly.'"} +{"question_id":"89941a94","hypothesis":"Yes. Before acquiring the later bike(s), you already had a road bike in addition to your mountain bike and commuter bike."} +{"question_id":"07741c45","hypothesis":"Under your bed."} +{"question_id":"8a2466db","hypothesis":"Recommended resources: 1) Adobe Premiere Pro official documentation and tutorials. 2) YouTube channels: Premiere Bro, Video Copilot, and Adobe Creative Cloud. 3) Online course platforms: Udemy, LinkedIn Learning, and Skillshare. 4) Communities/forums: Reddit's r/premierepro and Adobe's Premiere Pro forum. Also, practice and experiment with small projects as you learn."} +{"question_id":"06878be2","hypothesis":""} +{"question_id":"75832dbd","hypothesis":""} +{"question_id":"0edc2aef","hypothesis":"I cannot suggest a hotel in Miami based only on this conversation history, which contains information only about The Edgewater Hotel in Seattle. Please provide preferences or details about Miami (neighborhood, budget, desired amenities) or allow me to search for Miami hotels."} +{"question_id":"35a27287","hypothesis":""} +{"question_id":"32260d93","hypothesis":"Watch 'Hasan Minhaj: Homecoming King' — a Netflix stand-up special with strong, personal storytelling that should appeal if you like John Mulaney's narrative-driven style."} +{"question_id":"195a1a1b","hypothesis":""} +{"question_id":"afdc33df","hypothesis":""} +{"question_id":"caf03d32","hypothesis":""} +{"question_id":"54026fce","hypothesis":""} +{"question_id":"06f04340","hypothesis":""} +{"question_id":"6b7dfb22","hypothesis":""} +{"question_id":"1a1907b4","hypothesis":""} +{"question_id":"09d032c9","hypothesis":""} +{"question_id":"38146c39","hypothesis":""} +{"question_id":"d24813b1","hypothesis":""} +{"question_id":"57f827a0","hypothesis":""} +{"question_id":"95228167","hypothesis":""} +{"question_id":"505af2f5","hypothesis":""} +{"question_id":"75f70248","hypothesis":""} +{"question_id":"d6233ab6","hypothesis":"Yes — based on your positive memories (debate team, AP economics) and current nostalgia, attending your high school reunion would likely be a good idea as an opportunity to reconnect and reminisce. If you feel uncertain, you could plan to attend briefly or set a personal goal (e.g., talk to a few people) so it feels manageable."} +{"question_id":"1da05512","hypothesis":""} +{"question_id":"fca70973","hypothesis":""} +{"question_id":"b6025781","hypothesis":""} +{"question_id":"a89d7624","hypothesis":""} +{"question_id":"b0479f84","hypothesis":""} +{"question_id":"1d4e3b97","hypothesis":""} +{"question_id":"07b6f563","hypothesis":""} +{"question_id":"1c0ddc50","hypothesis":""} +{"question_id":"0a34ad58","hypothesis":""} +{"question_id":"7161e7e2","hypothesis":"Admon was assigned to the 8 am - 4 pm (Day Shift) on Sunday."} +{"question_id":"c4f10528","hypothesis":"Miss Bee Providore"} +{"question_id":"89527b6b","hypothesis":"blue"} +{"question_id":"e9327a54","hypothesis":"The Sugar Factory — a sweet shop at Icon Park known for its giant milkshakes."} +{"question_id":"4c36ccef","hypothesis":"Roscioli"} +{"question_id":"6ae235be","hypothesis":"The Lake Charles Refinery uses atmospheric distillation, fluid catalytic cracking (FCC), alkylation, and hydrotreating."} +{"question_id":"7e00a6cb","hypothesis":"International Budget Hostel"} +{"question_id":"1903aded","hypothesis":"Transcriptionist"} +{"question_id":"ceb54acb","hypothesis":"Sexual fixations; Problematic sexual behaviors; Sexual impulsivity; Compulsive sexuality"} +{"question_id":"f523d9fe","hypothesis":"Doc Martin"} +{"question_id":"0e5e2d1a","hypothesis":"38 subjects"} +{"question_id":"fea54f57","hypothesis":"The song was \"Evolution.\""} +{"question_id":"cc539528","hypothesis":"Ruby, Python, and PHP."} +{"question_id":"dc439ea3","hypothesis":"Hoop Dance"} +{"question_id":"18dcd5a5","hypothesis":"The party will face 4 mummies in the temple."} +{"question_id":"488d3006","hypothesis":"GR-90"} +{"question_id":"58470ed2","hypothesis":"Borges wrote: \"The Library is a sphere whose exact center is any one of its hexagons and whose circumference is inaccessible.\""} +{"question_id":"8cf51dda","hypothesis":"1. To identify molecular subtypes of endometrial cancer using a combination of genomic and transcriptomic approaches.\n2. To investigate the clinical and biological significance of the identified molecular subtypes, including their association with patient outcomes and response to therapy.\n3. To develop biomarkers for the early detection and prognosis of endometrial cancer based on the identified molecular subtypes."} +{"question_id":"1d4da289","hypothesis":"The assistant referred to biometric authentication (e.g., fingerprint or facial recognition) and one-time passwords (OTP) as two-factor authentication methods."} +{"question_id":"8464fc84","hypothesis":"Roscioli"} +{"question_id":"8aef76bc","hypothesis":"Mod Podge (or another sealant) to make the vase water-resistant."} +{"question_id":"71a3fd6b","hypothesis":"+49 (0) 62 32 / 14 23 - 0"} +{"question_id":"2bf43736","hypothesis":"Chapter 4 of Book 1 of the second part (titled \"Vocal Prayer and Meditation\")."} +{"question_id":"70b3e69b","hypothesis":"Manolo García"} +{"question_id":"8752c811","hypothesis":"Sound effects (e.g., ambient, diegetic, non-diegetic, etc.)"} +{"question_id":"3249768e","hypothesis":"Absinthe"} +{"question_id":"1b9b7252","hypothesis":"Mindful.org"} +{"question_id":"1568498a","hypothesis":""} +{"question_id":"6222b6eb","hypothesis":"6S (the 6S radiative transfer model) is implemented in the SIAC_GEE tool."} +{"question_id":"e8a79c70","hypothesis":"2-3 eggs"} +{"question_id":"d596882b","hypothesis":"By Chloe"} +{"question_id":"e3fc4d6e","hypothesis":"Dr. Arati Prabhakar"} +{"question_id":"51b23612","hypothesis":"The Soviet cartoon mentioned was \"Nu, pogodi!\", which the assistant said mocked Western culture and portrayed the Soviet Union as superior."} +{"question_id":"3e321797","hypothesis":"Leave it on for about 10 minutes, then wash it off with cold water."} +{"question_id":"e982271f","hypothesis":"Revolution Hall"} +{"question_id":"352ab8bd","hypothesis":"Approximately 20% average improvement in framerate when using the HAMT agent."} +{"question_id":"fca762bc","hypothesis":"Memrise"} +{"question_id":"7a8d0b71","hypothesis":"$2,000"} +{"question_id":"a40e080f","hypothesis":"Patagonia and Southwest Airlines"} +{"question_id":"8b9d4367","hypothesis":"Jaipur Rugs"} +{"question_id":"5809eb10","hypothesis":"2014"} +{"question_id":"41275add","hypothesis":"How to Sit Properly at a Desk to Avoid Back Pain — Mayo Clinic: https://www.youtube.com/watch?v=UfOvNlX9Hh0"} +{"question_id":"4388e9dd","hypothesis":"He was wearing an untidy, stained white shirt."} +{"question_id":"4baee567","hypothesis":"12"} +{"question_id":"561fabcd","hypothesis":"Fissionator"} +{"question_id":"b759caee","hypothesis":"@jessica_poole_jewellery"} +{"question_id":"ac031881","hypothesis":"LIV"} +{"question_id":"28bcfaac","hypothesis":"MusicTheory.net"} +{"question_id":"16c90bf4","hypothesis":"I recommended a light or medium-bodied beer — specifically a Pilsner or a lager (with the option of using a local beer from Ancash)."} +{"question_id":"c8f1aeed","hypothesis":"Pennsylvania"} +{"question_id":"eaca4986","hypothesis":"C D E F G A B A G F E D C"} +{"question_id":"c7cf7dfd","hypothesis":"Nostalgia"} +{"question_id":"e48988bc","hypothesis":"Patagonia."} +{"question_id":"1de5cff2","hypothesis":"Veja"} +{"question_id":"65240037","hypothesis":"Dilute tea tree oil with a carrier oil at a 1:10 ratio (one part tea tree oil to ten parts carrier oil)."} +{"question_id":"778164c6","hypothesis":""} +{"question_id":"e47becba","hypothesis":"Business Administration"} +{"question_id":"118b2229","hypothesis":"45 minutes each way."} +{"question_id":"51a45a95","hypothesis":"Not specified in the conversation history."} +{"question_id":"58bf7951","hypothesis":"The Glass Menagerie"} +{"question_id":"1e043500","hypothesis":"Summer Vibes"} +{"question_id":"c5e8278d","hypothesis":"Johnson"} +{"question_id":"6ade9755","hypothesis":"You take yoga at your local Serenity Yoga studio and at home using the Down Dog app."} +{"question_id":"6f9b354f","hypothesis":"A lighter shade of gray"} +{"question_id":"58ef2f1c","hypothesis":""} +{"question_id":"f8c5f88b","hypothesis":"A sports store downtown."} +{"question_id":"5d3d2817","hypothesis":"Marketing specialist at a small startup"} +{"question_id":"7527f7e2","hypothesis":"$800"} +{"question_id":"c960da58","hypothesis":"20"} +{"question_id":"3b6f954b","hypothesis":"University of Melbourne"} +{"question_id":"726462e0","hypothesis":"10%"} +{"question_id":"94f70d80","hypothesis":"4 hours"} +{"question_id":"66f24dbb","hypothesis":"A yellow dress and a pair of earrings that match the dress."} +{"question_id":"ad7109d1","hypothesis":"500 Mbps"} +{"question_id":"af8d2e46","hypothesis":"7 shirts"} +{"question_id":"dccbc061","hypothesis":"You used to be a staunch atheist."} +{"question_id":"c8c3f81d","hypothesis":"Nike"} +{"question_id":"8ebdbe50","hypothesis":"A Data Science certification."} +{"question_id":"6b168ec8","hypothesis":"3"} +{"question_id":"75499fd8","hypothesis":"Golden Retriever"} +{"question_id":"21436231","hypothesis":"12"} +{"question_id":"95bcc1c8","hypothesis":"10"} +{"question_id":"0862e8bf","hypothesis":"Luna"} +{"question_id":"853b0a1d","hypothesis":"18"} +{"question_id":"a06e4cfe","hypothesis":"3:1 (gin to vermouth)"} +{"question_id":"37d43f65","hypothesis":"16GB"} +{"question_id":"b86304ba","hypothesis":""} +{"question_id":"d52b4f67","hypothesis":"The Grand Ballroom"} +{"question_id":"25e5aa4f","hypothesis":"UCLA"} +{"question_id":"caf9ead2","hypothesis":"Around 5 hours."} +{"question_id":"8550ddae","hypothesis":"Lavender gin fizz"} +{"question_id":"60d45044","hypothesis":"Japanese short-grain rice"} +{"question_id":"3f1e9474","hypothesis":"Sarah"} +{"question_id":"86b68151","hypothesis":"IKEA"} +{"question_id":"577d4d32","hypothesis":"7 pm"} +{"question_id":"ec81a493","hypothesis":"500 copies worldwide"} +{"question_id":"15745da0","hypothesis":"Three months"} +{"question_id":"e01b8e2f","hypothesis":"Hawaii"} +{"question_id":"bc8a6e93","hypothesis":"Lemon blueberry cake"} +{"question_id":"ccb36322","hypothesis":"Spotify"} +{"question_id":"001be529","hypothesis":"Over a year."} +{"question_id":"b320f3f8","hypothesis":"A rare blue Snaggletooth action figure."} +{"question_id":"19b5f2b3","hypothesis":"Two weeks"} +{"question_id":"4fd1909e","hypothesis":"Xfinity Center"} +{"question_id":"545bd2b5","hypothesis":"About 2 hours per day."} +{"question_id":"8a137a7f","hypothesis":"Philips LED bulb"} +{"question_id":"76d63226","hypothesis":"55-inch"} +{"question_id":"86f00804","hypothesis":"The Seven Husbands of Evelyn Hugo"} +{"question_id":"8e9d538c","hypothesis":"17 skeins"} +{"question_id":"311778f1","hypothesis":"10 hours"} +{"question_id":"c19f7a0b","hypothesis":"Around 6:30 PM on weekdays."} +{"question_id":"4100d0a0","hypothesis":"Mixed ethnicity: Irish and Italian."} +{"question_id":"29f2956b","hypothesis":"30 minutes per day"} +{"question_id":"1faac195","hypothesis":"Emily lives in Denver."} +{"question_id":"faba32e5","hypothesis":"24 hours"} +{"question_id":"f4f1d8a4","hypothesis":"Your sister"} +{"question_id":"c14c00dd","hypothesis":"A lavender-scented shampoo purchased at Trader Joe's (no specific brand name was given)."} +{"question_id":"36580ce8","hypothesis":"Bronchitis"} +{"question_id":"3d86fd0a","hypothesis":"A coffee shop in the city."} +{"question_id":"a82c026e","hypothesis":"The last boss in the Dark Souls 3 DLC (Dark Souls 3 DLC)."} +{"question_id":"0862e8bf_abs","hypothesis":"I cannot answer — there is no information about a hamster or its name in the conversation history."} +{"question_id":"15745da0_abs","hypothesis":"I cannot determine how long you've been collecting vintage films because the conversation history contains no information about collecting vintage films."} +{"question_id":"bc8a6e93_abs","hypothesis":"Cannot be determined from the conversation — no information about an uncle's birthday or what was baked for it is provided."} +{"question_id":"19b5f2b3_abs","hypothesis":"Cannot be determined from the conversation history."} +{"question_id":"29f2956b_abs","hypothesis":"Cannot determine — the conversation history contains no information about daily violin practice."} +{"question_id":"f4f1d8a4_abs","hypothesis":"Cannot determine — the conversation does not say what, if anything, your dad gave you as a birthday gift."} +{"question_id":"gpt4_59149c77","hypothesis":"7 days"} +{"question_id":"gpt4_f49edff3","hypothesis":"First: helped friend prepare the nursery (2023-02-06); Second: helped cousin pick out stuff for her baby shower (2023-02-10); Third: ordered a customized phone case for a friend's birthday (2023-02-20)."} +{"question_id":"71017276","hypothesis":"About 4 weeks ago (approximately 29 days, ≈4.1 weeks)."} +{"question_id":"b46e15ed","hypothesis":""} +{"question_id":"gpt4_fa19884c","hypothesis":"7 days"} +{"question_id":"0bc8ad92","hypothesis":"About 5 months (5 months and 3 days, from 2022-10-22 to 2023-03-25)."} +{"question_id":"af082822","hypothesis":"2 weeks ago"} +{"question_id":"gpt4_4929293a","hypothesis":"Michael's engagement party happened before your cousin's wedding."} +{"question_id":"gpt4_b5700ca9","hypothesis":"3 days ago"} +{"question_id":"9a707b81","hypothesis":"21 days"} +{"question_id":"gpt4_1d4ab0c9","hypothesis":"24 days"} +{"question_id":"gpt4_e072b769","hypothesis":"About 3 weeks ago (approximately 2.9 weeks)."} +{"question_id":"0db4c65d","hypothesis":"18 days"} +{"question_id":"gpt4_1d80365e","hypothesis":""} +{"question_id":"gpt4_7f6b06db","hypothesis":""} +{"question_id":"gpt4_6dc9b45b","hypothesis":"4 months ago"} +{"question_id":"gpt4_8279ba02","hypothesis":"11 days ago"} +{"question_id":"gpt4_18c2b244","hypothesis":""} +{"question_id":"gpt4_a1b77f9c","hypothesis":"I cannot determine the total number of weeks because the conversation history does not state how long you spent on each book."} +{"question_id":"gpt4_1916e0ea","hypothesis":""} +{"question_id":"gpt4_7a0daae1","hypothesis":"1 week"} +{"question_id":"gpt4_468eb063","hypothesis":"9 days ago"} +{"question_id":"gpt4_7abb270c","hypothesis":""} +{"question_id":"gpt4_1e4a8aeb","hypothesis":"Cannot be determined from the conversation history: the exact date of the gardening workshop attendance is not stated."} +{"question_id":"gpt4_4fc4f797","hypothesis":""} +{"question_id":"4dfccbf7","hypothesis":"0 days"} +{"question_id":"gpt4_61e13b3c","hypothesis":""} +{"question_id":"gpt4_45189cb4","hypothesis":""} +{"question_id":"2ebe6c90","hypothesis":"21 days"} +{"question_id":"gpt4_e061b84f","hypothesis":""} +{"question_id":"370a8ff4","hypothesis":"11 weeks and 4 days (about 11.6 weeks)"} +{"question_id":"gpt4_d6585ce8","hypothesis":"I cannot determine an order because the conversation only mentions one attended event (a music festival in Brooklyn). No other past concerts/events or dates are provided."} +{"question_id":"gpt4_4ef30696","hypothesis":"1 day"} +{"question_id":"gpt4_ec93e27f","hypothesis":"train"} +{"question_id":"6e984301","hypothesis":""} +{"question_id":"8077ef71","hypothesis":"26 days ago"} +{"question_id":"gpt4_f420262c","hypothesis":""} +{"question_id":"gpt4_8e165409","hypothesis":"14 days"} +{"question_id":"gpt4_74aed68e","hypothesis":"29 days"} +{"question_id":"bcbe585f","hypothesis":"About 4.3 weeks ago (approximately 4 weeks and 2 days)."} +{"question_id":"gpt4_21adecb5","hypothesis":""} +{"question_id":"5e1b23de","hypothesis":"About 3 months ago (the workshop date was 2023-11-01)."} +{"question_id":"gpt4_98f46fc6","hypothesis":"The charity bake sale occurred first (on 2023-03-15), and the charity gala occurred later (around 2023-03-28)."} +{"question_id":"gpt4_af6db32f","hypothesis":"17 days ago"} +{"question_id":"eac54adc","hypothesis":"18 days"} +{"question_id":"gpt4_7ddcf75f","hypothesis":"2 days ago"} +{"question_id":"gpt4_a2d1d1f6","hypothesis":"3 days ago"} +{"question_id":"gpt4_85da3956","hypothesis":"Three weeks ago."} +{"question_id":"gpt4_b0863698","hypothesis":"7 days ago"} +{"question_id":"gpt4_68e94287","hypothesis":"The post about the vegan chili recipe happened first."} +{"question_id":"gpt4_e414231e","hypothesis":"4 days"} +{"question_id":"gpt4_7ca326fa","hypothesis":""} +{"question_id":"gpt4_7bc6cf22","hypothesis":"12 days ago"} +{"question_id":"2ebe6c92","hypothesis":""} +{"question_id":"gpt4_e061b84g","hypothesis":"The company's annual charity soccer tournament."} +{"question_id":"71017277","hypothesis":"Cannot be determined from the conversation history."} +{"question_id":"b46e15ee","hypothesis":"Walk for Hunger"} +{"question_id":"gpt4_d6585ce9","hypothesis":"I cannot determine who you went with last Saturday from the conversation history."} +{"question_id":"gpt4_1e4a8aec","hypothesis":""} +{"question_id":"gpt4_f420262d","hypothesis":"JetBlue"} +{"question_id":"gpt4_59149c78","hypothesis":""} +{"question_id":"gpt4_e414231f","hypothesis":""} +{"question_id":"gpt4_4929293b","hypothesis":"Cannot determine — the conversation states you were a bridesmaid at your cousin's wedding, but it does not say this (or any other mentioned event) occurred a week ago."} +{"question_id":"gpt4_468eb064","hypothesis":"Emma"} +{"question_id":"gpt4_fa19884d","hypothesis":"Unknown (the conversation says the user discovered a 'bluegrass band that features a banjo player' on 2023-03-31 but does not give the band's or artist's name)."} +{"question_id":"9a707b82","hypothesis":"You baked a chocolate cake for your friend's birthday party."} +{"question_id":"eac54add","hypothesis":"You mentioned that you landed your first client."} +{"question_id":"4dfccbf8","hypothesis":"You started taking ukulele lessons with your friend Rachel."} +{"question_id":"0bc8ad93","hypothesis":"Yes — you mentioned visiting the museum with a friend (a chemistry professor)."} +{"question_id":"6e984302","hypothesis":"You bought a set of sculpting tools: a modeling tool set, a wire cutter, and a sculpting mat."} +{"question_id":"gpt4_8279ba03","hypothesis":"Smoker"} +{"question_id":"gpt4_b5700ca0","hypothesis":"Episcopal Church"} +{"question_id":"gpt4_68e94288","hypothesis":"You participated in the social media #PlankChallenge."} +{"question_id":"d3ab962e","hypothesis":"8 miles"} +{"question_id":"2311e44b","hypothesis":"190 pages left"} +{"question_id":"cc06de0d","hypothesis":"The taxi ride was $6 more expensive than the train fare."} +{"question_id":"a11281a2","hypothesis":""} +{"question_id":"4f54b7c9","hypothesis":"2"} +{"question_id":"85fa3a3f","hypothesis":"$50"} +{"question_id":"9aaed6a3","hypothesis":"$0.75"} +{"question_id":"1f2b8d4f","hypothesis":"$750"} +{"question_id":"e6041065","hypothesis":"Cannot determine — the total number of shoes you packed on your last trip is not specified. If you tell me how many shoes you packed, I can calculate the percentage (percentage = 2 / total_packed * 100%)."} +{"question_id":"51c32626","hypothesis":"Cannot determine from the conversation history; no submission date is given."} +{"question_id":"d905b33f","hypothesis":"20%"} +{"question_id":"7405e8b1","hypothesis":""} +{"question_id":"f35224e0","hypothesis":"Approximately 27 episodes total (12 of 'My Favorite Murder' + around 15 of 'How I Built This')."} +{"question_id":"6456829e","hypothesis":"Tomatoes: 5 plants initially. Cucumbers: 3 plants."} +{"question_id":"a4996e51","hypothesis":""} +{"question_id":"3c1045c8","hypothesis":"You are 2.5 years older than the average employee in your department (about 2 years and 6 months)."} +{"question_id":"60036106","hypothesis":"12,000 people"} +{"question_id":"681a1674","hypothesis":"1"} +{"question_id":"e25c3b8d","hypothesis":"Cannot determine the amount saved. The conversation only states the purchase price ($200) and does not provide the original/retail price needed to calculate savings."} +{"question_id":"4adc0475","hypothesis":"5 (3 goals + 2 assists)"} +{"question_id":"4bc144e2","hypothesis":"$65"} +{"question_id":"ef66a6e5","hypothesis":"2"} +{"question_id":"5025383b","hypothesis":"Cooking and photography"} +{"question_id":"a1cc6108","hypothesis":"You were 11 years old when Alex was born."} +{"question_id":"9ee3ecd6","hypothesis":"You need 100 more points (300 points total) to redeem the free skincare product."} +{"question_id":"3fdac837","hypothesis":"12 days"} +{"question_id":"91b15a6e","hypothesis":"At least $5,150"} +{"question_id":"27016adc","hypothesis":"10%"} +{"question_id":"720133ac","hypothesis":"$75"} +{"question_id":"77eafa52","hypothesis":"$300"} +{"question_id":"8979f9ec","hypothesis":"8 lunches"} +{"question_id":"0100672e","hypothesis":"$12 per coffee mug"} +{"question_id":"a96c20ee","hypothesis":"Cannot be determined from the conversation history."} +{"question_id":"92a0aa75","hypothesis":"Cannot determine from the conversation history. The user said it took 2 years and 4 months to work up to the Senior Marketing Specialist role, but did not state how long they have held that role."} +{"question_id":"3fe836c9","hypothesis":"$25,000"} +{"question_id":"1c549ce4","hypothesis":"$140"} +{"question_id":"6c49646a","hypothesis":"3,000 miles"} +{"question_id":"1192316e","hypothesis":"90 minutes (1 hour 30 minutes)"} +{"question_id":"0ea62687","hypothesis":"2 miles per gallon"} +{"question_id":"67e0d0f2","hypothesis":"12"} +{"question_id":"bb7c3b45","hypothesis":"$300"} +{"question_id":"ba358f49","hypothesis":"I cannot determine your age when Rachel gets married because your current age or birthdate was not provided in the conversation."} +{"question_id":"61f8c8f8","hypothesis":"Cannot determine — the conversation only states last year's 5K time (45 minutes) and does not provide your current 5K finishing time."} +{"question_id":"60159905","hypothesis":""} +{"question_id":"ef9cf60a","hypothesis":"$300"} +{"question_id":"73d42213","hypothesis":"9:00 AM"} +{"question_id":"bc149d6b","hypothesis":"50 pounds"} +{"question_id":"099778bb","hypothesis":"20%"} +{"question_id":"09ba9854","hypothesis":""} +{"question_id":"d6062bb9","hypothesis":"1,998 views total (1,456 on TikTok + 542 on YouTube)."} +{"question_id":"157a136e","hypothesis":""} +{"question_id":"c18a7dc8","hypothesis":"7 years"} +{"question_id":"a3332713","hypothesis":"$200"} +{"question_id":"55241a1f","hypothesis":"Cannot determine total. Facebook Live = 12 comments; the number of comments on your most popular YouTube video is not specified in the conversation, so a total cannot be calculated."} +{"question_id":"a08a253f","hypothesis":"4 days per week"} +{"question_id":"f0e564bc","hypothesis":"$1,300"} +{"question_id":"078150f1","hypothesis":"$50"} +{"question_id":"8cf4d046","hypothesis":"The average GPA across your undergraduate and graduate studies is 3.83 out of 4.0."} +{"question_id":"a346bb18","hypothesis":"12 minutes"} +{"question_id":"37f165cf","hypothesis":"Cannot determine from the conversation: no novels are explicitly stated as having been finished in January or March."} +{"question_id":"8e91e7d9","hypothesis":"4"} +{"question_id":"87f22b4a","hypothesis":"$120"} +{"question_id":"e56a43b9","hypothesis":"$5 discount"} +{"question_id":"efc3f7c2","hypothesis":"You wake up 30 minutes earlier on Fridays."} +{"question_id":"21d02d0d","hypothesis":""} +{"question_id":"2311e44b_abs","hypothesis":"I cannot determine how many pages you have left in 'Sapiens' from the conversation history. Please tell me the book's total page count and your current page (or how many pages you've already read), and I will calculate the pages remaining."} +{"question_id":"6456829e_abs","hypothesis":"Tomatoes: 5. Chili peppers: unknown (not stated in the conversation)."} +{"question_id":"e5ba910e_abs","hypothesis":"Cannot determine total cost — the headphones cost $378, but no iPad purchase or price is provided in the conversation."} +{"question_id":"a96c20ee_abs","hypothesis":""} +{"question_id":"ba358f49_abs","hypothesis":"I cannot determine Rachel's age when you get married because the conversation does not include Rachel's current age or the date/year of your wedding."} +{"question_id":"09ba9854_abs","hypothesis":""} \ No newline at end of file diff --git a/packages/benchmark/src/cli/commands/evaluate.ts b/packages/benchmark/src/cli/commands/evaluate.ts new file mode 100644 index 0000000000000000000000000000000000000000..53a09695b7be5874eada13d443d80cafc33864e5 --- /dev/null +++ b/packages/benchmark/src/cli/commands/evaluate.ts @@ -0,0 +1,78 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { Evaluator, formatMetricsReport, parseJsonlResults } from "../../longmemeval/evaluator.js"; +import { loadDataset } from "../../longmemeval/loader.js"; + +interface EvaluateOptions { + hypothesis: string; + groundTruth: string; + output?: string; + llmEval: boolean; +} + +export async function evaluateCommand(options: EvaluateOptions): Promise { + console.log("📊 Evaluating benchmark results"); + console.log(""); + console.log(` Hypothesis file: ${options.hypothesis}`); + console.log(` Ground truth: ${options.groundTruth}`); + console.log(` LLM evaluation: ${options.llmEval}`); + console.log(""); + + try { + // Load hypothesis results + console.log("Loading hypothesis file..."); + const hypothesisContent = await readFile(options.hypothesis, "utf-8"); + const results = parseJsonlResults(hypothesisContent); + console.log(` Loaded ${results.length} results`); + + // Load ground truth + console.log("Loading ground truth dataset..."); + const { instances } = await loadDataset({ datasetPath: options.groundTruth }); + console.log(` Loaded ${instances.length} instances`); + + // Evaluate + console.log("Evaluating..."); + + // TODO: Add LLM provider for LLM-based evaluation + if (options.llmEval) { + console.warn("⚠️ LLM evaluation requested but no LLM provider configured"); + console.warn(" Falling back to string matching"); + } + + const evaluator = new Evaluator({ useLLMEvaluation: false }); + const { evaluated, metrics } = await evaluator.evaluateAll(results, instances); + + // Print report + console.log(""); + console.log("=".repeat(60)); + console.log(formatMetricsReport(metrics)); + console.log("=".repeat(60)); + + // Save metrics if output path specified + if (options.output) { + const outputData = { + metrics, + evaluated: evaluated.map((e) => ({ + questionId: e.questionId, + questionType: e.questionType, + memoryAbility: e.memoryAbility, + correct: e.correct, + })), + }; + await writeFile(options.output, JSON.stringify(outputData, null, 2), "utf-8"); + console.log(`\n✅ Metrics saved to: ${options.output}`); + } + + // Exit with appropriate code + const accuracy = metrics.overall.accuracy; + if (accuracy >= 0.7) { + console.log("\n✅ Benchmark passed (accuracy >= 70%)"); + } else if (accuracy >= 0.5) { + console.log("\n⚠️ Benchmark marginal (50% <= accuracy < 70%)"); + } else { + console.log("\n❌ Benchmark needs improvement (accuracy < 50%)"); + } + } catch (error) { + console.error("\n❌ Evaluation failed:", error); + process.exit(1); + } +} diff --git a/packages/benchmark/src/cli/commands/ingest.ts b/packages/benchmark/src/cli/commands/ingest.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9f378ce27912d993cdf3a750695b47b9acaa1f9 --- /dev/null +++ b/packages/benchmark/src/cli/commands/ingest.ts @@ -0,0 +1,177 @@ +/** + * Ingest command - loads LongMemEval dataset into FalkorDB + */ + +import { readFile } from "node:fs/promises"; +import { LongMemEvalDatasetSchema } from "../../longmemeval/types.js"; + +interface IngestOptions { + dataset: string; + falkorUrl: string; + qdrantUrl: string; + embeddingModel: string; + clear: boolean; + verbose: boolean; +} + +export async function ingestCommand(options: IngestOptions): Promise { + const { dataset, falkorUrl, verbose } = options; + + console.log("=== Engram Benchmark Data Ingestion ==="); + console.log(`Dataset: ${dataset}`); + console.log(`FalkorDB: ${falkorUrl}`); + console.log(""); + + // Load and parse dataset + console.log("Loading dataset..."); + const raw = await readFile(dataset, "utf-8"); + const data = LongMemEvalDatasetSchema.parse(JSON.parse(raw)); + console.log(`Loaded ${data.length} instances\n`); + + // Dynamic import of falkordb + const { FalkorDB } = await import("falkordb"); + + // Connect to FalkorDB + console.log("Connecting to FalkorDB..."); + const url = new URL(falkorUrl); + const db = await FalkorDB.connect({ + socket: { host: url.hostname, port: Number.parseInt(url.port) || 6379 }, + }); + const graph = db.selectGraph("engram_benchmark"); + + // Create indexes (FalkorDB syntax) + console.log("Creating indexes..."); + try { + await graph.query("CREATE INDEX FOR (s:Session) ON (s.id)"); + } catch { + /* exists */ + } + try { + await graph.query("CREATE INDEX FOR (t:Turn) ON (t.id)"); + } catch { + /* exists */ + } + try { + await graph.query("CREATE INDEX FOR (m:Memory) ON (m.id)"); + } catch { + /* exists */ + } + + // Track unique sessions + const processedSessions = new Set(); + let sessionsCreated = 0; + let turnsCreated = 0; + let memoriesCreated = 0; + + const now = new Date().toISOString(); + + // Process each instance + console.log("Processing instances..."); + for (const instance of data) { + for (let i = 0; i < instance.haystack_sessions.length; i++) { + const sessionId = instance.haystack_session_ids[i]; + const sessionDate = instance.haystack_dates[i]; + const session = instance.haystack_sessions[i]; + + if (processedSessions.has(sessionId)) continue; + processedSessions.add(sessionId); + + // Create Session node using parameterized query + const sessionEpoch = new Date(sessionDate).getTime(); + await graph.query( + `MERGE (s:Session {id: $id}) ON CREATE SET s.vt_start = $vtStart, s.vt_end = $vtEnd, s.tt_start = $ttStart, s.tt_end = $ttEnd, s.started_at = $startedAt, s.user_id = $userId, s.agent_type = $agentType`, + { + params: { + id: sessionId, + vtStart: sessionDate, + vtEnd: "9999-12-31T23:59:59.999Z", + ttStart: now, + ttEnd: "9999-12-31T23:59:59.999Z", + startedAt: sessionEpoch, + userId: "longmemeval", + agentType: "unknown", + }, + }, + ); + sessionsCreated++; + + // Process turns (pairs of user + assistant messages) + for (let turnIdx = 0; turnIdx < session.length - 1; turnIdx += 2) { + const userTurn = session[turnIdx]; + const assistantTurn = session[turnIdx + 1]; + + if (!userTurn || userTurn.role !== "user") continue; + + const userContent = userTurn.content.slice(0, 500); + const assistantContent = (assistantTurn?.content ?? "").slice(0, 500); + const turnId = `turn_${sessionId}_${turnIdx}`; + + // Create Turn node using parameterized query + await graph.query( + `MERGE (t:Turn {id: $id}) ON CREATE SET t.vt_start = $vtStart, t.vt_end = $vtEnd, t.tt_start = $ttStart, t.tt_end = $ttEnd, t.user_content = $userContent, t.assistant_preview = $assistantPreview, t.sequence_index = $seqIdx`, + { + params: { + id: turnId, + vtStart: sessionDate, + vtEnd: "9999-12-31T23:59:59.999Z", + ttStart: now, + ttEnd: "9999-12-31T23:59:59.999Z", + userContent, + assistantPreview: assistantContent, + seqIdx: Math.floor(turnIdx / 2), + }, + }, + ); + + // Link Turn to Session + await graph.query( + `MATCH (s:Session {id: $sid}), (t:Turn {id: $tid}) MERGE (s)-[:HAS_TURN]->(t)`, + { + params: { sid: sessionId, tid: turnId }, + }, + ); + turnsCreated++; + + // Create Memory node + const memoryContent = `User: ${userTurn.content.slice(0, 200)} Assistant: ${(assistantTurn?.content ?? "").slice(0, 200)}`; + const memoryId = `mem_${sessionId}_${turnIdx}`; + + await graph.query( + `MERGE (m:Memory {id: $id}) ON CREATE SET m.vt_start = $vtStart, m.vt_end = $vtEnd, m.tt_start = $ttStart, m.tt_end = $ttEnd, m.content = $content, m.type = $type, m.source_session_id = $srcSession, m.source_turn_id = $srcTurn, m.source = $source`, + { + params: { + id: memoryId, + vtStart: sessionDate, + vtEnd: "9999-12-31T23:59:59.999Z", + ttStart: now, + ttEnd: "9999-12-31T23:59:59.999Z", + content: memoryContent, + type: "turn", + srcSession: sessionId, + srcTurn: turnId, + source: "import", + }, + }, + ); + + // Link Memory to Turn + await graph.query( + `MATCH (t:Turn {id: $tid}), (m:Memory {id: $mid}) MERGE (t)-[:PRODUCES]->(m)`, + { + params: { tid: turnId, mid: memoryId }, + }, + ); + memoriesCreated++; + } + + if (verbose && sessionsCreated % 50 === 0) { + console.log(` Processed ${sessionsCreated} sessions...`); + } + } + } + + console.log("\n=== Ingestion Complete ==="); + console.log(`Sessions: ${sessionsCreated}`); + console.log(`Turns: ${turnsCreated}`); + console.log(`Memories: ${memoriesCreated}`); +} diff --git a/packages/benchmark/src/cli/commands/run.ts b/packages/benchmark/src/cli/commands/run.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc6064069028e6c1027c45ed11ef8b1ab1771608 --- /dev/null +++ b/packages/benchmark/src/cli/commands/run.ts @@ -0,0 +1,367 @@ +import { writeFile } from "node:fs/promises"; +import { + BenchmarkPipeline, + type CustomRetriever, + type PipelineProgress, + type RetrievalDebugInfo, +} from "../../longmemeval/pipeline.js"; +import { + AnthropicProvider, + GeminiProvider, + OllamaProvider, + OpenAICompatibleProvider, +} from "../../longmemeval/providers/anthropic-provider.js"; +import { EngramRetriever } from "../../longmemeval/providers/engram-provider.js"; +import { QdrantEmbeddingProvider } from "../../longmemeval/providers/qdrant-provider.js"; +import type { LLMProvider } from "../../longmemeval/reader.js"; +import { StubEmbeddingProvider, StubLLMProvider } from "../../longmemeval/reader.js"; +import type { EmbeddingProvider } from "../../longmemeval/retriever.js"; +import type { DatasetVariant } from "../../longmemeval/types.js"; + +interface RunOptions { + dataset: string; + variant: string; + output?: string; + limit?: number; + topK: number; + retriever: string; + chainOfNote: boolean; + timeAware: boolean; + verbose: boolean; + // Provider options + embeddings: string; + llm: string; + qdrantUrl?: string; + ollamaUrl?: string; + ollamaModel?: string; + // Gemini options + geminiModel?: string; + // Milestone 2 optimizations + keyExpansion: boolean; + temporalAnalysis: boolean; + // Engram full pipeline options + rerank: boolean; + rerankTier: string; + rerankDepth: number; + hybridSearch: boolean; + // Learned fusion options + learnedFusion: boolean; + fusionModel: string; + // Multi-query retrieval options + multiQuery: boolean; + multiQueryVariations: number; + // Abstention detection options + abstention: boolean; + abstentionThreshold: number; + abstentionHedging: boolean; + abstentionNli: boolean; + abstentionNliThreshold: number; + // Session-aware retrieval options + sessionAware: boolean; + topSessions: number; + turnsPerSession: number; + // Temporal query parsing options + temporalAware: boolean; + temporalConfidenceThreshold: number; + // Embedding model options + embeddingModel: string; + // Debug options + debugRetrieval: boolean; +} + +export async function runCommand(benchmark: string, options: RunOptions): Promise { + if (benchmark !== "longmemeval") { + console.error(`Unknown benchmark: ${benchmark}`); + console.error("Available benchmarks: longmemeval"); + process.exit(1); + } + + console.log("🚀 Starting LongMemEval benchmark"); + console.log(""); + console.log("Configuration:"); + console.log(` Dataset: ${options.dataset}`); + console.log(` Variant: ${options.variant}`); + console.log(` Top-K: ${options.topK}`); + console.log(` Retriever: ${options.retriever}`); + console.log(` Chain-of-Note: ${options.chainOfNote}`); + console.log(` Time-Aware: ${options.timeAware}`); + console.log(` Embeddings: ${options.embeddings}`); + console.log(` LLM: ${options.llm}`); + console.log(` Key Expansion: ${options.keyExpansion}`); + console.log(` Temporal Analysis: ${options.temporalAnalysis}`); + if (options.embeddings === "engram") { + console.log(` Hybrid Search: ${options.hybridSearch}`); + console.log(` Learned Fusion: ${options.learnedFusion}`); + if (options.learnedFusion) { + console.log(` Fusion Model: ${options.fusionModel}`); + } + console.log(` Rerank: ${options.rerank}`); + if (options.rerank) { + console.log(` Rerank Tier: ${options.rerankTier}`); + console.log(` Rerank Depth: ${options.rerankDepth}`); + } + console.log(` Multi-Query: ${options.multiQuery}`); + if (options.multiQuery) { + console.log(` Multi-Query Variations: ${options.multiQueryVariations}`); + } + console.log(` Abstention Detection: ${options.abstention}`); + if (options.abstention) { + console.log(` Abstention Threshold: ${options.abstentionThreshold}`); + console.log(` Abstention Hedging (Layer 3): ${options.abstentionHedging}`); + console.log(` Abstention NLI (Layer 2): ${options.abstentionNli}`); + if (options.abstentionNli) { + console.log(` Abstention NLI Threshold: ${options.abstentionNliThreshold}`); + } + } + console.log(` Session-Aware Retrieval: ${options.sessionAware}`); + if (options.sessionAware) { + console.log(` Top Sessions (Stage 1): ${options.topSessions}`); + console.log(` Turns Per Session (Stage 2): ${options.turnsPerSession}`); + } + console.log(` Temporal Query Parsing: ${options.temporalAware}`); + if (options.temporalAware) { + console.log(` Temporal Confidence Threshold: ${options.temporalConfidenceThreshold}`); + } + console.log(` Embedding Model: ${options.embeddingModel}`); + } + if (options.limit) { + console.log(` Limit: ${options.limit} instances`); + } + console.log(""); + + // Initialize providers + const embeddings = createEmbeddingProvider(options); + const llm = createLLMProvider(options); + const customRetriever = createCustomRetriever(options); + + const pipeline = new BenchmarkPipeline(embeddings, llm, { + loader: { + datasetPath: options.dataset, + variant: options.variant as DatasetVariant, + limit: options.limit, + }, + retriever: { + method: options.retriever as "dense" | "bm25" | "hybrid", + topK: options.topK, + timeAwareExpansion: options.timeAware, + }, + reader: { + chainOfNote: options.chainOfNote, + // Enable abstention detection in Reader if --abstention-hedging or --abstention-nli + abstentionDetection: + options.abstention && (options.abstentionHedging || options.abstentionNli), + abstentionNLI: options.abstentionNli, + abstentionNLIThreshold: options.abstentionNliThreshold, + }, + // Milestone 2 optimizations + keyExpansion: { + enabled: options.keyExpansion, + types: ["keyphrase", "userfact"], + }, + temporal: { + enabled: options.temporalAnalysis, + }, + // Custom retriever for Engram full pipeline + customRetriever, + onProgress: (progress: PipelineProgress) => { + if (options.verbose) { + console.log( + `[${progress.stage}] ${progress.current}/${progress.total} - ${progress.message}`, + ); + } else { + // Simple progress bar + const pct = Math.round((progress.current / progress.total) * 100); + process.stdout.write(`\r${progress.stage}: ${pct}%`); + } + }, + // Debug retrieval callback + onRetrievalDebug: options.debugRetrieval ? logRetrievalDebug : undefined, + }); + + try { + const result = await pipeline.run(); + + console.log("\n"); + console.log("=".repeat(60)); + console.log(result.report); + console.log("=".repeat(60)); + + // Save results if output path specified + if (options.output) { + await writeFile(options.output, result.jsonl, "utf-8"); + console.log(`\n✅ Results saved to: ${options.output}`); + } + + // Save detailed report + const reportPath = options.output + ? options.output.replace(".jsonl", "-report.md") + : "longmemeval-report.md"; + await writeFile(reportPath, result.report, "utf-8"); + console.log(`📊 Report saved to: ${reportPath}`); + + // ONNX runtime has threading issues that cause ugly errors at exit + // Suppress stderr briefly and force exit + const originalStderr = process.stderr.write.bind(process.stderr); + process.stderr.write = () => true; // Suppress ONNX mutex errors + setTimeout(() => { + process.stderr.write = originalStderr; + process.exit(0); + }, 100); + } catch (error) { + console.error("\n❌ Benchmark failed:", error); + process.exit(1); + } +} + +/** + * Create embedding provider based on options + */ +function createEmbeddingProvider(options: RunOptions): EmbeddingProvider { + switch (options.embeddings) { + case "engram": + // Engram uses custom retriever, but we still need a stub for pipeline init + console.log("🚀 Using Engram full pipeline (search-core)"); + console.log(" - Dense: E5-small (384d)"); + if (options.hybridSearch) { + console.log(" - Sparse: SPLADE"); + console.log(" - Fusion: RRF"); + } + if (options.rerank) { + console.log(` - Reranker: ${options.rerankTier} tier`); + } + return new StubEmbeddingProvider(); // Pipeline uses customRetriever instead + + case "qdrant": + case "e5": + console.log("📦 Using Qdrant/E5 embeddings (HuggingFace transformers)"); + return new QdrantEmbeddingProvider({ + url: options.qdrantUrl ?? "http://localhost:6333", + }); + default: + console.log("⚠️ Using stub embeddings (random vectors)"); + return new StubEmbeddingProvider(); + } +} + +/** + * Create custom retriever for Engram full pipeline + */ +function createCustomRetriever(options: RunOptions): CustomRetriever | undefined { + if (options.embeddings !== "engram") { + return undefined; + } + + return new EngramRetriever({ + qdrantUrl: options.qdrantUrl ?? "http://localhost:6333", + hybridSearch: options.hybridSearch, + learnedFusion: options.learnedFusion, + fusionModel: options.fusionModel, + rerank: options.rerank, + rerankTier: options.rerankTier as "fast" | "accurate" | "code" | "colbert", + rerankDepth: options.rerankDepth, + topK: options.topK, + multiQuery: options.multiQuery, + multiQueryVariations: options.multiQueryVariations, + abstention: options.abstention, + abstentionThreshold: options.abstentionThreshold, + sessionAware: options.sessionAware, + topSessions: options.topSessions, + turnsPerSession: options.turnsPerSession, + temporalAware: options.temporalAware, + temporalConfidenceThreshold: options.temporalConfidenceThreshold, + embeddingModel: options.embeddingModel as + | "e5-small" + | "e5-base" + | "e5-large" + | "gte-base" + | "gte-large" + | "bge-small" + | "bge-base" + | "bge-large", + }); +} + +/** + * Create LLM provider based on options + */ +function createLLMProvider(options: RunOptions): LLMProvider { + switch (options.llm) { + case "anthropic": + case "claude": + if (!process.env.ANTHROPIC_API_KEY) { + console.error("❌ ANTHROPIC_API_KEY environment variable required for Claude"); + process.exit(1); + } + console.log("🤖 Using Anthropic Claude for answer generation"); + return new AnthropicProvider(); + + case "openai": + case "gpt": + if (!process.env.OPENAI_API_KEY) { + console.error("❌ OPENAI_API_KEY environment variable required for OpenAI"); + process.exit(1); + } + console.log("🤖 Using OpenAI GPT for answer generation"); + return new OpenAICompatibleProvider(); + + case "ollama": + if (!options.ollamaModel) { + console.error("❌ --ollama-model is required when using Ollama"); + process.exit(1); + } + console.log(`🤖 Using Ollama (${options.ollamaModel}) for answer generation`); + return new OllamaProvider({ + baseUrl: options.ollamaUrl ?? "http://localhost:11434", + model: options.ollamaModel, + }); + + case "gemini": + case "google": + if (!process.env.GOOGLE_GENERATIVE_AI_API_KEY) { + console.error("❌ GOOGLE_GENERATIVE_AI_API_KEY environment variable required for Gemini"); + process.exit(1); + } + console.log( + `🤖 Using Google Gemini (${options.geminiModel ?? "gemini-3-flash-preview"}) for answer generation`, + ); + return new GeminiProvider({ + model: options.geminiModel ?? "gemini-3-flash-preview", + }); + default: + console.log("⚠️ Using stub LLM (no real generation)"); + return new StubLLMProvider(); + } +} + +/** + * Log retrieval debug info to console + */ +function logRetrievalDebug(debug: RetrievalDebugInfo): void { + const truncate = (s: string, len: number) => (s.length > len ? `${s.slice(0, len)}...` : s); + + console.log(`\n${"─".repeat(80)}`); + console.log(`📋 RETRIEVAL DEBUG: ${debug.questionId}`); + console.log("─".repeat(80)); + + console.log(`\n❓ Question: ${debug.question}`); + console.log(`✅ Expected Answer: ${debug.expectedAnswer}`); + console.log(`📊 Recall: ${(debug.recall * 100).toFixed(1)}%`); + + console.log(`\n🎯 EXPECTED EVIDENCE (${debug.evidenceDocs.length} docs):`); + for (const doc of debug.evidenceDocs) { + const found = debug.retrievedDocs.some((r) => r.id === doc.id); + const status = found ? "✅" : "❌"; + console.log(` ${status} [${doc.sessionId}] ${truncate(doc.content, 100)}`); + } + + console.log(`\n🔍 RETRIEVED (${debug.retrievedDocs.length} docs):`); + for (let i = 0; i < debug.retrievedDocs.length; i++) { + const doc = debug.retrievedDocs[i]; + const marker = doc.isEvidence ? "🎯" : " "; + console.log( + ` ${i + 1}. ${marker} [score=${doc.score.toFixed(3)}] ${truncate(doc.content, 80)}`, + ); + } + + console.log(`${"─".repeat(80)}\n`); +} diff --git a/packages/benchmark/src/cli/commands/train-fusion.ts b/packages/benchmark/src/cli/commands/train-fusion.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6d32411899f0a26a1b2b1b4aa03e5b3b62c7f37 --- /dev/null +++ b/packages/benchmark/src/cli/commands/train-fusion.ts @@ -0,0 +1,495 @@ +import { writeFile } from "node:fs/promises"; +import { QueryFeatureExtractor } from "@engram/search"; +import { type LoaderConfig, loadDataset } from "../../longmemeval/loader.js"; +import { type EngramDocument, mapInstance } from "../../longmemeval/mapper.js"; +import { computeRetrievalMetrics, type RetrievalResult } from "../../longmemeval/retriever.js"; +import type { DatasetVariant, ParsedInstance } from "../../longmemeval/types.js"; + +/** + * Training sample for fusion weight MLP. + */ +interface FusionTrainingSample { + /** Unique identifier for this sample */ + instanceId: string; + /** The question text */ + question: string; + /** Normalized feature vector for model input */ + features: number[]; + /** Feature names for debugging */ + featureNames: string[]; + /** Optimal fusion weights found via grid search */ + optimalWeights: { + dense: number; + sparse: number; + rerank: number; + }; + /** Best recall achieved with optimal weights */ + bestRecall: number; + /** Grid search results for analysis */ + gridSearchResults: Array<{ + weights: { dense: number; sparse: number; rerank: number }; + recall: number; + }>; +} + +/** + * Configuration for training data generation. + */ +interface TrainFusionOptions { + dataset: string; + variant: string; + output: string; + limit?: number; + verbose: boolean; + qdrantUrl: string; + // Grid search parameters + denseSteps: number[]; + sparseSteps: number[]; +} + +const DEFAULT_DENSE_STEPS = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]; +const DEFAULT_SPARSE_STEPS = [0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]; + +/** + * Generate training data for fusion weight MLP via grid search. + * + * For each LongMemEval instance: + * 1. Extract query features + * 2. Run retrieval with each weight combination + * 3. Find weights that maximize recall + * 4. Save (features, optimal_weights) pairs + */ +export async function trainFusionCommand(options: TrainFusionOptions): Promise { + console.log("🔬 Generating Fusion Training Data"); + console.log(""); + console.log("Configuration:"); + console.log(` Dataset: ${options.dataset}`); + console.log(` Variant: ${options.variant}`); + console.log(` Output: ${options.output}`); + console.log(` Dense steps: ${options.denseSteps.join(", ")}`); + console.log(` Sparse steps: ${options.sparseSteps.join(", ")}`); + if (options.limit) { + console.log(` Limit: ${options.limit} instances`); + } + console.log(""); + + // Initialize components + const featureExtractor = new QueryFeatureExtractor(); + const weightedRetriever = await createWeightedRetriever(options.qdrantUrl); + + // Load dataset + console.log("📂 Loading dataset..."); + const loaderConfig: LoaderConfig = { + datasetPath: options.dataset, + variant: options.variant as DatasetVariant, + limit: options.limit, + }; + const loadResult = await loadDataset(loaderConfig); + console.log(` Loaded ${loadResult.instances.length} instances`); + + // Generate training samples + const samples: FusionTrainingSample[] = []; + const totalGridSize = options.denseSteps.length * options.sparseSteps.length; + console.log(` Grid size: ${totalGridSize} combinations per instance`); + console.log(""); + + for (let i = 0; i < loadResult.instances.length; i++) { + const instance = loadResult.instances[i]; + const progress = `[${i + 1}/${loadResult.instances.length}]`; + + if (options.verbose) { + console.log(`${progress} Processing: ${instance.question.substring(0, 50)}...`); + } else { + process.stdout.write(`\r${progress} Generating training data...`); + } + + try { + const sample = await generateTrainingSample( + instance, + featureExtractor, + weightedRetriever, + options.denseSteps, + options.sparseSteps, + ); + samples.push(sample); + + if (options.verbose) { + console.log( + ` → Best weights: d=${sample.optimalWeights.dense.toFixed(2)}, ` + + `s=${sample.optimalWeights.sparse.toFixed(2)}, ` + + `r=${sample.optimalWeights.rerank.toFixed(2)} ` + + `(recall=${sample.bestRecall.toFixed(3)})`, + ); + } + } catch (error) { + console.warn(`\n⚠️ Failed to process instance ${instance.questionId}:`, error); + } + } + + console.log("\n"); + console.log(`✅ Generated ${samples.length} training samples`); + + // Analyze weight distribution + analyzeWeightDistribution(samples); + + // Save to JSONL + const jsonlContent = samples.map((s) => JSON.stringify(s)).join("\n"); + await writeFile(options.output, jsonlContent, "utf-8"); + console.log(`\n📁 Saved training data to: ${options.output}`); + + // Cleanup + await weightedRetriever.cleanup(); +} + +/** + * Generate a training sample for a single instance. + */ +async function generateTrainingSample( + instance: ParsedInstance, + featureExtractor: QueryFeatureExtractor, + retriever: WeightedRetriever, + denseSteps: number[], + sparseSteps: number[], +): Promise { + // Map instance to documents + const mapped = mapInstance(instance); + + // Index documents + await retriever.index(mapped.documents); + + // Extract query features + const features = featureExtractor.extract(instance.question); + const normalized = featureExtractor.toNormalizedVector(features); + + // Get evidence document IDs for recall calculation + const evidenceDocIds = mapped.evidenceDocIds; + + // Grid search for optimal weights + const gridResults: Array<{ + weights: { dense: number; sparse: number; rerank: number }; + recall: number; + }> = []; + + let bestRecall = 0; + let bestWeights = { dense: 0.4, sparse: 0.3, rerank: 0.3 }; + + for (const dense of denseSteps) { + for (const sparse of sparseSteps) { + const rerank = Math.max(0, 1 - dense - sparse); + if (rerank < 0 || dense + sparse > 1) continue; + + const weights = { dense, sparse, rerank }; + + // Retrieve with weighted fusion + const result = await retriever.search(instance.question, weights, 10); + + // Calculate recall + const metrics = computeRetrievalMetrics(result, evidenceDocIds); + const recall = metrics.recall; + + gridResults.push({ weights, recall }); + + if (recall > bestRecall) { + bestRecall = recall; + bestWeights = weights; + } + } + } + + // Clear index for next instance + retriever.clear(); + + return { + instanceId: instance.questionId, + question: instance.question, + features: normalized.vector, + featureNames: normalized.names, + optimalWeights: bestWeights, + bestRecall, + gridSearchResults: gridResults, + }; +} + +/** + * Analyze and report weight distribution in training data. + */ +function analyzeWeightDistribution(samples: FusionTrainingSample[]): void { + console.log("\n📊 Weight Distribution Analysis:"); + + // Aggregate optimal weights + const denseWeights = samples.map((s) => s.optimalWeights.dense); + const sparseWeights = samples.map((s) => s.optimalWeights.sparse); + const rerankWeights = samples.map((s) => s.optimalWeights.rerank); + + const mean = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length; + const std = (arr: number[]) => { + const m = mean(arr); + return Math.sqrt(arr.reduce((sum, x) => sum + (x - m) ** 2, 0) / arr.length); + }; + + console.log( + ` Dense: mean=${mean(denseWeights).toFixed(3)}, std=${std(denseWeights).toFixed(3)}`, + ); + console.log( + ` Sparse: mean=${mean(sparseWeights).toFixed(3)}, std=${std(sparseWeights).toFixed(3)}`, + ); + console.log( + ` Rerank: mean=${mean(rerankWeights).toFixed(3)}, std=${std(rerankWeights).toFixed(3)}`, + ); + + // Show question type breakdown + console.log("\n By Question Type:"); + const byType = new Map(); + for (const sample of samples) { + // Parse question type from features (index 3 in normalized vector) + const typeValue = sample.features[3]; + let type = "other"; + if (typeValue < 0.1) type = "factoid"; + else if (typeValue < 0.2) type = "list"; + else if (typeValue < 0.4) type = "comparison"; + else if (typeValue < 0.5) type = "causal"; + else if (typeValue < 0.7) type = "temporal"; + else if (typeValue < 0.8) type = "opinion"; + + if (!byType.has(type)) byType.set(type, []); + byType.get(type)?.push(sample); + } + + for (const [type, typeSamples] of byType) { + const avgDense = mean(typeSamples.map((s) => s.optimalWeights.dense)); + const avgSparse = mean(typeSamples.map((s) => s.optimalWeights.sparse)); + const avgRerank = mean(typeSamples.map((s) => s.optimalWeights.rerank)); + console.log( + ` ${type.padEnd(12)}: d=${avgDense.toFixed(2)}, s=${avgSparse.toFixed(2)}, r=${avgRerank.toFixed(2)} (n=${typeSamples.length})`, + ); + } +} + +/** + * Weighted retriever that allows configurable fusion weights. + */ +interface WeightedRetriever { + index(documents: EngramDocument[]): Promise; + search( + query: string, + weights: { dense: number; sparse: number; rerank: number }, + topK: number, + ): Promise; + clear(): void; + cleanup(): Promise; +} + +/** + * Create a weighted retriever for grid search. + * This uses the Engram pipeline with configurable fusion weights. + */ +async function createWeightedRetriever(qdrantUrl: string): Promise { + // Dynamic import to avoid circular dependencies + const searchCore = await import("@engram/search"); + const { QdrantClient } = await import("@qdrant/js-client-rest"); + + const collectionName = "fusion_training"; + const client = new QdrantClient({ url: qdrantUrl }); + const textEmbedder = new searchCore.TextEmbedder(); + const spladeEmbedder = new searchCore.SpladeEmbedder(); + const reranker = searchCore.BatchedReranker.forTier("fast"); + + let indexed = false; + let documents: EngramDocument[] = []; + + return { + async index(docs: EngramDocument[]): Promise { + documents = docs; + + // Ensure collection exists + try { + await client.deleteCollection(collectionName); + } catch { + // Ignore if doesn't exist + } + + await client.createCollection(collectionName, { + vectors: { + dense: { size: 384, distance: "Cosine" }, + }, + sparse_vectors: { + sparse: { index: { on_disk: false } }, + }, + }); + + // Generate embeddings + const texts = docs.map((d) => d.content); + const denseEmbeddings = await Promise.all(texts.map((t) => textEmbedder.embed(t))); + const sparseEmbeddings = await Promise.all(texts.map((t) => spladeEmbedder.embed(t))); + + // Index points + const points = docs.map((doc, i) => ({ + id: hashId(doc.id), + vector: { + dense: Array.from(denseEmbeddings[i]), + sparse: sparseEmbeddings[i], + }, + payload: { + doc_id: doc.id, + content: doc.content, + valid_time: doc.validTime.toISOString(), + has_answer: doc.metadata.hasAnswer, + }, + })); + + await client.upsert(collectionName, { wait: true, points }); + indexed = true; + }, + + async search( + query: string, + weights: { dense: number; sparse: number; rerank: number }, + topK: number, + ): Promise { + if (!indexed) { + return { documents: [], scores: [], retrievedIds: [] }; + } + + // Get dense and sparse query embeddings + const denseQuery = await textEmbedder.embedQuery(query); + const sparseQuery = await spladeEmbedder.embedQuery(query); + + // Fetch candidates for each method + const fetchLimit = 30; + + // Dense search + const denseResults = await client.search(collectionName, { + vector: { name: "dense", vector: Array.from(denseQuery) }, + limit: fetchLimit, + with_payload: true, + }); + + // Sparse search using query API + const sparseResults = await client.query(collectionName, { + query: { + indices: sparseQuery.indices, + values: sparseQuery.values, + }, + using: "sparse", + limit: fetchLimit, + with_payload: true, + }); + + // Build score map for weighted fusion + const scoreMap = new Map< + string, + { + docId: string; + content: string; + denseScore: number; + sparseScore: number; + rerankScore: number; + } + >(); + + // Normalize dense scores to 0-1 range + const maxDense = Math.max(...denseResults.map((r) => r.score), 0.001); + for (const r of denseResults) { + const payload = r.payload as Record; + const docId = payload.doc_id as string; + scoreMap.set(docId, { + docId, + content: payload.content as string, + denseScore: r.score / maxDense, + sparseScore: 0, + rerankScore: 0, + }); + } + + // Add sparse scores + const sparsePoints = sparseResults.points || []; + const maxSparse = Math.max(...sparsePoints.map((r) => r.score), 0.001); + for (const r of sparsePoints) { + const payload = r.payload as Record; + const docId = payload.doc_id as string; + const existing = scoreMap.get(docId); + if (existing) { + existing.sparseScore = r.score / maxSparse; + } else { + scoreMap.set(docId, { + docId, + content: payload.content as string, + denseScore: 0, + sparseScore: r.score / maxSparse, + rerankScore: 0, + }); + } + } + + // Get rerank scores for top candidates + const candidates = Array.from(scoreMap.values()).map((s) => ({ + id: s.docId, + content: s.content, + score: s.denseScore * weights.dense + s.sparseScore * weights.sparse, + })); + + if (weights.rerank > 0 && candidates.length > 0) { + const reranked = await reranker.rerank(query, candidates, candidates.length); + const maxRerank = Math.max(...reranked.map((r: { score: number }) => r.score), 0.001); + for (const r of reranked) { + const existing = scoreMap.get(String(r.id)); + if (existing) { + existing.rerankScore = r.score / maxRerank; + } + } + } + + // Calculate final weighted scores + const results = Array.from(scoreMap.values()) + .map((s) => ({ + docId: s.docId, + content: s.content, + score: + s.denseScore * weights.dense + + s.sparseScore * weights.sparse + + s.rerankScore * weights.rerank, + })) + .sort((a, b) => b.score - a.score) + .slice(0, topK); + + // Convert to RetrievalResult + const resultDocs = results + .map((r) => documents.find((d) => d.id === r.docId)) + .filter((d): d is EngramDocument => d !== undefined); + + return { + documents: resultDocs, + scores: results.map((r) => r.score), + retrievedIds: results.map((r) => r.docId), + }; + }, + + clear(): void { + indexed = false; + documents = []; + }, + + async cleanup(): Promise { + try { + await client.deleteCollection(collectionName); + } catch { + // Ignore + } + }, + }; +} + +/** + * Generate numeric hash for Qdrant point ID. + */ +function hashId(id: string): number { + let hash = 0; + for (let i = 0; i < id.length; i++) { + hash = (hash << 5) - hash + id.charCodeAt(i); + hash = hash >>> 0; + } + return hash; +} + +export { DEFAULT_DENSE_STEPS, DEFAULT_SPARSE_STEPS }; +export type { TrainFusionOptions, FusionTrainingSample }; diff --git a/packages/benchmark/src/cli/commands/validate.ts b/packages/benchmark/src/cli/commands/validate.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c1f11a3efaa9ce4c55b731ef0f52ad6e7d1df7b --- /dev/null +++ b/packages/benchmark/src/cli/commands/validate.ts @@ -0,0 +1,28 @@ +import { validateDataset } from "../../longmemeval/loader.js"; + +export async function validateCommand(path: string): Promise { + console.log(`🔍 Validating dataset: ${path}`); + console.log(""); + + const result = await validateDataset(path); + + if (result.valid) { + console.log("✅ Dataset is valid"); + console.log(""); + console.log("Statistics:"); + console.log(` Total instances: ${result.stats?.totalInstances}`); + console.log(` Total sessions: ${result.stats?.totalSessions}`); + console.log(` Total turns: ${result.stats?.totalTurns}`); + console.log(` Abstention questions: ${result.stats?.abstentionCount}`); + console.log(""); + console.log("By Memory Ability:"); + for (const [ability, count] of Object.entries(result.stats?.byAbility ?? {})) { + console.log(` ${ability}: ${count}`); + } + } else { + console.error("❌ Dataset validation failed"); + console.error(""); + console.error(`Error: ${result.error}`); + process.exit(1); + } +} diff --git a/packages/benchmark/src/cli/index.ts b/packages/benchmark/src/cli/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..4dcb060801fef8d134c6a93974abf2461d55a608 --- /dev/null +++ b/packages/benchmark/src/cli/index.ts @@ -0,0 +1,159 @@ +#!/usr/bin/env node +import { Command } from "commander"; +import { evaluateCommand } from "./commands/evaluate.js"; +import { ingestCommand } from "./commands/ingest.js"; +import { runCommand } from "./commands/run.js"; +import { + DEFAULT_DENSE_STEPS, + DEFAULT_SPARSE_STEPS, + trainFusionCommand, +} from "./commands/train-fusion.js"; +import { validateCommand } from "./commands/validate.js"; + +const program = new Command(); + +program + .name("engram-benchmark") + .description("Benchmark Engram memory system against industry benchmarks") + .version("0.0.1"); + +// Run benchmark command +program + .command("run") + .description("Run a benchmark against Engram") + .argument("", "Benchmark to run (longmemeval)") + .requiredOption("-d, --dataset ", "Path to dataset file or directory") + .option("-v, --variant ", "Dataset variant (s, m, oracle)", "s") + .option("-o, --output ", "Output file for results (JSONL)") + .option("-l, --limit ", "Limit number of instances", Number.parseInt) + .option("-k, --top-k ", "Number of documents to retrieve", Number.parseInt, 10) + .option("--retriever ", "Retrieval method (dense, bm25, hybrid)", "dense") + .option("--chain-of-note", "Enable Chain-of-Note reading", false) + .option("--time-aware", "Enable time-aware query expansion", false) + .option("--verbose", "Show detailed progress", false) + // Provider options + .option("--embeddings ", "Embedding provider (stub, qdrant, e5, engram)", "stub") + .option("--llm ", "LLM provider (stub, anthropic, openai, ollama, gemini)", "stub") + .option("--qdrant-url ", "Qdrant server URL", "http://localhost:6333") + .option("--ollama-url ", "Ollama server URL", "http://localhost:11434") + .option("--ollama-model ", "Ollama model name") + .option("--gemini-model ", "Gemini model name", "gemini-3-flash-preview") + // Milestone 2 optimizations + .option("--key-expansion", "Enable key expansion with fact extraction (+9% recall)", false) + .option("--temporal-analysis", "Enable improved temporal query analysis (+7-11% on TR)", false) + // Engram full pipeline options (when --embeddings engram) + .option("--rerank", "Enable reranking (requires --embeddings engram)", true) + .option("--rerank-tier ", "Reranker tier: fast, accurate, code, colbert", "fast") + .option("--rerank-depth ", "Candidates to fetch before reranking", Number.parseInt, 30) + .option("--hybrid-search", "Enable hybrid search with RRF (requires --embeddings engram)", true) + // Learned fusion options + .option("--learned-fusion", "Use learned fusion weights instead of fixed RRF", false) + .option("--fusion-model ", "Path to fusion MLP ONNX model", "models/fusion_mlp.onnx") + // Multi-query retrieval options + .option("--multi-query", "Enable multi-query expansion with RRF fusion", false) + .option( + "--multi-query-variations ", + "Number of query variations to generate", + Number.parseInt, + 3, + ) + // Abstention detection options + .option("--abstention", "Enable retrieval confidence abstention detection (Layer 1)", false) + .option( + "--abstention-threshold ", + "Minimum retrieval score to proceed (0-1)", + Number.parseFloat, + 0.3, + ) + .option( + "--abstention-hedging", + "Enable hedging pattern detection (Layer 3) - requires --abstention", + false, + ) + .option( + "--abstention-nli", + "Enable NLI answer grounding check (Layer 2) - requires --abstention", + false, + ) + .option( + "--abstention-nli-threshold ", + "NLI entailment threshold for abstention (0-1)", + Number.parseFloat, + 0.7, + ) + // Session-aware retrieval options + .option("--session-aware", "Enable session-aware hierarchical retrieval", false) + .option("--top-sessions ", "Number of sessions to retrieve in stage 1", Number.parseInt, 5) + .option("--turns-per-session ", "Number of turns per session in stage 2", Number.parseInt, 3) + // Temporal query parsing options + .option("--temporal-aware", "Enable temporal query parsing with chrono-node", false) + .option( + "--temporal-confidence-threshold ", + "Minimum confidence to apply temporal filter (0-1)", + Number.parseFloat, + 0.5, + ) + // Embedding model options + .option( + "--embedding-model ", + "Embedding model: e5-small, e5-base, e5-large, gte-base, gte-large, bge-small, bge-base, bge-large", + "e5-small", + ) + // Debug options + .option("--debug-retrieval", "Log retrieved vs expected documents for each query", false) + .action(runCommand); + +// Evaluate results command +program + .command("evaluate") + .description("Evaluate benchmark results against ground truth") + .requiredOption("-h, --hypothesis ", "Path to hypothesis JSONL file") + .requiredOption("-g, --ground-truth ", "Path to ground truth dataset") + .option("-o, --output ", "Output file for metrics (JSON)") + .option("--llm-eval", "Use LLM-based evaluation (more accurate)", false) + .action(evaluateCommand); + +// Validate dataset command +program + .command("validate") + .description("Validate a benchmark dataset file") + .argument("", "Path to dataset file") + .action(validateCommand); + +// Ingest dataset into FalkorDB + Qdrant +program + .command("ingest") + .description("Ingest dataset into FalkorDB (graph) and Qdrant (vectors)") + .requiredOption("-d, --dataset ", "Path to dataset file") + .option("--falkor-url ", "FalkorDB (Redis) URL", "redis://localhost:6379") + .option("--qdrant-url ", "Qdrant server URL", "http://localhost:6333") + .option("--embedding-model ", "Embedding model: e5-small, e5-base, e5-large", "e5-large") + .option("--clear", "Clear existing data before ingesting", false) + .option("--verbose", "Show detailed progress", false) + .action(ingestCommand); + +// Train fusion weights command +program + .command("train-fusion") + .description("Generate training data for learned fusion weights via grid search") + .requiredOption("-d, --dataset ", "Path to dataset file or directory") + .requiredOption("-o, --output ", "Output file for training data (JSONL)") + .option("-v, --variant ", "Dataset variant (s, m, oracle)", "s") + .option("-l, --limit ", "Limit number of instances", Number.parseInt) + .option("--qdrant-url ", "Qdrant server URL", "http://localhost:6333") + .option("--verbose", "Show detailed progress", false) + .option( + "--dense-steps ", + "Comma-separated dense weight values to try", + (v) => v.split(",").map(Number), + DEFAULT_DENSE_STEPS, + ) + .option( + "--sparse-steps ", + "Comma-separated sparse weight values to try", + (v) => v.split(",").map(Number), + DEFAULT_SPARSE_STEPS, + ) + .action(trainFusionCommand); + +program.parse(); diff --git a/packages/benchmark/src/core/config.ts b/packages/benchmark/src/core/config.ts new file mode 100644 index 0000000000000000000000000000000000000000..579e4f95b1986d046f13875904243000c7b40919 --- /dev/null +++ b/packages/benchmark/src/core/config.ts @@ -0,0 +1,132 @@ +/** + * Configuration builder for programmatic benchmark API + * + * Provides defaults and environment variable fallbacks for benchmark configuration. + * + * @module @engram/benchmark/core + */ + +import type { RunBenchmarkConfig } from "./types.js"; + +/** + * Default benchmark configuration values + */ +export const DEFAULT_BENCHMARK_CONFIG: Omit = { + // Dataset + variant: "oracle", + limit: undefined, + + // Retrieval + topK: 10, + retriever: "hybrid", + + // Engram pipeline + embeddings: "engram", + hybridSearch: true, + learnedFusion: false, + fusionModel: "", + rerank: true, + rerankTier: "accurate", + rerankDepth: 30, + + // Multi-query + multiQuery: false, + multiQueryVariations: 3, + + // Abstention + abstention: true, + abstentionThreshold: 0.3, + + // Session-aware + sessionAware: false, + topSessions: 5, + turnsPerSession: 3, + + // Temporal + temporalAware: false, + temporalConfidenceThreshold: 0.7, + + // Model + embeddingModel: "e5-small", + llm: "stub", + + // Ollama + ollamaUrl: "http://localhost:11434", + ollamaModel: "llama3.2", + + // Infrastructure + qdrantUrl: "http://localhost:6333", +}; + +/** + * Build a complete benchmark configuration from partial options + * + * Uses defaults and environment variable fallbacks for missing values. + * + * @param options - Partial configuration options + * @returns Complete configuration with all required fields + * + * @example + * ```ts + * const config = buildBenchmarkConfig({ + * dataset: "./data/longmemeval_oracle.json", + * limit: 50, + * llm: "anthropic", + * }); + * ``` + */ +export function buildBenchmarkConfig( + options: Partial & { dataset: string }, +): RunBenchmarkConfig { + return { + // Dataset (required) + dataset: options.dataset, + variant: options.variant ?? DEFAULT_BENCHMARK_CONFIG.variant, + limit: options.limit ?? DEFAULT_BENCHMARK_CONFIG.limit, + + // Retrieval + topK: options.topK ?? DEFAULT_BENCHMARK_CONFIG.topK, + retriever: options.retriever ?? DEFAULT_BENCHMARK_CONFIG.retriever, + + // Engram pipeline + embeddings: options.embeddings ?? DEFAULT_BENCHMARK_CONFIG.embeddings, + hybridSearch: options.hybridSearch ?? DEFAULT_BENCHMARK_CONFIG.hybridSearch, + learnedFusion: options.learnedFusion ?? DEFAULT_BENCHMARK_CONFIG.learnedFusion, + fusionModel: options.fusionModel ?? DEFAULT_BENCHMARK_CONFIG.fusionModel, + rerank: options.rerank ?? DEFAULT_BENCHMARK_CONFIG.rerank, + rerankTier: options.rerankTier ?? DEFAULT_BENCHMARK_CONFIG.rerankTier, + rerankDepth: options.rerankDepth ?? DEFAULT_BENCHMARK_CONFIG.rerankDepth, + + // Multi-query + multiQuery: options.multiQuery ?? DEFAULT_BENCHMARK_CONFIG.multiQuery, + multiQueryVariations: + options.multiQueryVariations ?? DEFAULT_BENCHMARK_CONFIG.multiQueryVariations, + + // Abstention + abstention: options.abstention ?? DEFAULT_BENCHMARK_CONFIG.abstention, + abstentionThreshold: + options.abstentionThreshold ?? DEFAULT_BENCHMARK_CONFIG.abstentionThreshold, + + // Session-aware + sessionAware: options.sessionAware ?? DEFAULT_BENCHMARK_CONFIG.sessionAware, + topSessions: options.topSessions ?? DEFAULT_BENCHMARK_CONFIG.topSessions, + turnsPerSession: options.turnsPerSession ?? DEFAULT_BENCHMARK_CONFIG.turnsPerSession, + + // Temporal + temporalAware: options.temporalAware ?? DEFAULT_BENCHMARK_CONFIG.temporalAware, + temporalConfidenceThreshold: + options.temporalConfidenceThreshold ?? DEFAULT_BENCHMARK_CONFIG.temporalConfidenceThreshold, + + // Model + embeddingModel: options.embeddingModel ?? DEFAULT_BENCHMARK_CONFIG.embeddingModel, + llm: options.llm ?? DEFAULT_BENCHMARK_CONFIG.llm, + + // Ollama + ollamaUrl: options.ollamaUrl ?? process.env.OLLAMA_URL ?? DEFAULT_BENCHMARK_CONFIG.ollamaUrl, + ollamaModel: + options.ollamaModel ?? process.env.OLLAMA_MODEL ?? DEFAULT_BENCHMARK_CONFIG.ollamaModel, + + // Infrastructure + qdrantUrl: options.qdrantUrl ?? process.env.QDRANT_URL ?? DEFAULT_BENCHMARK_CONFIG.qdrantUrl, + }; +} diff --git a/packages/benchmark/src/core/index.ts b/packages/benchmark/src/core/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..23baab01f0a4740ee1786d01c4b286bcb0511001 --- /dev/null +++ b/packages/benchmark/src/core/index.ts @@ -0,0 +1,24 @@ +/** + * Core programmatic API for @engram/benchmark + * + * This module provides a function-based API for running benchmarks + * programmatically, suitable for integration with the tuner and other + * automated systems. + * + * @module @engram/benchmark/core + */ + +export { buildBenchmarkConfig, DEFAULT_BENCHMARK_CONFIG } from "./config.js"; +// Main API +export { type BenchmarkCallbacks, runBenchmark } from "./runner.js"; + +// Types +export type { + BenchmarkMetrics, + BenchmarkProgress, + BenchmarkRunResult, + EmbeddingModel, + LLMProviderType, + RerankerTier, + RunBenchmarkConfig, +} from "./types.js"; diff --git a/packages/benchmark/src/core/runner.ts b/packages/benchmark/src/core/runner.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0bc002c5805129c376095483d690ca8042f83d0 --- /dev/null +++ b/packages/benchmark/src/core/runner.ts @@ -0,0 +1,226 @@ +/** + * Programmatic benchmark runner + * + * Provides a function-based API for running benchmarks, suitable for + * integration with the tuner and other automated systems. + * + * @module @engram/benchmark/core + */ + +import { BenchmarkPipeline, type CustomRetriever } from "../longmemeval/pipeline.js"; +import { + AnthropicProvider, + OllamaProvider, + OpenAICompatibleProvider, +} from "../longmemeval/providers/anthropic-provider.js"; +import { EngramRetriever } from "../longmemeval/providers/engram-provider.js"; +import { QdrantEmbeddingProvider } from "../longmemeval/providers/qdrant-provider.js"; +import type { LLMProvider } from "../longmemeval/reader.js"; +import { StubEmbeddingProvider, StubLLMProvider } from "../longmemeval/reader.js"; +import type { EmbeddingProvider } from "../longmemeval/retriever.js"; +import type { + BenchmarkMetrics, + BenchmarkProgress, + BenchmarkRunResult, + RunBenchmarkConfig, +} from "./types.js"; + +/** + * Callbacks for monitoring benchmark execution + */ +export interface BenchmarkCallbacks { + /** Called when progress is made */ + onProgress?: (progress: BenchmarkProgress) => void; +} + +/** + * Run a benchmark with the given configuration + * + * This is the main programmatic entry point for running benchmarks. + * Use `buildBenchmarkConfig` to create a complete configuration from partial options. + * + * @param config - Complete benchmark configuration + * @param callbacks - Optional callbacks for progress monitoring + * @returns Benchmark results including metrics, report, and JSONL output + * + * @example + * ```ts + * import { runBenchmark, buildBenchmarkConfig } from "@engram/benchmark"; + * + * const config = buildBenchmarkConfig({ + * dataset: "./data/longmemeval_oracle.json", + * limit: 50, + * }); + * + * const result = await runBenchmark(config, { + * onProgress: (p) => console.log(`${p.stage}: ${p.current}/${p.total}`), + * }); + * + * console.log(`Accuracy: ${result.metrics.accuracy}`); + * ``` + */ +export async function runBenchmark( + config: RunBenchmarkConfig, + callbacks?: BenchmarkCallbacks, +): Promise { + const startTime = Date.now(); + + // Initialize providers + const embeddings = createEmbeddingProvider(config); + const llm = createLLMProvider(config); + const customRetriever = createCustomRetriever(config); + + // Create pipeline + const pipeline = new BenchmarkPipeline(embeddings, llm, { + loader: { + datasetPath: config.dataset, + variant: config.variant, + limit: config.limit, + }, + retriever: { + method: config.retriever, + topK: config.topK, + timeAwareExpansion: false, + }, + reader: { + chainOfNote: false, + abstentionDetection: config.abstention, + abstentionNLI: false, + abstentionNLIThreshold: 0.5, + }, + keyExpansion: { + enabled: false, + }, + temporal: { + enabled: config.temporalAware, + }, + customRetriever, + onProgress: callbacks?.onProgress, + }); + + // Run pipeline + const pipelineResult = await pipeline.run(); + + const totalDurationMs = Date.now() - startTime; + + // Map pipeline result to BenchmarkMetrics + const metrics = mapToMetrics(pipelineResult, totalDurationMs); + + return { + metrics, + report: pipelineResult.report, + jsonl: pipelineResult.jsonl, + }; +} + +/** + * Map pipeline result to BenchmarkMetrics format + */ +function mapToMetrics( + result: Awaited>, + totalDurationMs: number, +): BenchmarkMetrics { + const { metrics, latency } = result; + const retrieval = metrics.retrieval; + const abstention = metrics.abstention; + + return { + // QA accuracy + accuracy: metrics.overall.accuracy, + + // Retrieval metrics + recallAt1: retrieval?.recallAtK?.[1] ?? 0, + recallAt5: retrieval?.recallAtK?.[5] ?? 0, + recallAt10: retrieval?.recallAtK?.[10] ?? 0, + ndcgAt10: retrieval?.ndcgAtK?.[10] ?? 0, + mrr: retrieval?.mrr ?? 0, + + // Abstention metrics + abstentionPrecision: abstention?.precision ?? 0, + abstentionRecall: abstention?.recall ?? 0, + abstentionF1: abstention?.f1 ?? 0, + + // Latency metrics from pipeline + p50Latency: latency.p50, + p95Latency: latency.p95, + p99Latency: latency.p99, + totalDurationMs: latency.totalDurationMs || totalDurationMs, + }; +} + +/** + * Create embedding provider from config + */ +function createEmbeddingProvider(config: RunBenchmarkConfig): EmbeddingProvider { + switch (config.embeddings) { + case "engram": + // Engram uses custom retriever, stub is fine for pipeline init + return new StubEmbeddingProvider(); + + case "qdrant": + return new QdrantEmbeddingProvider({ + url: config.qdrantUrl ?? "http://localhost:6333", + }); + + default: + return new StubEmbeddingProvider(); + } +} + +/** + * Create LLM provider from config + */ +function createLLMProvider(config: RunBenchmarkConfig): LLMProvider { + switch (config.llm) { + case "anthropic": + if (!process.env.ANTHROPIC_API_KEY) { + throw new Error("ANTHROPIC_API_KEY environment variable required for Claude"); + } + return new AnthropicProvider(); + + case "openai": + if (!process.env.OPENAI_API_KEY) { + throw new Error("OPENAI_API_KEY environment variable required for OpenAI"); + } + return new OpenAICompatibleProvider(); + + case "ollama": + return new OllamaProvider({ + baseUrl: config.ollamaUrl ?? "http://localhost:11434", + model: config.ollamaModel ?? "llama3.2", + }); + + default: + return new StubLLMProvider(); + } +} + +/** + * Create custom retriever for Engram full pipeline + */ +function createCustomRetriever(config: RunBenchmarkConfig): CustomRetriever | undefined { + if (config.embeddings !== "engram") { + return undefined; + } + + return new EngramRetriever({ + qdrantUrl: config.qdrantUrl ?? "http://localhost:6333", + hybridSearch: config.hybridSearch, + learnedFusion: config.learnedFusion, + fusionModel: config.fusionModel, + rerank: config.rerank, + rerankTier: config.rerankTier, + rerankDepth: config.rerankDepth, + topK: config.topK, + multiQuery: config.multiQuery, + multiQueryVariations: config.multiQueryVariations, + abstention: config.abstention, + abstentionThreshold: config.abstentionThreshold, + sessionAware: config.sessionAware, + topSessions: config.topSessions, + turnsPerSession: config.turnsPerSession, + temporalAware: config.temporalAware, + temporalConfidenceThreshold: config.temporalConfidenceThreshold, + embeddingModel: config.embeddingModel, + }); +} diff --git a/packages/benchmark/src/core/types.ts b/packages/benchmark/src/core/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..e49df276041cb43124aea13c6964bf4a99f25885 --- /dev/null +++ b/packages/benchmark/src/core/types.ts @@ -0,0 +1,202 @@ +/** + * Shared types for programmatic benchmark API + * + * @module @engram/benchmark/core + */ + +import type { DatasetVariant } from "../longmemeval/types.js"; + +/** + * Embedding model options + */ +export type EmbeddingModel = + | "e5-small" + | "e5-base" + | "e5-large" + | "gte-base" + | "gte-large" + | "bge-small" + | "bge-base" + | "bge-large"; + +/** + * LLM provider options + */ +export type LLMProviderType = "stub" | "anthropic" | "openai" | "ollama"; + +/** + * Reranker tier options + */ +export type RerankerTier = "fast" | "accurate" | "code" | "colbert" | "llm"; + +/** + * Configuration for running a benchmark programmatically + */ +export interface RunBenchmarkConfig { + /** Path to the dataset file */ + dataset: string; + + /** Dataset variant (s, m, oracle) */ + variant: DatasetVariant; + + /** Limit number of instances to evaluate */ + limit?: number; + + // Retrieval settings + /** Number of documents to retrieve */ + topK: number; + + /** Retrieval method */ + retriever: "dense" | "bm25" | "hybrid"; + + // Engram pipeline settings + /** Embedding provider (engram uses full pipeline) */ + embeddings: "engram" | "qdrant" | "stub"; + + /** Enable hybrid search (dense + sparse) */ + hybridSearch: boolean; + + /** Enable learned fusion for hybrid search */ + learnedFusion: boolean; + + /** Fusion model path or name */ + fusionModel: string; + + /** Enable reranking */ + rerank: boolean; + + /** Reranker tier */ + rerankTier: RerankerTier; + + /** Number of candidates to rerank */ + rerankDepth: number; + + // Multi-query + /** Enable multi-query retrieval */ + multiQuery: boolean; + + /** Number of query variations to generate */ + multiQueryVariations: number; + + // Abstention + /** Enable abstention detection */ + abstention: boolean; + + /** Minimum score threshold for abstention */ + abstentionThreshold: number; + + // Session-aware + /** Enable session-aware retrieval */ + sessionAware: boolean; + + /** Number of top sessions for stage 1 */ + topSessions: number; + + /** Number of turns per session for stage 2 */ + turnsPerSession: number; + + // Temporal + /** Enable temporal-aware query parsing */ + temporalAware: boolean; + + /** Temporal confidence threshold */ + temporalConfidenceThreshold: number; + + // Embedding model + /** Embedding model to use */ + embeddingModel: EmbeddingModel; + + // LLM provider + /** LLM provider for answer generation and evaluation */ + llm: LLMProviderType; + + // Ollama settings (when llm = "ollama") + /** Ollama base URL */ + ollamaUrl?: string; + + /** Ollama model name */ + ollamaModel?: string; + + // Infrastructure + /** Qdrant URL */ + qdrantUrl?: string; +} + +/** + * Benchmark metrics returned from evaluation + */ +export interface BenchmarkMetrics { + // QA accuracy + /** Overall accuracy (correct/total) */ + accuracy: number; + + // Retrieval metrics + /** Recall@1 */ + recallAt1: number; + + /** Recall@5 */ + recallAt5: number; + + /** Recall@10 */ + recallAt10: number; + + /** NDCG@10 */ + ndcgAt10: number; + + /** Mean Reciprocal Rank */ + mrr: number; + + // Abstention metrics + /** Precision for abstention detection */ + abstentionPrecision: number; + + /** Recall for abstention detection */ + abstentionRecall: number; + + /** F1 score for abstention detection */ + abstentionF1: number; + + // Latency metrics (ms) + /** 50th percentile query latency */ + p50Latency: number; + + /** 95th percentile query latency */ + p95Latency: number; + + /** 99th percentile query latency */ + p99Latency: number; + + /** Total benchmark duration */ + totalDurationMs: number; +} + +/** + * Progress information during benchmark execution + */ +export interface BenchmarkProgress { + /** Current stage */ + stage: "loading" | "indexing" | "retrieving" | "reading" | "evaluating"; + + /** Current item number */ + current: number; + + /** Total items */ + total: number; + + /** Human-readable message */ + message: string; +} + +/** + * Result from running a benchmark + */ +export interface BenchmarkRunResult { + /** Computed metrics */ + metrics: BenchmarkMetrics; + + /** Human-readable report (markdown) */ + report: string; + + /** JSONL output (LongMemEval format) */ + jsonl: string; +} diff --git a/packages/benchmark/src/index.ts b/packages/benchmark/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4ca9269d9d8c944e9c00fa619e2828379f62c5b --- /dev/null +++ b/packages/benchmark/src/index.ts @@ -0,0 +1,29 @@ +/** + * @engram/benchmark + * + * Benchmark adapters for evaluating Engram's memory system against + * industry-standard benchmarks. + * + * Currently supported: + * - LongMemEval (ICLR 2025) + * + * @see https://github.com/xiaowu0162/LongMemEval + */ + +// Programmatic API (primary exports for automation/tuning) +export { + type BenchmarkCallbacks, + type BenchmarkMetrics, + type BenchmarkProgress, + type BenchmarkRunResult, + buildBenchmarkConfig, + DEFAULT_BENCHMARK_CONFIG, + type EmbeddingModel, + type LLMProviderType, + type RerankerTier, + type RunBenchmarkConfig, + runBenchmark, +} from "./core/index.js"; + +// LongMemEval-specific exports +export * from "./longmemeval/index.js"; diff --git a/packages/benchmark/src/longmemeval/evaluator.ts b/packages/benchmark/src/longmemeval/evaluator.ts new file mode 100644 index 0000000000000000000000000000000000000000..04e77b33d321f48f30c94dbd718dee6cede02b8a --- /dev/null +++ b/packages/benchmark/src/longmemeval/evaluator.ts @@ -0,0 +1,582 @@ +import type { LLMProvider } from "./reader.js"; +import type { + AbilityMetrics, + AbstentionMetrics, + BenchmarkResult, + EvaluatedResult, + EvaluationMetrics, + MemoryAbility, + ParsedInstance, + RetrievalMetrics, +} from "./types.js"; + +/** + * Configuration for evaluation + */ +export interface EvaluatorConfig { + /** Whether to use LLM-based evaluation (more accurate, higher cost) */ + useLLMEvaluation: boolean; + /** Use GPT-4o style evaluation prompt (LongMemEval methodology) */ + useGPT4oPrompt: boolean; + /** Strict string matching for non-LLM evaluation */ + strictMatching: boolean; + /** K values for recall and NDCG computation */ + kValues: number[]; +} + +/** + * Default evaluator configuration + */ +export const DEFAULT_EVALUATOR_CONFIG: EvaluatorConfig = { + useLLMEvaluation: false, + useGPT4oPrompt: true, + strictMatching: false, + kValues: [1, 5, 10], +}; + +/** + * Per-instance retrieval data for metrics computation + */ +export interface RetrievalData { + questionId: string; + /** IDs of retrieved documents in ranked order */ + retrievedIds: string[]; + /** Relevance scores for retrieved documents */ + scores: number[]; + /** IDs of ground truth evidence documents */ + evidenceIds: string[]; +} + +/** + * Evaluator class for computing benchmark metrics + * + * Implements Milestone 4 enhancements: + * - GPT-4o style evaluation (97% human agreement per LongMemEval) + * - NDCG@K metrics for retrieval quality + * - Abstention precision/recall metrics + */ +export class Evaluator { + private config: EvaluatorConfig; + private llm?: LLMProvider; + + constructor(config?: Partial, llm?: LLMProvider) { + this.config = { ...DEFAULT_EVALUATOR_CONFIG, ...config }; + this.llm = llm; + } + + /** + * Evaluate a single result against ground truth + */ + async evaluateOne( + result: BenchmarkResult, + instance: ParsedInstance, + _abstained?: boolean, + ): Promise { + const correct = + this.config.useLLMEvaluation && this.llm + ? await this.llmJudge(result.hypothesis, instance.answer, instance.question) + : this.stringMatch(result.hypothesis, instance.answer); + + return { + ...result, + answer: instance.answer, + questionType: instance.questionType, + memoryAbility: instance.memoryAbility, + correct, + }; + } + + /** + * Evaluate all results and compute aggregate metrics + */ + async evaluateAll( + results: BenchmarkResult[], + instances: ParsedInstance[], + retrievalData?: RetrievalData[], + abstentionFlags?: Map, + ): Promise<{ + evaluated: EvaluatedResult[]; + metrics: EvaluationMetrics; + }> { + // Create lookup map for instances + const instanceMap = new Map(instances.map((i) => [i.questionId, i])); + + // Evaluate each result + const evaluated: EvaluatedResult[] = []; + for (const result of results) { + const instance = instanceMap.get(result.questionId); + if (!instance) { + console.warn(`No instance found for question: ${result.questionId}`); + continue; + } + + const abstained = abstentionFlags?.get(result.questionId); + const evalResult = await this.evaluateOne(result, instance, abstained); + evaluated.push(evalResult); + } + + // Compute metrics + const metrics = this.computeMetrics(evaluated); + + // Compute retrieval metrics if data provided + if (retrievalData && retrievalData.length > 0) { + metrics.retrieval = this.computeRetrievalMetrics(retrievalData); + } + + // Compute abstention metrics if flags provided + if (abstentionFlags) { + metrics.abstention = this.computeAbstentionMetrics(evaluated, abstentionFlags); + } + + return { evaluated, metrics }; + } + + /** + * String-based matching (baseline evaluation) + */ + private stringMatch(hypothesis: string, answer: string): boolean { + const normalizedHyp = this.normalize(hypothesis); + const normalizedAns = this.normalize(answer); + + if (this.config.strictMatching) { + return normalizedHyp === normalizedAns; + } + + // Fuzzy matching: check if answer is contained in hypothesis + // or if they share significant overlap + if (normalizedHyp.includes(normalizedAns)) { + return true; + } + + if (normalizedAns.includes(normalizedHyp)) { + return true; + } + + // Check word overlap + const hypWords = new Set(normalizedHyp.split(/\s+/)); + const ansWords = normalizedAns.split(/\s+/); + + const overlap = ansWords.filter((w) => hypWords.has(w)).length; + const overlapRatio = overlap / ansWords.length; + + return overlapRatio >= 0.7; + } + + /** + * Normalize text for comparison + */ + private normalize(text: string): string { + return text + .toLowerCase() + .replace(/[^\w\s]/g, "") // Remove punctuation + .replace(/\s+/g, " ") // Normalize whitespace + .trim(); + } + + /** + * LLM-based evaluation using GPT-4o style prompt + * Based on LongMemEval's methodology (97% human agreement) + */ + private async llmJudge(hypothesis: string, answer: string, question: string): Promise { + if (!this.llm) { + throw new Error("LLM provider required for LLM evaluation"); + } + + const prompt = this.config.useGPT4oPrompt + ? this.buildGPT4oPrompt(hypothesis, answer, question) + : this.buildBasicPrompt(hypothesis, answer, question); + + const response = await this.llm.complete(prompt, { + temperature: 0, + maxTokens: 50, + }); + + return this.parseJudgment(response.text); + } + + /** + * GPT-4o style evaluation prompt (LongMemEval methodology) + * Achieves 97% agreement with human evaluation + */ + private buildGPT4oPrompt(hypothesis: string, answer: string, question: string): string { + return `You are an expert evaluator for a memory-augmented AI system. Your task is to determine if a generated answer correctly addresses a question when compared to a ground-truth reference answer. + +## Evaluation Criteria + +A generated answer is CORRECT if: +1. It contains the essential information from the reference answer +2. The factual claims match the reference (dates, names, numbers, etc.) +3. Minor phrasing differences or additional context are acceptable +4. Partial answers are correct if they include the key facts + +A generated answer is INCORRECT if: +1. It contradicts the reference answer +2. It contains factually wrong information +3. It is completely unrelated to the question +4. It is a refusal/abstention when the information is available + +Special cases: +- Abstention answers ("I don't know", "No information available") are CORRECT only if the reference indicates the question is unanswerable +- Numeric answers must match exactly or be semantically equivalent (e.g., "3" = "three") +- Date formats can vary as long as they refer to the same date + +## Question +${question} + +## Reference Answer (Ground Truth) +${answer} + +## Generated Answer +${hypothesis} + +## Your Judgment +Analyze the generated answer against the reference. Consider semantic equivalence, not just string matching. + +Output ONLY one of these two words on a single line: +CORRECT +INCORRECT`; + } + + /** + * Basic evaluation prompt (fallback) + */ + private buildBasicPrompt(hypothesis: string, answer: string, question: string): string { + return `You are evaluating whether a generated answer correctly addresses a question compared to a reference answer. + +## Question +${question} + +## Reference Answer +${answer} + +## Generated Answer +${hypothesis} + +## Task +Determine if the generated answer is correct. Consider: +1. The generated answer captures the key information from the reference +2. Minor differences in wording are acceptable +3. Additional correct information is acceptable +4. Incorrect or contradictory information is NOT acceptable +5. "I don't know" type answers are only correct if the reference also indicates unknown + +Respond with ONLY "CORRECT" or "INCORRECT" on a single line.`; + } + + /** + * Parse LLM judgment response + */ + private parseJudgment(text: string): boolean { + const upper = text.trim().toUpperCase(); + // Look for CORRECT not preceded by IN + if (upper.includes("INCORRECT")) { + return false; + } + return upper.includes("CORRECT"); + } + + /** + * Compute aggregate metrics from evaluated results + */ + private computeMetrics(evaluated: EvaluatedResult[]): EvaluationMetrics { + const total = evaluated.length; + const correct = evaluated.filter((e) => e.correct).length; + + // Initialize per-ability metrics + const byAbility: Record = { + IE: { total: 0, correct: 0, accuracy: 0 }, + MR: { total: 0, correct: 0, accuracy: 0 }, + TR: { total: 0, correct: 0, accuracy: 0 }, + KU: { total: 0, correct: 0, accuracy: 0 }, + ABS: { total: 0, correct: 0, accuracy: 0 }, + }; + + // Aggregate by ability + for (const result of evaluated) { + const ability = result.memoryAbility; + byAbility[ability].total++; + if (result.correct) { + byAbility[ability].correct++; + } + } + + // Compute accuracy per ability + for (const ability of Object.keys(byAbility) as MemoryAbility[]) { + const metrics = byAbility[ability]; + metrics.accuracy = metrics.total > 0 ? metrics.correct / metrics.total : 0; + } + + return { + overall: { + total, + correct, + accuracy: total > 0 ? correct / total : 0, + }, + byAbility, + }; + } + + /** + * Compute retrieval metrics including NDCG + */ + private computeRetrievalMetrics(retrievalData: RetrievalData[]): RetrievalMetrics { + const recallAtK: Record = {}; + const ndcgAtK: Record = {}; + + // Initialize for each K value + for (const k of this.config.kValues) { + recallAtK[k] = 0; + ndcgAtK[k] = 0; + } + + let totalTurnRecall = 0; + let totalSessionRecall = 0; + let totalMRR = 0; + + for (const data of retrievalData) { + const evidenceSet = new Set(data.evidenceIds); + + // Compute recall at K + for (const k of this.config.kValues) { + const topK = data.retrievedIds.slice(0, k); + const retrieved = topK.filter((id) => evidenceSet.has(id)).length; + const recall = evidenceSet.size > 0 ? retrieved / evidenceSet.size : 1; + recallAtK[k] += recall; + } + + // Compute NDCG at K + for (const k of this.config.kValues) { + ndcgAtK[k] += this.computeNDCG(data.retrievedIds.slice(0, k), evidenceSet); + } + + // Turn recall (all retrieved) + const allRetrieved = data.retrievedIds.filter((id) => evidenceSet.has(id)).length; + totalTurnRecall += evidenceSet.size > 0 ? allRetrieved / evidenceSet.size : 1; + + // Session recall (simplified - treat as same for now) + totalSessionRecall += evidenceSet.size > 0 ? allRetrieved / evidenceSet.size : 1; + + // MRR - reciprocal rank of first relevant document + totalMRR += this.computeReciprocalRank(data.retrievedIds, evidenceSet); + } + + const n = retrievalData.length || 1; + + // Average across all instances + for (const k of this.config.kValues) { + recallAtK[k] /= n; + ndcgAtK[k] /= n; + } + + return { + turnRecall: totalTurnRecall / n, + sessionRecall: totalSessionRecall / n, + recallAtK, + ndcgAtK, + mrr: totalMRR / n, + }; + } + + /** + * Compute NDCG (Normalized Discounted Cumulative Gain) + * + * NDCG measures the quality of a ranking by comparing to ideal ranking. + * Uses binary relevance (1 if in evidence set, 0 otherwise). + */ + private computeNDCG(rankedIds: string[], evidenceSet: Set): number { + if (rankedIds.length === 0 || evidenceSet.size === 0) { + return evidenceSet.size === 0 ? 1 : 0; + } + + // DCG: sum of relevance / log2(rank + 1) + let dcg = 0; + for (let i = 0; i < rankedIds.length; i++) { + const relevance = evidenceSet.has(rankedIds[i]) ? 1 : 0; + dcg += relevance / Math.log2(i + 2); // i+2 because log2(1) = 0 + } + + // IDCG: ideal DCG (all relevant items at top) + const idealRanking = Math.min(evidenceSet.size, rankedIds.length); + let idcg = 0; + for (let i = 0; i < idealRanking; i++) { + idcg += 1 / Math.log2(i + 2); + } + + return idcg > 0 ? dcg / idcg : 0; + } + + /** + * Compute reciprocal rank (1/rank of first relevant item) + */ + private computeReciprocalRank(rankedIds: string[], evidenceSet: Set): number { + for (let i = 0; i < rankedIds.length; i++) { + if (evidenceSet.has(rankedIds[i])) { + return 1 / (i + 1); + } + } + return 0; + } + + /** + * Compute abstention-specific metrics + * + * For abstention questions (ABS), we want to measure: + * - Precision: Of all abstentions, how many were correct? + * - Recall: Of questions requiring abstention, how many abstained? + */ + private computeAbstentionMetrics( + evaluated: EvaluatedResult[], + abstentionFlags: Map, + ): AbstentionMetrics { + let truePositives = 0; // Correctly abstained on ABS questions + let falsePositives = 0; // Incorrectly abstained on non-ABS questions + let falseNegatives = 0; // Should have abstained but didn't + let trueNegatives = 0; // Correctly answered non-ABS questions + + for (const result of evaluated) { + const didAbstain = abstentionFlags.get(result.questionId) ?? false; + const shouldAbstain = result.memoryAbility === "ABS"; + + if (shouldAbstain && didAbstain) { + truePositives++; + } else if (!shouldAbstain && didAbstain) { + falsePositives++; + } else if (shouldAbstain && !didAbstain) { + falseNegatives++; + } else { + trueNegatives++; + } + } + + const precision = + truePositives + falsePositives > 0 ? truePositives / (truePositives + falsePositives) : 0; + + const recall = + truePositives + falseNegatives > 0 ? truePositives / (truePositives + falseNegatives) : 0; + + const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0; + + return { + truePositives, + falsePositives, + falseNegatives, + trueNegatives, + precision, + recall, + f1, + }; + } +} + +/** + * Format metrics as a human-readable report + */ +export function formatMetricsReport(metrics: EvaluationMetrics): string { + const lines: string[] = [ + "# LongMemEval Benchmark Results", + "", + "## Overall", + `- Total: ${metrics.overall.total}`, + `- Correct: ${metrics.overall.correct}`, + `- Accuracy: ${(metrics.overall.accuracy * 100).toFixed(1)}%`, + "", + "## By Memory Ability", + "", + "| Ability | Total | Correct | Accuracy |", + "|:--------|------:|--------:|---------:|", + ]; + + const abilityNames: Record = { + IE: "Information Extraction", + MR: "Multi-Session Reasoning", + TR: "Temporal Reasoning", + KU: "Knowledge Update", + ABS: "Abstention", + }; + + for (const [ability, name] of Object.entries(abilityNames) as [MemoryAbility, string][]) { + const m = metrics.byAbility[ability]; + lines.push( + `| ${name} (${ability}) | ${m.total} | ${m.correct} | ${(m.accuracy * 100).toFixed(1)}% |`, + ); + } + + if (metrics.retrieval) { + lines.push(""); + lines.push("## Retrieval Metrics"); + lines.push(""); + lines.push(`- Turn Recall: ${((metrics.retrieval.turnRecall ?? 0) * 100).toFixed(1)}%`); + lines.push(`- Session Recall: ${((metrics.retrieval.sessionRecall ?? 0) * 100).toFixed(1)}%`); + if (metrics.retrieval.mrr !== undefined) { + lines.push(`- MRR: ${metrics.retrieval.mrr.toFixed(3)}`); + } + lines.push(""); + lines.push("### Recall@K"); + lines.push(""); + lines.push("| K | Recall |"); + lines.push("|--:|-------:|"); + if (metrics.retrieval.recallAtK) { + for (const [k, recall] of Object.entries(metrics.retrieval.recallAtK)) { + lines.push(`| ${k} | ${((recall ?? 0) * 100).toFixed(1)}% |`); + } + } + if (metrics.retrieval.ndcgAtK) { + lines.push(""); + lines.push("### NDCG@K"); + lines.push(""); + lines.push("| K | NDCG |"); + lines.push("|--:|-----:|"); + for (const [k, ndcg] of Object.entries(metrics.retrieval.ndcgAtK)) { + lines.push(`| ${k} | ${(ndcg ?? 0).toFixed(3)} |`); + } + } + } + + if (metrics.abstention) { + lines.push(""); + lines.push("## Abstention Metrics"); + lines.push(""); + lines.push(`- Precision: ${(metrics.abstention.precision * 100).toFixed(1)}%`); + lines.push(`- Recall: ${(metrics.abstention.recall * 100).toFixed(1)}%`); + lines.push(`- F1 Score: ${(metrics.abstention.f1 * 100).toFixed(1)}%`); + lines.push(""); + lines.push("### Confusion Matrix"); + lines.push(""); + lines.push("| | Abstained | Answered |"); + lines.push("|:--|----------:|---------:|"); + lines.push( + `| Should Abstain | ${metrics.abstention.truePositives} (TP) | ${metrics.abstention.falseNegatives} (FN) |`, + ); + lines.push( + `| Should Answer | ${metrics.abstention.falsePositives} (FP) | ${metrics.abstention.trueNegatives} (TN) |`, + ); + } + + return lines.join("\n"); +} + +/** + * Save results to JSONL format (LongMemEval output format) + */ +export function resultsToJsonl(results: BenchmarkResult[]): string { + return results + .map((r) => JSON.stringify({ question_id: r.questionId, hypothesis: r.hypothesis })) + .join("\n"); +} + +/** + * Parse results from JSONL format + */ +export function parseJsonlResults(jsonl: string): BenchmarkResult[] { + return jsonl + .trim() + .split("\n") + .filter((line) => line.trim()) + .map((line) => { + const parsed = JSON.parse(line); + return { + questionId: parsed.question_id, + hypothesis: parsed.hypothesis, + }; + }); +} diff --git a/packages/benchmark/src/longmemeval/index.ts b/packages/benchmark/src/longmemeval/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..798c633972baac66b3a82e3e0ecf528cfa00d3b3 --- /dev/null +++ b/packages/benchmark/src/longmemeval/index.ts @@ -0,0 +1,24 @@ +/** + * LongMemEval Benchmark Adapter + * + * Evaluates Engram's memory system against the LongMemEval benchmark (ICLR 2025). + * + * @see https://github.com/xiaowu0162/LongMemEval + * @see https://arxiv.org/abs/2410.10813 + */ + +export * from "./evaluator.js"; +// Optimizations (Milestone 2) +export * from "./key-expansion.js"; +// Core components +export * from "./loader.js"; +export * from "./mapper.js"; +// Pipeline +export * from "./pipeline.js"; +// Providers (real implementations) +export * from "./providers/index.js"; +export * from "./reader.js"; +export * from "./retriever.js"; +export * from "./temporal.js"; +// Types +export * from "./types.js"; diff --git a/packages/benchmark/src/longmemeval/key-expansion.ts b/packages/benchmark/src/longmemeval/key-expansion.ts new file mode 100644 index 0000000000000000000000000000000000000000..de3e6978bc2847a20cc1fdcf3cef66e4c7bc638f --- /dev/null +++ b/packages/benchmark/src/longmemeval/key-expansion.ts @@ -0,0 +1,494 @@ +import type { EngramDocument } from "./mapper.js"; +import type { LLMProvider } from "./reader.js"; + +/** + * Key Expansion for improved retrieval + * + * Based on LongMemEval findings: + * - Fact-augmented key expansion improves recall by 9.4% + * - Extracting summaries, keyphrases, user facts, and timestamped events + * + * @see https://arxiv.org/abs/2410.10813 + */ + +/** + * Types of key expansion supported + */ +export type ExpansionType = "summary" | "keyphrase" | "userfact" | "event"; + +/** + * Configuration for key expansion + */ +export interface KeyExpansionConfig { + /** Which expansion types to use */ + types: ExpansionType[]; + /** LLM for extraction (optional - uses heuristics if not provided) */ + llm?: LLMProvider; + /** Maximum tokens per extraction */ + maxTokens: number; +} + +const DEFAULT_CONFIG: KeyExpansionConfig = { + types: ["keyphrase", "userfact"], + maxTokens: 256, +}; + +/** + * Expanded document with additional keys for retrieval + */ +export interface ExpandedDocument extends EngramDocument { + /** Original content */ + originalContent: string; + /** Expanded content for indexing */ + expandedContent: string; + /** Extracted metadata */ + expansion: { + summary?: string; + keyphrases?: string[]; + userFacts?: string[]; + events?: TimestampedEvent[]; + }; +} + +/** + * A timestamped event extracted from content + */ +export interface TimestampedEvent { + description: string; + date?: Date; + dateText?: string; +} + +/** + * Key expander that augments documents with extracted facts + */ +export class KeyExpander { + private config: KeyExpansionConfig; + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + } + + /** + * Expand a batch of documents + */ + async expandBatch(documents: EngramDocument[]): Promise { + const expanded: ExpandedDocument[] = []; + + for (const doc of documents) { + expanded.push(await this.expand(doc)); + } + + return expanded; + } + + /** + * Expand a single document + */ + async expand(document: EngramDocument): Promise { + const expansion: ExpandedDocument["expansion"] = {}; + + // Extract based on configured types + for (const type of this.config.types) { + switch (type) { + case "summary": + expansion.summary = await this.extractSummary(document.content); + break; + case "keyphrase": + expansion.keyphrases = await this.extractKeyphrases(document.content); + break; + case "userfact": + expansion.userFacts = await this.extractUserFacts(document.content); + break; + case "event": + expansion.events = await this.extractEvents(document.content, document.validTime); + break; + } + } + + // Build expanded content + const expandedContent = this.buildExpandedContent(document.content, expansion); + + return { + ...document, + originalContent: document.content, + expandedContent, + content: expandedContent, // Replace content for indexing + expansion, + }; + } + + /** + * Extract a summary from content + */ + private async extractSummary(content: string): Promise { + if (this.config.llm) { + return this.llmExtractSummary(content); + } + return this.heuristicSummary(content); + } + + /** + * Extract keyphrases from content + */ + private async extractKeyphrases(content: string): Promise { + if (this.config.llm) { + return this.llmExtractKeyphrases(content); + } + return this.heuristicKeyphrases(content); + } + + /** + * Extract user facts from content + */ + private async extractUserFacts(content: string): Promise { + if (this.config.llm) { + return this.llmExtractUserFacts(content); + } + return this.heuristicUserFacts(content); + } + + /** + * Extract timestamped events from content + */ + private async extractEvents(content: string, baseDate: Date): Promise { + if (this.config.llm) { + return this.llmExtractEvents(content, baseDate); + } + return this.heuristicEvents(content, baseDate); + } + + /** + * Build expanded content from original + extracted facts + */ + private buildExpandedContent(original: string, expansion: ExpandedDocument["expansion"]): string { + const parts = [original]; + + if (expansion.summary) { + parts.push(`[Summary: ${expansion.summary}]`); + } + + if (expansion.keyphrases && expansion.keyphrases.length > 0) { + parts.push(`[Keywords: ${expansion.keyphrases.join(", ")}]`); + } + + if (expansion.userFacts && expansion.userFacts.length > 0) { + parts.push(`[Facts: ${expansion.userFacts.join("; ")}]`); + } + + if (expansion.events && expansion.events.length > 0) { + const eventStrs = expansion.events.map( + (e) => `${e.description}${e.dateText ? ` (${e.dateText})` : ""}`, + ); + parts.push(`[Events: ${eventStrs.join("; ")}]`); + } + + return parts.join("\n"); + } + + // ========== LLM-based extraction ========== + + private async llmExtractSummary(content: string): Promise { + const prompt = `Summarize the following conversation turn in one sentence. Focus on the key information shared. + +Content: +${content} + +Summary (one sentence):`; + + const response = await this.config.llm?.complete(prompt, { maxTokens: 100 }); + return response?.text.trim() ?? ""; + } + + private async llmExtractKeyphrases(content: string): Promise { + const prompt = `Extract 3-5 key phrases from the following text. Return only the phrases, one per line. + +Content: +${content} + +Key phrases:`; + + const response = await this.config.llm?.complete(prompt, { maxTokens: 100 }); + if (!response) return []; + return response.text + .split("\n") + .map((line) => line.trim().replace(/^[-•*]\s*/, "")) + .filter((line) => line.length > 0); + } + + private async llmExtractUserFacts(content: string): Promise { + const prompt = `Extract any personal facts about the user from this conversation. Include preferences, biographical info, habits, etc. Return facts as simple statements, one per line. + +Content: +${content} + +User facts (if any):`; + + const response = await this.config.llm?.complete(prompt, { maxTokens: 150 }); + if (!response) return []; + return response.text + .split("\n") + .map((line) => line.trim().replace(/^[-•*]\s*/, "")) + .filter( + (line) => + line.length > 0 && + !line.toLowerCase().includes("no ") && + !line.toLowerCase().includes("none"), + ); + } + + private async llmExtractEvents(content: string, baseDate: Date): Promise { + const prompt = `Extract any events or activities mentioned in this text. For each event, note if a specific date or time is mentioned. Return as JSON array. + +Content: +${content} + +Base date for relative references: ${baseDate.toISOString().split("T")[0]} + +Return JSON array of objects with "description" and optional "dateText" fields:`; + + const response = await this.config.llm?.complete(prompt, { maxTokens: 200 }); + if (!response) return []; + + try { + const jsonMatch = response.text.match(/\[[\s\S]*\]/); + if (jsonMatch) { + return JSON.parse(jsonMatch[0]); + } + } catch { + // Fall back to heuristic + } + + return this.heuristicEvents(content, baseDate); + } + + // ========== Heuristic-based extraction ========== + + private heuristicSummary(content: string): string { + // Take first sentence or first 100 chars + const firstSentence = content.match(/^[^.!?]+[.!?]/); + if (firstSentence && firstSentence[0].length < 200) { + return firstSentence[0].trim(); + } + return `${content.slice(0, 100).trim()}...`; + } + + private heuristicKeyphrases(content: string): string[] { + const keyphrases: string[] = []; + + // Extract noun phrases (simplified) + const words = content.toLowerCase().split(/\s+/); + const stopwords = new Set([ + "the", + "a", + "an", + "is", + "are", + "was", + "were", + "be", + "been", + "being", + "have", + "has", + "had", + "do", + "does", + "did", + "will", + "would", + "could", + "should", + "may", + "might", + "must", + "shall", + "can", + "need", + "dare", + "ought", + "used", + "to", + "of", + "in", + "for", + "on", + "with", + "at", + "by", + "from", + "as", + "into", + "through", + "during", + "before", + "after", + "above", + "below", + "between", + "under", + "again", + "further", + "then", + "once", + "here", + "there", + "when", + "where", + "why", + "how", + "all", + "each", + "few", + "more", + "most", + "other", + "some", + "such", + "no", + "nor", + "not", + "only", + "own", + "same", + "so", + "than", + "too", + "very", + "just", + "i", + "me", + "my", + "myself", + "we", + "our", + "ours", + "you", + "your", + "he", + "him", + "his", + "she", + "her", + "it", + "its", + "they", + "them", + "their", + "what", + "which", + "who", + "whom", + "this", + "that", + "these", + "those", + "am", + "and", + "but", + "if", + "or", + "because", + "until", + "while", + ]); + + // Find significant words + const significantWords = words.filter( + (w) => w.length > 3 && !stopwords.has(w) && /^[a-z]+$/.test(w), + ); + + // Count frequency + const freq = new Map(); + for (const word of significantWords) { + freq.set(word, (freq.get(word) ?? 0) + 1); + } + + // Get top words + const sorted = [...freq.entries()].sort((a, b) => b[1] - a[1]); + keyphrases.push(...sorted.slice(0, 5).map(([word]) => word)); + + return keyphrases; + } + + private heuristicUserFacts(content: string): string[] { + const facts: string[] = []; + const _lowerContent = content.toLowerCase(); + + // Patterns for user facts + const patterns = [ + /my (?:favorite|favourite) (\w+) is ([^.!?,]+)/gi, + /i (?:am|'m) (?:a |an )?([^.!?,]+)/gi, + /i (?:live|work|study) (?:in|at) ([^.!?,]+)/gi, + /i (?:like|love|enjoy|prefer) ([^.!?,]+)/gi, + /i (?:have|own|got) (?:a |an )?([^.!?,]+)/gi, + /my (?:name|job|occupation|hobby) is ([^.!?,]+)/gi, + /i (?:was born|grew up) (?:in|on) ([^.!?,]+)/gi, + ]; + + for (const pattern of patterns) { + for (const match of content.matchAll(pattern)) { + const fact = match[0].trim(); + if (fact.length > 5 && fact.length < 100) { + facts.push(fact); + } + } + } + + return [...new Set(facts)].slice(0, 5); + } + + private heuristicEvents(content: string, _baseDate: Date): TimestampedEvent[] { + const events: TimestampedEvent[] = []; + + // Patterns for events with dates + const datePatterns = [ + /(?:on|at|during|last|next|this) (monday|tuesday|wednesday|thursday|friday|saturday|sunday)/gi, + /(?:on|in|during) (january|february|march|april|may|june|july|august|september|october|november|december)(?: \d{1,2})?(?:,? \d{4})?/gi, + /(yesterday|today|tomorrow|last week|next week|last month|next month)/gi, + /(\d{1,2}\/\d{1,2}(?:\/\d{2,4})?)/g, + /(\d{4}-\d{2}-\d{2})/g, + ]; + + // Activity patterns + const activityPatterns = [ + /i (?:went|visited|attended|saw|met|had) ([^.!?]+)/gi, + /(?:going|planning|scheduled) to ([^.!?]+)/gi, + /(?:bought|purchased|ordered|received) ([^.!?]+)/gi, + ]; + + // Extract date mentions + const dateMentions: string[] = []; + for (const pattern of datePatterns) { + for (const match of content.matchAll(pattern)) { + dateMentions.push(match[1]); + } + } + + // Extract activities + for (const pattern of activityPatterns) { + for (const match of content.matchAll(pattern)) { + const description = match[0].trim(); + if (description.length > 10 && description.length < 150) { + events.push({ + description, + dateText: dateMentions[0], // Associate with first date mention + }); + } + } + } + + return events.slice(0, 5); + } +} + +/** + * Apply key expansion to documents before indexing + */ +export async function expandDocuments( + documents: EngramDocument[], + config?: Partial, +): Promise { + const expander = new KeyExpander(config); + return expander.expandBatch(documents); +} diff --git a/packages/benchmark/src/longmemeval/loader.ts b/packages/benchmark/src/longmemeval/loader.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ae7d662c39ef337dd236d61c5cd2c1ee8350d50 --- /dev/null +++ b/packages/benchmark/src/longmemeval/loader.ts @@ -0,0 +1,226 @@ +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { + type DatasetVariant, + getMemoryAbility, + type LongMemEvalDataset, + LongMemEvalDatasetSchema, + type LongMemEvalInstance, + type ParsedInstance, + type ParsedSession, + type ParsedTurn, +} from "./types.js"; + +/** + * Configuration for the dataset loader + */ +export interface LoaderConfig { + /** Path to the dataset directory or file */ + datasetPath: string; + /** Dataset variant to load */ + variant?: DatasetVariant; + /** Limit number of instances to load (for testing) */ + limit?: number; + /** Filter by question types */ + questionTypes?: string[]; +} + +/** + * Result of loading a dataset + */ +export interface LoadResult { + /** Parsed instances ready for processing */ + instances: ParsedInstance[]; + /** Raw dataset for reference */ + raw: LongMemEvalDataset; + /** Statistics about the loaded dataset */ + stats: LoadStats; +} + +/** + * Statistics about the loaded dataset + */ +export interface LoadStats { + totalInstances: number; + totalSessions: number; + totalTurns: number; + byAbility: Record; + abstentionCount: number; +} + +/** + * Loads and parses a LongMemEval dataset + */ +export async function loadDataset(config: LoaderConfig): Promise { + const datasetPath = resolveDatasetPath(config); + const rawContent = await readFile(datasetPath, "utf-8"); + const rawData = JSON.parse(rawContent); + + // Validate with Zod + const dataset = LongMemEvalDatasetSchema.parse(rawData); + + // Apply filters + let filteredDataset = dataset; + + if (config.questionTypes && config.questionTypes.length > 0) { + filteredDataset = filteredDataset.filter((instance) => + config.questionTypes?.includes(instance.question_type), + ); + } + + if (config.limit && config.limit > 0) { + filteredDataset = filteredDataset.slice(0, config.limit); + } + + // Parse instances + const instances = filteredDataset.map(parseInstance); + + // Compute statistics + const stats = computeStats(instances); + + return { + instances, + raw: filteredDataset, + stats, + }; +} + +/** + * Resolves the dataset path based on variant + */ +function resolveDatasetPath(config: LoaderConfig): string { + const { datasetPath, variant } = config; + + // If path ends with .json, use it directly + if (datasetPath.endsWith(".json")) { + return datasetPath; + } + + // Otherwise, construct path from variant + const filename = variant ? `longmemeval_${variant}_cleaned.json` : "longmemeval_s_cleaned.json"; + + return join(datasetPath, filename); +} + +/** + * Parses a raw LongMemEval instance into a normalized format + */ +function parseInstance(raw: LongMemEvalInstance): ParsedInstance { + const isAbstention = raw.question_id.endsWith("_abs"); + const memoryAbility = getMemoryAbility(raw.question_type, raw.question_id); + + // Parse sessions with timestamps + const sessions: ParsedSession[] = raw.haystack_sessions.map((session, sessionIndex) => { + const sessionId = raw.haystack_session_ids[sessionIndex]; + const timestamp = parseTimestamp(raw.haystack_dates[sessionIndex]); + + const turns: ParsedTurn[] = session.map((turn, turnIndex) => ({ + role: turn.role, + content: turn.content, + hasAnswer: turn.has_answer ?? false, + sequenceIndex: turnIndex, + })); + + return { + sessionId, + timestamp, + turns, + }; + }); + + return { + questionId: raw.question_id, + questionType: raw.question_type, + memoryAbility, + question: raw.question, + answer: raw.answer, + questionDate: parseTimestamp(raw.question_date), + sessions, + answerSessionIds: raw.answer_session_ids, + isAbstention, + }; +} + +/** + * Parses a timestamp string into a Date object + * Handles various formats from the dataset + */ +function parseTimestamp(timestamp: string): Date { + // Try ISO 8601 first + const date = new Date(timestamp); + + if (!Number.isNaN(date.getTime())) { + return date; + } + + // Try other formats if needed + // The dataset uses ISO format, so this should generally work + throw new Error(`Unable to parse timestamp: ${timestamp}`); +} + +/** + * Computes statistics about the loaded instances + */ +function computeStats(instances: ParsedInstance[]): LoadStats { + const byAbility: Record = { + IE: 0, + MR: 0, + TR: 0, + KU: 0, + ABS: 0, + }; + + let totalSessions = 0; + let totalTurns = 0; + let abstentionCount = 0; + + for (const instance of instances) { + byAbility[instance.memoryAbility]++; + + if (instance.isAbstention) { + abstentionCount++; + } + + totalSessions += instance.sessions.length; + + for (const session of instance.sessions) { + totalTurns += session.turns.length; + } + } + + return { + totalInstances: instances.length, + totalSessions, + totalTurns, + byAbility, + abstentionCount, + }; +} + +/** + * Loads a single instance by question ID + */ +export async function loadInstance( + config: LoaderConfig, + questionId: string, +): Promise { + const { instances } = await loadDataset(config); + return instances.find((i) => i.questionId === questionId) ?? null; +} + +/** + * Validates that a dataset file exists and is valid + */ +export async function validateDataset( + datasetPath: string, +): Promise<{ valid: boolean; error?: string; stats?: LoadStats }> { + try { + const result = await loadDataset({ datasetPath }); + return { valid: true, stats: result.stats }; + } catch (error) { + return { + valid: false, + error: error instanceof Error ? error.message : String(error), + }; + } +} diff --git a/packages/benchmark/src/longmemeval/mapper.ts b/packages/benchmark/src/longmemeval/mapper.ts new file mode 100644 index 0000000000000000000000000000000000000000..7381dad77669edaf87f3d28179f9c4d694cfe463 --- /dev/null +++ b/packages/benchmark/src/longmemeval/mapper.ts @@ -0,0 +1,234 @@ +import type { ParsedInstance, ParsedSession } from "./types.js"; + +/** + * Configuration for mapping LongMemEval data to Engram format + */ +export interface MapperConfig { + /** Granularity for indexing (turn is recommended by LongMemEval paper) */ + granularity: "session" | "turn"; + /** Whether to include assistant turns in embeddings */ + includeAssistant: boolean; +} + +/** + * Default mapper configuration based on LongMemEval findings + * - Turn granularity is optimal (Finding 1 from paper) + * - Include both user and assistant (recommended setting) + */ +export const DEFAULT_MAPPER_CONFIG: MapperConfig = { + granularity: "turn", + includeAssistant: true, +}; + +/** + * Represents a document ready for indexing in Engram + */ +export interface EngramDocument { + /** Unique identifier */ + id: string; + /** Instance this document belongs to */ + instanceId: string; + /** Original session ID from LongMemEval */ + sessionId: string; + /** Content to embed */ + content: string; + /** Valid time - when this conversation occurred */ + validTime: Date; + /** Metadata for filtering and evaluation */ + metadata: EngramDocumentMetadata; +} + +export interface EngramDocumentMetadata { + /** Original question ID */ + questionId: string; + /** Role of the speaker */ + role: "user" | "assistant" | "combined"; + /** Whether this document contains answer evidence */ + hasAnswer: boolean; + /** Turn index within the session */ + turnIndex?: number; + /** Session index within the instance */ + sessionIndex: number; +} + +/** + * Result of mapping an instance to Engram documents + */ +export interface MappedInstance { + /** The original parsed instance */ + instance: ParsedInstance; + /** Documents ready for indexing */ + documents: EngramDocument[]; + /** Evidence document IDs for evaluation */ + evidenceDocIds: string[]; +} + +/** + * Maps a LongMemEval instance to Engram documents + */ +export function mapInstance( + instance: ParsedInstance, + config: MapperConfig = DEFAULT_MAPPER_CONFIG, +): MappedInstance { + const documents: EngramDocument[] = []; + const evidenceDocIds: string[] = []; + + for (let sessionIndex = 0; sessionIndex < instance.sessions.length; sessionIndex++) { + const session = instance.sessions[sessionIndex]; + const sessionDocs = mapSession(instance.questionId, session, sessionIndex, config); + + documents.push(...sessionDocs); + + // Track evidence documents + for (const doc of sessionDocs) { + if (doc.metadata.hasAnswer) { + evidenceDocIds.push(doc.id); + } + } + } + + return { + instance, + documents, + evidenceDocIds, + }; +} + +/** + * Maps a session to Engram documents based on granularity + */ +function mapSession( + questionId: string, + session: ParsedSession, + sessionIndex: number, + config: MapperConfig, +): EngramDocument[] { + if (config.granularity === "session") { + return [mapSessionAsDocument(questionId, session, sessionIndex, config)]; + } + + return mapTurnsAsDocuments(questionId, session, sessionIndex, config); +} + +/** + * Maps an entire session as a single document + */ +function mapSessionAsDocument( + questionId: string, + session: ParsedSession, + sessionIndex: number, + config: MapperConfig, +): EngramDocument { + const relevantTurns = config.includeAssistant + ? session.turns + : session.turns.filter((t) => t.role === "user"); + + const content = relevantTurns.map((t) => `${t.role}: ${t.content}`).join("\n\n"); + + const hasAnswer = session.turns.some((t) => t.hasAnswer); + + return { + id: `${questionId}:${session.sessionId}`, + instanceId: questionId, + sessionId: session.sessionId, + content, + validTime: session.timestamp, + metadata: { + questionId, + role: "combined", + hasAnswer, + sessionIndex, + }, + }; +} + +/** + * Maps each turn as a separate document (recommended by LongMemEval) + */ +function mapTurnsAsDocuments( + questionId: string, + session: ParsedSession, + sessionIndex: number, + config: MapperConfig, +): EngramDocument[] { + const documents: EngramDocument[] = []; + + for (const turn of session.turns) { + // Skip assistant turns if not included + if (!config.includeAssistant && turn.role === "assistant") { + continue; + } + + documents.push({ + id: `${questionId}:${session.sessionId}:${turn.sequenceIndex}`, + instanceId: questionId, + sessionId: session.sessionId, + content: turn.content, + validTime: session.timestamp, + metadata: { + questionId, + role: turn.role, + hasAnswer: turn.hasAnswer, + turnIndex: turn.sequenceIndex, + sessionIndex, + }, + }); + } + + return documents; +} + +/** + * Formats documents for retrieval context + * Uses structured JSON format (recommended by LongMemEval) + */ +export function formatDocumentsForContext( + documents: EngramDocument[], + options: { includeTimestamp?: boolean; maxLength?: number } = {}, +): string { + const { includeTimestamp = true, maxLength } = options; + + const formatted = documents.map((doc, index) => { + const entry: Record = { + index: index + 1, + content: doc.content, + }; + + if (includeTimestamp) { + entry.date = doc.validTime.toISOString().split("T")[0]; + } + + if (doc.metadata.role !== "combined") { + entry.role = doc.metadata.role; + } + + return entry; + }); + + let result = JSON.stringify(formatted, null, 2); + + // Truncate if needed + if (maxLength && result.length > maxLength) { + result = `${result.slice(0, maxLength)}\n... (truncated)`; + } + + return result; +} + +/** + * Groups documents by session for session-level evaluation + */ +export function groupBySession(documents: EngramDocument[]): Map { + const groups = new Map(); + + for (const doc of documents) { + const existing = groups.get(doc.sessionId); + if (existing) { + existing.push(doc); + } else { + groups.set(doc.sessionId, [doc]); + } + } + + return groups; +} diff --git a/packages/benchmark/src/longmemeval/pipeline.ts b/packages/benchmark/src/longmemeval/pipeline.ts new file mode 100644 index 0000000000000000000000000000000000000000..a549bcee2058c834fbf275d838f71c313ce70998 --- /dev/null +++ b/packages/benchmark/src/longmemeval/pipeline.ts @@ -0,0 +1,446 @@ +import { + DEFAULT_EVALUATOR_CONFIG, + Evaluator, + type EvaluatorConfig, + formatMetricsReport, + resultsToJsonl, +} from "./evaluator.js"; +import { KeyExpander, type KeyExpansionConfig } from "./key-expansion.js"; +import { type LoaderConfig, loadDataset } from "./loader.js"; +import { + DEFAULT_MAPPER_CONFIG, + type EngramDocument, + type MappedInstance, + type MapperConfig, + mapInstance, +} from "./mapper.js"; +import { DEFAULT_READER_CONFIG, type LLMProvider, Reader, type ReaderConfig } from "./reader.js"; +import { + computeRetrievalMetrics, + DEFAULT_RETRIEVER_CONFIG, + type EmbeddingProvider, + type RetrievalResult, + Retriever, + type RetrieverConfig, +} from "./retriever.js"; +import { filterByTimeRange, TemporalAnalyzer, type TemporalConfig } from "./temporal.js"; +import type { BenchmarkResult, EvaluationMetrics } from "./types.js"; + +/** + * Interface for custom retrievers (e.g., EngramRetriever) + */ +export interface CustomRetriever { + indexInstance(mapped: MappedInstance): Promise; + retrieve(question: string, questionDate?: Date): Promise; + clear(): void; +} + +/** + * Debug info for retrieval analysis + */ +export interface RetrievalDebugInfo { + questionId: string; + question: string; + expectedAnswer: string; + evidenceDocIds: string[]; + evidenceDocs: Array<{ id: string; content: string; sessionId: string }>; + retrievedDocs: Array<{ id: string; content: string; score: number; isEvidence: boolean }>; + recall: number; +} + +/** + * Full pipeline configuration + */ +export interface PipelineConfig { + /** Dataset loading configuration */ + loader: LoaderConfig; + /** Mapper configuration */ + mapper?: Partial; + /** Retriever configuration */ + retriever?: Partial; + /** Reader configuration */ + reader?: Partial; + /** Evaluator configuration */ + evaluator?: Partial; + /** Key expansion configuration (Milestone 2) */ + keyExpansion?: Partial & { enabled?: boolean }; + /** Temporal analysis configuration (Milestone 2) */ + temporal?: Partial & { enabled?: boolean }; + /** Progress callback */ + onProgress?: (progress: PipelineProgress) => void; + /** Optional custom retriever (overrides default) */ + customRetriever?: CustomRetriever; + /** Debug retrieval callback - called after each retrieval with detailed info */ + onRetrievalDebug?: (debug: RetrievalDebugInfo) => void; +} + +/** + * Progress information during pipeline execution + */ +export interface PipelineProgress { + stage: "loading" | "indexing" | "retrieving" | "reading" | "evaluating"; + current: number; + total: number; + message: string; +} + +/** + * Latency metrics computed from per-query timings + */ +export interface LatencyMetrics { + /** Per-query latencies in ms (for computing percentiles) */ + perQueryLatencies: number[]; + /** 50th percentile latency in ms */ + p50: number; + /** 95th percentile latency in ms */ + p95: number; + /** 99th percentile latency in ms */ + p99: number; + /** Mean latency in ms */ + mean: number; + /** Total pipeline duration in ms */ + totalDurationMs: number; +} + +/** + * Result of running the full pipeline + */ +export interface PipelineResult { + /** All benchmark results */ + results: BenchmarkResult[]; + /** Evaluation metrics */ + metrics: EvaluationMetrics; + /** Human-readable report */ + report: string; + /** JSONL output (LongMemEval format) */ + jsonl: string; + /** Per-instance details for debugging */ + details: InstanceDetail[]; + /** Latency metrics */ + latency: LatencyMetrics; +} + +/** + * Details for a single instance (for debugging) + */ +export interface InstanceDetail { + questionId: string; + question: string; + answer: string; + hypothesis: string; + correct: boolean; + retrievedCount: number; + evidenceRetrieved: number; + retrievalRecall: number; + /** Query latency in ms (retrieval + reading time) */ + latencyMs: number; +} + +/** + * Main benchmark pipeline + */ +export class BenchmarkPipeline { + private embeddings: EmbeddingProvider; + private llm: LLMProvider; + private config: PipelineConfig; + + constructor(embeddings: EmbeddingProvider, llm: LLMProvider, config: PipelineConfig) { + this.embeddings = embeddings; + this.llm = llm; + this.config = config; + } + + /** + * Run the full benchmark pipeline + */ + async run(): Promise { + const pipelineStartTime = Date.now(); + const { onProgress } = this.config; + + // Stage 1: Load dataset + onProgress?.({ + stage: "loading", + current: 0, + total: 1, + message: "Loading dataset...", + }); + + const { instances, stats } = await loadDataset(this.config.loader); + + onProgress?.({ + stage: "loading", + current: 1, + total: 1, + message: `Loaded ${stats.totalInstances} instances`, + }); + + // Initialize components + const mapperConfig = { ...DEFAULT_MAPPER_CONFIG, ...this.config.mapper }; + const retrieverConfig = { ...DEFAULT_RETRIEVER_CONFIG, ...this.config.retriever }; + const readerConfig = { ...DEFAULT_READER_CONFIG, ...this.config.reader }; + const evaluatorConfig = { ...DEFAULT_EVALUATOR_CONFIG, ...this.config.evaluator }; + + // Use custom retriever if provided, otherwise create default + const retriever = + this.config.customRetriever ?? new Retriever(this.embeddings, retrieverConfig); + const reader = new Reader(this.llm, readerConfig); + const evaluator = new Evaluator(evaluatorConfig, this.llm); + + // Initialize optional Milestone 2 components + const keyExpander = this.config.keyExpansion?.enabled + ? new KeyExpander({ ...this.config.keyExpansion, llm: this.llm }) + : null; + const temporalAnalyzer = this.config.temporal?.enabled + ? new TemporalAnalyzer({ ...this.config.temporal, llm: this.llm }) + : null; + + // Process each instance + const results: BenchmarkResult[] = []; + const details: InstanceDetail[] = []; + const perQueryLatencies: number[] = []; + const total = instances.length; + + for (let i = 0; i < instances.length; i++) { + const instance = instances[i]; + const queryStartTime = Date.now(); + + // Stage 2: Map and index + onProgress?.({ + stage: "indexing", + current: i + 1, + total, + message: `Indexing instance ${i + 1}/${total}`, + }); + + const mapped = mapInstance(instance, mapperConfig); + + // Apply key expansion if enabled (Milestone 2) + let documentsToIndex: EngramDocument[] = mapped.documents; + if (keyExpander) { + const expanded = await keyExpander.expandBatch(mapped.documents); + documentsToIndex = expanded; + } + + await retriever.indexInstance({ ...mapped, documents: documentsToIndex }); + + // Stage 3: Retrieve + onProgress?.({ + stage: "retrieving", + current: i + 1, + total, + message: `Retrieving for ${instance.questionId}`, + }); + + // Apply temporal analysis if enabled (Milestone 2) + let queryForRetrieval = instance.question; + let temporalTimeRange: { start: Date; end: Date } | undefined; + + if (temporalAnalyzer) { + const temporalAnalysis = await temporalAnalyzer.analyze( + instance.question, + instance.questionDate, + ); + queryForRetrieval = temporalAnalysis.expandedQuery; + temporalTimeRange = temporalAnalysis.timeRange; + } + + let retrieved = await retriever.retrieve(queryForRetrieval, instance.questionDate); + + // Apply temporal filtering if we have a time range + if (temporalTimeRange && retrieved.documents.length > 0) { + const filtered = filterByTimeRange(retrieved.documents, temporalTimeRange); + // Only use filtered if we have enough results + if (filtered.length >= Math.min(3, retrieved.documents.length / 2)) { + retrieved = { + ...retrieved, + documents: filtered, + retrievedIds: filtered.map((d) => d.id), + scores: retrieved.scores.slice(0, filtered.length), + }; + } + } + + const retrievalMetrics = computeRetrievalMetrics(retrieved, mapped.evidenceDocIds); + + // Debug callback for retrieval analysis + if (this.config.onRetrievalDebug) { + const evidenceDocs = mapped.documents + .filter((d) => mapped.evidenceDocIds.includes(d.id)) + .map((d) => ({ id: d.id, content: d.content, sessionId: d.sessionId })); + + const retrievedDocs = retrieved.documents.map((d, idx) => ({ + id: d.id, + content: d.content, + score: retrieved.scores[idx] ?? 0, + isEvidence: mapped.evidenceDocIds.includes(d.id), + })); + + this.config.onRetrievalDebug({ + questionId: instance.questionId, + question: instance.question, + expectedAnswer: instance.answer, + evidenceDocIds: mapped.evidenceDocIds, + evidenceDocs, + retrievedDocs, + recall: retrievalMetrics.recall, + }); + } + + // Stage 4: Read/Generate answer + onProgress?.({ + stage: "reading", + current: i + 1, + total, + message: `Generating answer for ${instance.questionId}`, + }); + + const readResult = await reader.read( + instance.question, + retrieved.documents, + instance.questionDate, + retrieved.scores, + ); + + // Compute query latency (indexing + retrieval + reading) + const queryLatencyMs = Date.now() - queryStartTime; + perQueryLatencies.push(queryLatencyMs); + + // Store result + results.push({ + questionId: instance.questionId, + hypothesis: readResult.hypothesis, + }); + + // Store detail + details.push({ + questionId: instance.questionId, + question: instance.question, + answer: instance.answer, + hypothesis: readResult.hypothesis, + correct: false, // Will be set during evaluation + retrievedCount: retrieved.documents.length, + evidenceRetrieved: mapped.evidenceDocIds.filter((id) => retrieved.retrievedIds.includes(id)) + .length, + retrievalRecall: retrievalMetrics.recall, + latencyMs: queryLatencyMs, + }); + + // Clear index for next instance + retriever.clear(); + } + + // Stage 5: Evaluate + onProgress?.({ + stage: "evaluating", + current: 0, + total: 1, + message: "Evaluating results...", + }); + + const { evaluated, metrics } = await evaluator.evaluateAll(results, instances); + + // Update details with evaluation results + for (const evalResult of evaluated) { + const detail = details.find((d) => d.questionId === evalResult.questionId); + if (detail) { + detail.correct = evalResult.correct; + } + } + + // Add retrieval metrics + const avgRetrievalRecall = + details.reduce((sum, d) => sum + d.retrievalRecall, 0) / details.length; + metrics.retrieval = { + turnRecall: avgRetrievalRecall, + sessionRecall: avgRetrievalRecall, // Simplified for MVP + recallAtK: { 1: 0, 5: 0, 10: avgRetrievalRecall }, // Simplified for MVP + ndcgAtK: { 1: 0, 5: 0, 10: avgRetrievalRecall }, // Simplified for MVP + mrr: avgRetrievalRecall, // Simplified for MVP + }; + + onProgress?.({ + stage: "evaluating", + current: 1, + total: 1, + message: "Evaluation complete", + }); + + // Compute latency metrics + const totalDurationMs = Date.now() - pipelineStartTime; + const latency = computeLatencyMetrics(perQueryLatencies, totalDurationMs); + + return { + results, + metrics, + report: formatMetricsReport(metrics), + jsonl: resultsToJsonl(results), + details, + latency, + }; + } +} + +/** + * Compute latency percentiles from an array of latencies + */ +function computeLatencyMetrics(latencies: number[], totalDurationMs: number): LatencyMetrics { + if (latencies.length === 0) { + return { + perQueryLatencies: [], + p50: 0, + p95: 0, + p99: 0, + mean: 0, + totalDurationMs, + }; + } + + const sorted = [...latencies].sort((a, b) => a - b); + const len = sorted.length; + + // Compute percentile indices + const p50Index = Math.floor(len * 0.5); + const p95Index = Math.min(Math.floor(len * 0.95), len - 1); + const p99Index = Math.min(Math.floor(len * 0.99), len - 1); + + // Compute mean + const sum = latencies.reduce((acc, val) => acc + val, 0); + const mean = sum / len; + + return { + perQueryLatencies: latencies, + p50: sorted[p50Index], + p95: sorted[p95Index], + p99: sorted[p99Index], + mean: Math.round(mean), + totalDurationMs, + }; +} + +/** + * Quick evaluation of existing results file + */ +export async function evaluateResults( + resultsPath: string, + datasetPath: string, + llm?: LLMProvider, +): Promise<{ metrics: EvaluationMetrics; report: string }> { + const { readFile } = await import("node:fs/promises"); + + // Load results + const resultsContent = await readFile(resultsPath, "utf-8"); + const { parseJsonlResults } = await import("./evaluator.js"); + const results = parseJsonlResults(resultsContent); + + // Load dataset + const { instances } = await loadDataset({ datasetPath }); + + // Evaluate + const evaluator = new Evaluator({ useLLMEvaluation: !!llm }, llm); + const { metrics } = await evaluator.evaluateAll(results, instances); + + return { + metrics, + report: formatMetricsReport(metrics), + }; +} diff --git a/packages/benchmark/src/longmemeval/providers/anthropic-provider.ts b/packages/benchmark/src/longmemeval/providers/anthropic-provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..a36af140666d9643a614298d841769534b7c6639 --- /dev/null +++ b/packages/benchmark/src/longmemeval/providers/anthropic-provider.ts @@ -0,0 +1,321 @@ +import type { LLMOptions, LLMProvider, LLMResponse } from "../reader.js"; + +/** + * Configuration for the Anthropic LLM provider + */ +export interface AnthropicProviderConfig { + /** Anthropic API key (defaults to ANTHROPIC_API_KEY env var) */ + apiKey?: string; + /** Model to use */ + model: string; + /** Maximum tokens for response */ + maxTokens: number; +} + +const DEFAULT_CONFIG: AnthropicProviderConfig = { + model: "claude-sonnet-4-20250514", + maxTokens: 1024, +}; + +/** + * Anthropic Claude provider for LLM operations + * + * Used for: + * - Answer generation (reading stage) + * - LLM-based evaluation (QA correctness) + * - Fact extraction (key expansion) + */ +export class AnthropicProvider implements LLMProvider { + private config: AnthropicProviderConfig; + private client: AnthropicClient | null = null; + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + } + + /** + * Initialize the Anthropic client (lazy loading) + */ + private async getClient(): Promise { + if (this.client) { + return this.client; + } + + const apiKey = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY; + + if (!apiKey) { + throw new Error( + "Anthropic API key required. Set ANTHROPIC_API_KEY environment variable or pass apiKey in config.", + ); + } + + try { + // Try to import the Anthropic SDK + const { default: Anthropic } = await import("@anthropic-ai/sdk"); + this.client = new Anthropic({ apiKey }) as unknown as AnthropicClient; + } catch { + throw new Error("@anthropic-ai/sdk not installed. Run: npm install @anthropic-ai/sdk"); + } + + return this.client; + } + + /** + * Generate a completion + */ + async complete(prompt: string, options?: LLMOptions): Promise { + const client = await this.getClient(); + + const response = await client.messages.create({ + model: this.config.model, + max_tokens: options?.maxTokens ?? this.config.maxTokens, + messages: [{ role: "user", content: prompt }], + }); + + // Extract text from response + const textContent = response.content.find((block: { type: string }) => block.type === "text") as + | { text: string } + | undefined; + + return { + text: textContent?.text ?? "", + usage: { + inputTokens: response.usage.input_tokens, + outputTokens: response.usage.output_tokens, + }, + }; + } +} + +/** + * Interface for Anthropic client (to avoid importing types) + */ +interface AnthropicClient { + messages: { + create(params: { + model: string; + max_tokens: number; + messages: Array<{ role: string; content: string }>; + }): Promise<{ + content: Array<{ type: string; text?: string }>; + usage: { input_tokens: number; output_tokens: number }; + }>; + }; +} + +/** + * OpenAI-compatible provider for LLM operations + * + * Works with OpenAI API or compatible endpoints (e.g., Ollama, vLLM) + */ +export class OpenAICompatibleProvider implements LLMProvider { + private baseUrl: string; + private apiKey: string; + private model: string; + + constructor( + config: { + baseUrl?: string; + apiKey?: string; + model?: string; + } = {}, + ) { + this.baseUrl = config.baseUrl ?? "https://api.openai.com/v1"; + this.apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? ""; + this.model = config.model ?? "gpt-5-mini"; + } + + async complete(prompt: string, options?: LLMOptions): Promise { + // GPT-5+ models use max_completion_tokens instead of max_tokens, and don't support temperature + const isGpt5Plus = this.model.startsWith("gpt-5") || this.model.startsWith("gpt-5."); + const maxTokensParam = isGpt5Plus ? "max_completion_tokens" : "max_tokens"; + + const requestBody: Record = { + model: this.model, + messages: [{ role: "user", content: prompt }], + [maxTokensParam]: options?.maxTokens ?? 4096, + }; + + // GPT-5 mini doesn't support temperature parameter + if (!isGpt5Plus) { + requestBody.temperature = options?.temperature ?? 0.1; + } + + const response = await fetch(`${this.baseUrl}/chat/completions`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify(requestBody), + }); + + if (!response.ok) { + const errorBody = await response.text(); + throw new Error(`OpenAI API error: ${response.status} ${response.statusText} - ${errorBody}`); + } + + const data = (await response.json()) as OpenAIResponse; + + return { + text: data.choices[0]?.message?.content ?? "", + usage: data.usage + ? { + inputTokens: data.usage.prompt_tokens, + outputTokens: data.usage.completion_tokens, + } + : undefined, + }; + } +} + +interface OpenAIResponse { + choices: Array<{ message?: { content?: string } }>; + usage?: { prompt_tokens: number; completion_tokens: number }; +} + +/** + * Ollama provider for local LLM operations + */ +export class OllamaProvider implements LLMProvider { + private baseUrl: string; + private model: string; + + constructor(config: { baseUrl?: string; model: string }) { + this.baseUrl = config.baseUrl ?? "http://localhost:11434"; + this.model = config.model; + } + + async complete(prompt: string, options?: LLMOptions): Promise { + const response = await fetch(`${this.baseUrl}/api/generate`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + model: this.model, + prompt, + stream: false, + options: { + temperature: options?.temperature ?? 0.1, + num_predict: options?.maxTokens ?? 1024, + }, + }), + }); + + if (!response.ok) { + throw new Error(`Ollama API error: ${response.status} ${response.statusText}`); + } + + const data = (await response.json()) as OllamaResponse; + + return { + text: data.response ?? "", + usage: { + inputTokens: data.prompt_eval_count ?? 0, + outputTokens: data.eval_count ?? 0, + }, + }; + } +} + +interface OllamaResponse { + response?: string; + prompt_eval_count?: number; + eval_count?: number; +} + +/** + * Google Gemini provider for LLM operations + * + * Uses the @google/genai SDK (recommended as of 2025) + * Supports Gemini 2.5 Flash and other Gemini models + */ +export class GeminiProvider implements LLMProvider { + private model: string; + private apiKey: string; + private client: GoogleGenAIClient | null = null; + + constructor( + config: { + apiKey?: string; + model?: string; + } = {}, + ) { + this.apiKey = config.apiKey ?? process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? ""; + this.model = config.model ?? "gemini-3-flash-preview"; + } + + /** + * Initialize the Gemini client (lazy loading) + */ + private async getClient(): Promise { + if (this.client) { + return this.client; + } + + if (!this.apiKey) { + throw new Error( + "Gemini API key required. Set GOOGLE_GENERATIVE_AI_API_KEY environment variable.", + ); + } + + try { + // Dynamic import to handle optional dependency + // eslint-disable-next-line @typescript-eslint/no-require-imports + const genaiModule = await import("@google/genai" as string); + const GoogleGenAI = genaiModule.GoogleGenAI; + this.client = new GoogleGenAI({ apiKey: this.apiKey }) as unknown as GoogleGenAIClient; + } catch { + throw new Error("@google/genai not installed. Run: npm install @google/genai"); + } + + return this.client; + } + + async complete(prompt: string, options?: LLMOptions): Promise { + const client = await this.getClient(); + + const response = await client.models.generateContent({ + model: this.model, + contents: prompt, + config: { + maxOutputTokens: options?.maxTokens ?? 4096, + temperature: options?.temperature ?? 0.1, + }, + }); + + return { + text: response.text ?? "", + usage: response.usageMetadata + ? { + inputTokens: response.usageMetadata.promptTokenCount ?? 0, + outputTokens: response.usageMetadata.candidatesTokenCount ?? 0, + } + : undefined, + }; + } +} + +/** + * Interface for GoogleGenAI client (to avoid importing types) + */ +interface GoogleGenAIClient { + models: { + generateContent(params: { + model: string; + contents: string; + config?: { + maxOutputTokens?: number; + temperature?: number; + topP?: number; + topK?: number; + }; + }): Promise<{ + text?: string; + usageMetadata?: { + promptTokenCount?: number; + candidatesTokenCount?: number; + totalTokenCount?: number; + }; + }>; + }; +} diff --git a/packages/benchmark/src/longmemeval/providers/engram-provider.ts b/packages/benchmark/src/longmemeval/providers/engram-provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ea3fd57d163132e6a5617d7fb5fd70a5ee8348a --- /dev/null +++ b/packages/benchmark/src/longmemeval/providers/engram-provider.ts @@ -0,0 +1,1274 @@ +import type { EngramDocument, MappedInstance } from "../mapper.js"; +import type { EmbeddingProvider, RetrievalResult } from "../retriever.js"; + +/** + * Embedding model options for configurable embeddings. + */ +export type EmbeddingModelOption = + | "e5-small" + | "e5-base" + | "e5-large" + | "gte-base" + | "gte-large" + | "bge-small" + | "bge-base" + | "bge-large"; + +/** + * Configuration for the Engram provider + */ +export interface EngramProviderConfig { + /** Qdrant server URL */ + qdrantUrl: string; + /** Collection name for benchmark data */ + collectionName: string; + /** Enable hybrid search (dense + sparse with RRF) */ + hybridSearch: boolean; + /** Use learned fusion weights instead of fixed RRF */ + learnedFusion: boolean; + /** Path to fusion MLP ONNX model */ + fusionModel: string; + /** Enable reranking */ + rerank: boolean; + /** Reranker tier: fast, accurate, code, colbert, or llm */ + rerankTier: "fast" | "accurate" | "code" | "colbert" | "llm"; + /** Number of candidates to fetch before reranking */ + rerankDepth: number; + /** Number of documents to return */ + topK: number; + /** Enable multi-query expansion with RRF fusion */ + multiQuery: boolean; + /** Number of query variations to generate */ + multiQueryVariations: number; + /** Enable retrieval confidence abstention detection */ + abstention: boolean; + /** Minimum retrieval score to proceed (0-1) */ + abstentionThreshold: number; + /** Enable session-aware hierarchical retrieval */ + sessionAware: boolean; + /** Number of sessions to retrieve in stage 1 */ + topSessions: number; + /** Number of turns per session in stage 2 */ + turnsPerSession: number; + /** Enable temporal query parsing */ + temporalAware: boolean; + /** Minimum confidence to apply temporal filter (0-1) */ + temporalConfidenceThreshold: number; + /** Embedding model to use */ + embeddingModel: EmbeddingModelOption; + /** Reference date for temporal queries (defaults to question date) */ + referenceDate?: Date; +} + +const DEFAULT_CONFIG: EngramProviderConfig = { + qdrantUrl: "http://localhost:6333", + collectionName: "longmemeval_engram", + hybridSearch: true, + learnedFusion: false, + fusionModel: "models/fusion_mlp.onnx", + rerank: true, + rerankTier: "fast", + rerankDepth: 30, + topK: 10, + multiQuery: false, + multiQueryVariations: 3, + abstention: false, + abstentionThreshold: 0.3, + sessionAware: false, + topSessions: 5, + turnsPerSession: 3, + temporalAware: false, + temporalConfidenceThreshold: 0.5, + embeddingModel: "e5-small", +}; + +/** + * Full Engram retrieval pipeline using search-core + * + * Features: + * - Dense embeddings (E5-small, 384d) + * - Sparse embeddings (SPLADE) + * - Hybrid search with RRF fusion + * - ColBERT late interaction reranking + * - Cross-encoder reranking (fast/accurate/code tiers) + */ +export class EngramRetriever { + private config: EngramProviderConfig; + private textEmbedder: TextEmbedderInterface | null = null; + private spladeEmbedder: SpladeEmbedderInterface | null = null; + private colbertEmbedder: ColBERTEmbedderInterface | null = null; + private reranker: RerankerInterface | null = null; + private colbertReranker: ColBERTRerankerInterface | null = null; + private client: QdrantClientInterface | null = null; + private indexed: boolean = false; + private documentEmbeddings: Map = new Map(); // ColBERT embeddings cache + private xaiClient: XAIClientInterface | null = null; // For multi-query expansion + private abstentionDetector: AbstentionDetectorInterface | null = null; + private sessionSummarizer: SessionSummarizerInterface | null = null; + private sessionRetriever: SessionRetrieverInterface | null = null; + private llmProvider: LLMProviderInterface | null = null; + private temporalParser: TemporalParserInterface | null = null; + private learnedFusion: LearnedFusionInterface | null = null; + private embeddingDimensions: number = 384; // Default for e5-small + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + } + + /** + * Initialize all embedders and rerankers (lazy loading) + */ + private async initialize(): Promise { + if (this.textEmbedder) return; + + try { + // Import search-core components + const searchCore = await import("@engram/search"); + + // Initialize embedders with configurable model + if (this.config.embeddingModel === "e5-small") { + // Use legacy TextEmbedder for backwards compatibility + this.textEmbedder = new searchCore.TextEmbedder() as unknown as TextEmbedderInterface; + this.embeddingDimensions = 384; + } else { + // Use configurable embedder for other models + const embedder = searchCore.createEmbedder({ + model: this.config.embeddingModel, + sparse: this.config.hybridSearch, + }); + this.textEmbedder = embedder as unknown as TextEmbedderInterface; + this.embeddingDimensions = embedder.dimensions; + console.log(`Using ${this.config.embeddingModel} embedder (${this.embeddingDimensions}d)`); + } + + // Initialize temporal parser + if (this.config.temporalAware) { + this.temporalParser = new searchCore.TemporalQueryParser( + this.config.referenceDate, + ) as unknown as TemporalParserInterface; + } + + if (this.config.hybridSearch) { + this.spladeEmbedder = new searchCore.SpladeEmbedder() as unknown as SpladeEmbedderInterface; + } + + // Initialize learned fusion if enabled + if (this.config.learnedFusion) { + this.learnedFusion = new searchCore.LearnedFusion({ + modelPath: this.config.fusionModel, + }) as unknown as LearnedFusionInterface; + console.log(` [Learned Fusion] Using model: ${this.config.fusionModel}`); + } + + if (this.config.rerank && this.config.rerankTier === "colbert") { + const colbertEmb = new searchCore.ColBERTEmbedder(); + this.colbertEmbedder = colbertEmb as unknown as ColBERTEmbedderInterface; + this.colbertReranker = new searchCore.ColBERTReranker( + colbertEmb, + ) as unknown as ColBERTRerankerInterface; + } + + if (this.config.rerank && this.config.rerankTier !== "colbert") { + // Use BatchedReranker for cross-encoder tiers + this.reranker = searchCore.BatchedReranker.forTier( + this.config.rerankTier, + ) as unknown as RerankerInterface; + } + + // Initialize Qdrant client + const { QdrantClient } = await import("@qdrant/js-client-rest"); + this.client = new QdrantClient({ url: this.config.qdrantUrl }) as QdrantClientInterface; + + // Initialize Google AI client for multi-query expansion + if (this.config.multiQuery) { + const { createGoogleGenerativeAI } = await import("@ai-sdk/google"); + const { generateText } = await import("ai"); + const googleProvider = createGoogleGenerativeAI(); + this.xaiClient = { + chat: async (messages: Array<{ role: string; content: string }>) => { + const result = await generateText({ + model: googleProvider("gemini-3-flash-preview"), + system: messages.find((m) => m.role === "system")?.content, + prompt: messages.find((m) => m.role === "user")?.content ?? "", + }); + return result.text; + }, + }; + } + + // Initialize abstention detector + if (this.config.abstention) { + const { AbstentionDetector } = await import("@engram/search"); + this.abstentionDetector = new AbstentionDetector({ + minRetrievalScore: this.config.abstentionThreshold, + }) as unknown as AbstentionDetectorInterface; + } + + // Initialize session-aware components + if (this.config.sessionAware) { + // Create a simple LLM provider for summarization + const { SessionSummarizer, SessionAwareRetriever } = await import("@engram/search"); + const { createGoogleGenerativeAI } = await import("@ai-sdk/google"); + const { generateText } = await import("ai"); + + // Use Google AI via AI SDK as LLM provider for summarization + const googleProvider = createGoogleGenerativeAI(); + + this.llmProvider = { + complete: async (prompt: string) => { + const result = await generateText({ + model: googleProvider("gemini-3-flash-preview"), + prompt, + }); + return { text: result.text }; + }, + }; + + this.sessionSummarizer = new SessionSummarizer( + this.llmProvider, + ) as unknown as SessionSummarizerInterface; + + // Session retriever will be initialized after collection setup + // Cast client to the expected type for SessionAwareRetriever + const sessionRetrieverInstance = new SessionAwareRetriever( + this.client as never, + { + topSessions: this.config.topSessions, + turnsPerSession: this.config.turnsPerSession, + finalTopK: this.config.topK, + sessionCollection: `${this.config.collectionName}_sessions`, + turnCollection: this.config.collectionName, + }, + this.reranker as never, + ); + this.sessionRetriever = sessionRetrieverInstance as unknown as SessionRetrieverInterface; + + console.log(" [Session-Aware] Initialized session summarizer and retriever"); + } + } catch (error) { + console.error("Failed to initialize Engram provider:", error); + throw new Error("@engram/search not available. Install it or use a different provider."); + } + } + + /** + * Ensure collection exists with proper multi-vector schema + */ + async ensureCollection(): Promise { + await this.initialize(); + if (!this.client) throw new Error("Client not initialized"); + + try { + await this.client.getCollection(this.config.collectionName); + // Collection exists, delete it to start fresh for each benchmark instance + await this.client.deleteCollection(this.config.collectionName); + } catch { + // Collection doesn't exist, that's fine + } + + // Create collection with multi-vector support + const vectorsConfig: Record = { + dense: { + size: 384, + distance: "Cosine", + }, + }; + + const sparseVectorsConfig: Record = {}; + if (this.config.hybridSearch) { + sparseVectorsConfig.sparse = { + index: { + on_disk: false, + }, + }; + } + + await this.client.createCollection(this.config.collectionName, { + vectors: vectorsConfig, + sparse_vectors: Object.keys(sparseVectorsConfig).length > 0 ? sparseVectorsConfig : undefined, + }); + + // Create sessions collection for session-aware retrieval + if (this.config.sessionAware) { + const sessionsCollection = `${this.config.collectionName}_sessions`; + try { + await this.client.getCollection(sessionsCollection); + await this.client.deleteCollection(sessionsCollection); + } catch { + // Collection doesn't exist, that's fine + } + + // Sessions collection uses text_dense vector for summary embeddings + await this.client.createCollection(sessionsCollection, { + vectors: { + text_dense: { + size: 384, + distance: "Cosine", + }, + }, + }); + console.log(` [Session-Aware] Created sessions collection: ${sessionsCollection}`); + } + } + + /** + * Index a mapped instance for retrieval (Retriever interface) + */ + async indexInstance(mapped: MappedInstance): Promise { + await this.index(mapped.documents); + } + + /** + * Retrieve relevant documents for a question (Retriever interface) + * Uses session-aware retrieval, multi-query expansion, or standard search. + */ + async retrieve(question: string, _questionDate?: Date): Promise { + // Session-aware two-stage retrieval + if (this.config.sessionAware && this.sessionRetriever) { + return this.sessionAwareSearch(question); + } + // Multi-query expansion with RRF fusion + if (this.config.multiQuery && this.xaiClient) { + return this.multiQuerySearch(question, this.config.topK); + } + return this.search(question, this.config.topK); + } + + /** + * Session-aware two-stage retrieval. + * Stage 1: Retrieve relevant sessions + * Stage 2: Retrieve turns within each session + */ + private async sessionAwareSearch(query: string): Promise { + if (!this.sessionRetriever) { + return this.search(query, this.config.topK); + } + + try { + const results = await this.sessionRetriever.retrieve(query); + + // Convert SessionAwareSearchResult to EngramDocument + const documents: EngramDocument[] = results.map((r) => { + const payload = r.payload; + return { + id: payload?.node_id ?? String(r.id), + instanceId: payload?.session_id ?? "", + sessionId: r.sessionId, + content: payload?.content ?? "", + validTime: new Date(payload?.timestamp ?? Date.now()), + metadata: { + questionId: payload?.session_id ?? "", + hasAnswer: false, + role: "combined" as const, + turnIndex: undefined, + sessionIndex: 0, + }, + }; + }); + + return { + documents, + scores: results.map((r) => r.score), + retrievedIds: documents.map((d) => d.id), + }; + } catch (error) { + console.warn("[Session-Aware] Retrieval failed, falling back to standard search:", error); + return this.search(query, this.config.topK); + } + } + + /** + * Multi-query search: expand query into variations and fuse results with RRF. + * Based on DMQR-RAG: Diverse Multi-Query Rewriting for RAG. + * @see https://arxiv.org/abs/2411.13154 + */ + private async multiQuerySearch(query: string, topK: number): Promise { + await this.initialize(); + + try { + // Step 1: Expand query into variations + const variations = await this.expandQuery(query); + console.log(` [Multi-Query] Generated ${variations.length} query variations`); + + // Step 2: Search with each variation in parallel + const perQueryLimit = Math.max(topK * 2, 20); + const allResults = await Promise.all( + variations.map((varQuery) => this.search(varQuery, perQueryLimit)), + ); + + // Step 3: Fuse results using RRF + const fused = this.rrfFusionResults(allResults, topK); + + console.log( + ` [Multi-Query] Fused ${allResults.reduce((sum, r) => sum + r.documents.length, 0)} candidates into ${fused.documents.length} results`, + ); + + return fused; + } catch (error) { + console.warn("[Multi-Query] Expansion failed, falling back to single query:", error); + return this.search(query, topK); + } + } + + /** + * Expand a query into multiple variations using LLM. + */ + private async expandQuery(query: string): Promise { + const variations: string[] = [query]; // Always include original + + if (!this.xaiClient) { + return variations; + } + + const systemPrompt = `You are a search query expansion expert. Given a user query, generate alternative search queries that will help retrieve relevant documents. + +Rules: +- Generate queries that are semantically different but target the same information need +- Each query should emphasize different aspects or use different vocabulary +- Return ONLY a JSON array of query strings +- Example: ["query 1", "query 2", "query 3"] +- Do not include numbering, bullets, or markdown formatting`; + + const userPrompt = `Generate ${this.config.multiQueryVariations} alternative search queries for: +"${query}" + +Use these strategies: +- Paraphrase: Rephrase the query using different words and synonyms +- Keyword: Focus on key entities, names, and technical terms +- Step-back: Generalize to a broader concept or category + +Return ONLY a JSON array of query strings. No explanations.`; + + try { + const response = await this.xaiClient.chat([ + { role: "system", content: systemPrompt }, + { role: "user", content: userPrompt }, + ]); + + // Parse JSON array from response + const jsonMatch = response.match(/\[[\s\S]*\]/); + if (jsonMatch) { + const parsed = JSON.parse(jsonMatch[0]) as string[]; + const validVariations = parsed + .filter((v) => typeof v === "string" && v.trim().length > 0 && v !== query) + .slice(0, this.config.multiQueryVariations); + variations.push(...validVariations); + } + } catch (error) { + console.warn("[Multi-Query] Query expansion parsing failed:", error); + } + + return variations; + } + + /** + * Fuse multiple RetrievalResults using Reciprocal Rank Fusion (RRF). + * RRF score = sum(1 / (k + rank_i)) across all result sets. + */ + private rrfFusionResults(resultSets: RetrievalResult[], topK: number): RetrievalResult { + const k = 60; // RRF constant + const scoreMap = new Map(); + + for (const results of resultSets) { + for (let rank = 0; rank < results.documents.length; rank++) { + const doc = results.documents[rank]; + const rrfScore = 1 / (k + rank + 1); + + const existing = scoreMap.get(doc.id); + if (existing) { + existing.rrfScore += rrfScore; + } else { + scoreMap.set(doc.id, { document: doc, rrfScore }); + } + } + } + + // Sort by RRF score and return top K + const sorted = Array.from(scoreMap.values()) + .sort((a, b) => b.rrfScore - a.rrfScore) + .slice(0, topK); + + return { + documents: sorted.map((s) => s.document), + scores: sorted.map((s) => s.rrfScore), + retrievedIds: sorted.map((s) => s.document.id), + }; + } + + /** + * Index documents with dense, sparse, and optionally ColBERT embeddings + */ + async index(documents: EngramDocument[]): Promise { + await this.initialize(); + if (!this.client || !this.textEmbedder) throw new Error("Not initialized"); + + await this.ensureCollection(); + + // Generate dense embeddings + const texts = documents.map((d) => d.content); + const denseEmbeddings = await Promise.all( + texts.map((text) => this.textEmbedder?.embed(text) ?? Promise.resolve(new Float32Array(384))), + ); + + // Generate sparse embeddings if hybrid search enabled + let sparseEmbeddings: SparseVector[] | null = null; + if (this.config.hybridSearch && this.spladeEmbedder) { + sparseEmbeddings = await Promise.all( + texts.map( + (text) => + this.spladeEmbedder?.embed(text) ?? Promise.resolve({ indices: [], values: [] }), + ), + ); + } + + // Generate ColBERT embeddings if using ColBERT reranking + if (this.config.rerank && this.config.rerankTier === "colbert" && this.colbertEmbedder) { + for (const doc of documents) { + const colbertEmb = await this.colbertEmbedder.encodeDocument(doc.content); + this.documentEmbeddings.set(doc.id, colbertEmb); + } + } + + // Prepare points for Qdrant + const points = documents.map((doc, i) => { + const embedding = denseEmbeddings[i] ?? new Float32Array(384); + const point: QdrantPoint = { + id: this.hashId(doc.id), + vector: { + dense: Array.from(embedding), + }, + payload: { + doc_id: doc.id, + instance_id: doc.instanceId, + session_id: doc.sessionId, + content: doc.content, + valid_time: doc.validTime.toISOString(), + has_answer: doc.metadata.hasAnswer, + role: doc.metadata.role, + turn_index: doc.metadata.turnIndex, + session_index: doc.metadata.sessionIndex, + }, + }; + + // Add sparse vector if available + if (sparseEmbeddings?.[i]) { + point.vector.sparse = sparseEmbeddings[i]; + } + + return point; + }); + + // Batch upsert with retry logic + const batchSize = 50; // Smaller batches to reduce memory pressure + for (let i = 0; i < points.length; i += batchSize) { + const batch = points.slice(i, i + batchSize); + if (!this.client) throw new Error("Client not initialized"); + const client = this.client; + await this.retryOperation(() => + client.upsert(this.config.collectionName, { + wait: true, + points: batch, + }), + ); + } + + // Index session summaries if session-aware is enabled + if (this.config.sessionAware && this.sessionSummarizer) { + await this.indexSessionSummaries(documents); + } + + this.indexed = true; + } + + /** + * Group documents by session and index session summaries + */ + private async indexSessionSummaries(documents: EngramDocument[]): Promise { + if (!this.client || !this.sessionSummarizer) return; + + // Group documents by session + const sessionGroups = this.groupBySession(documents); + const sessionIds = Object.keys(sessionGroups); + + console.log(` [Session-Aware] Generating summaries for ${sessionIds.length} sessions...`); + + // Generate summaries for each session + const summaries = await Promise.all( + sessionIds.map(async (sessionId) => { + const docs = sessionGroups[sessionId]; + // Convert EngramDocument to Turn format for SessionSummarizer + const turns = docs.map((doc) => ({ + id: doc.id, + sessionId: doc.sessionId, + role: doc.metadata.role as "user" | "assistant" | "system", + content: doc.content, + timestamp: doc.validTime, + })); + + try { + return await this.sessionSummarizer?.summarize(turns); + } catch (error) { + console.warn(` [Session-Aware] Failed to summarize session ${sessionId}:`, error); + return null; + } + }), + ); + + // Filter out failed summaries (type guard to narrow type) + const validSummaries = summaries.filter((s): s is NonNullable => s !== null); + console.log(` [Session-Aware] Generated ${validSummaries.length} session summaries`); + + // Index summaries in sessions collection + const sessionsCollection = `${this.config.collectionName}_sessions`; + const sessionPoints = validSummaries.map((summary) => ({ + id: this.hashId(summary.sessionId), + vector: { + text_dense: summary.embedding, + }, + payload: { + session_id: summary.sessionId, + summary: summary.summary, + topics: summary.topics, + entities: summary.entities, + start_time: summary.startTime.toISOString(), + end_time: summary.endTime.toISOString(), + turn_count: summary.turnCount, + }, + })); + + // Batch upsert sessions + const client = this.client; + for (let i = 0; i < sessionPoints.length; i += 50) { + const batch = sessionPoints.slice(i, i + 50); + await this.retryOperation(() => + client.upsert(sessionsCollection, { + wait: true, + points: batch, + }), + ); + } + + console.log(` [Session-Aware] Indexed ${sessionPoints.length} session summaries`); + } + + /** + * Group documents by session ID + */ + private groupBySession(docs: EngramDocument[]): Record { + const groups: Record = {}; + for (const doc of docs) { + if (!groups[doc.sessionId]) { + groups[doc.sessionId] = []; + } + groups[doc.sessionId].push(doc); + } + // Sort each group by validTime + for (const sessionId of Object.keys(groups)) { + groups[sessionId].sort((a, b) => a.validTime.getTime() - b.validTime.getTime()); + } + return groups; + } + + /** + * Retry an operation with exponential backoff + */ + private async retryOperation( + operation: () => Promise, + maxRetries = 3, + baseDelayMs = 100, + ): Promise { + let lastError: Error | undefined; + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + return await operation(); + } catch (error) { + lastError = error as Error; + if (attempt < maxRetries - 1) { + const delay = baseDelayMs * 2 ** attempt; + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + } + throw lastError; + } + + /** + * Search with full Engram pipeline: hybrid retrieval + reranking + */ + async search(query: string, topK: number): Promise { + if (!this.indexed || !this.client || !this.textEmbedder) { + return { documents: [], scores: [], retrievedIds: [] }; + } + + try { + // Step 0: Parse temporal expressions if enabled + let semanticQuery = query; + let temporalFilter: TemporalFilterType | null = null; + + if (this.temporalParser) { + const parsed = this.temporalParser.parse(query); + if (parsed.temporalFilter && parsed.confidence >= this.config.temporalConfidenceThreshold) { + semanticQuery = parsed.semanticQuery; + temporalFilter = parsed.temporalFilter; + console.log( + ` [Temporal] "${parsed.temporalFilter.expression}" → ` + + `${parsed.temporalFilter.after?.toISOString().split("T")[0] ?? "∞"} to ` + + `${parsed.temporalFilter.before?.toISOString().split("T")[0] ?? "∞"} ` + + `(conf: ${parsed.confidence.toFixed(2)})`, + ); + } + } + + // Step 1: Generate query embeddings (use semantic query without temporal) + const denseQuery = await this.textEmbedder.embedQuery(semanticQuery); + let sparseQuery: SparseVector | null = null; + if (this.config.hybridSearch && this.spladeEmbedder) { + try { + sparseQuery = await this.spladeEmbedder.embedQuery(semanticQuery); + } catch (error) { + // Fall back to dense-only if SPLADE fails + console.warn("SPLADE embedding failed, using dense-only:", error); + } + } + + // Step 2: Retrieve candidates (fetch more for reranking) + const fetchLimit = this.config.rerank ? this.config.rerankDepth : topK; + let results: QdrantSearchResult[]; + + if (this.config.hybridSearch && sparseQuery) { + if (this.config.learnedFusion && this.learnedFusion) { + // Learned fusion: fetch dense and sparse separately, then fuse with predicted weights + results = await this.learnedFusionSearch( + query, + denseQuery, + sparseQuery, + fetchLimit, + temporalFilter, + ); + } else { + // Standard hybrid search with fixed RRF fusion + results = await this.hybridSearch(denseQuery, sparseQuery, fetchLimit, temporalFilter); + } + } else { + // Dense-only search + results = await this.denseSearch(denseQuery, fetchLimit, temporalFilter); + } + + // Step 3: Rerank if enabled + if (this.config.rerank && results.length > 0) { + try { + results = await this.rerank(query, results, topK); + } catch (error) { + // Fall back to retrieval results if reranking fails + console.warn("Reranking failed, using retrieval scores:", error); + results = results.slice(0, topK); + } + } else { + results = results.slice(0, topK); + } + + // Step 4: Convert to EngramDocuments + const documents: EngramDocument[] = results.map((r) => { + const payload = r.payload as Record; + return { + id: payload.doc_id as string, + instanceId: payload.instance_id as string, + sessionId: payload.session_id as string, + content: payload.content as string, + validTime: new Date(payload.valid_time as string), + metadata: { + questionId: payload.instance_id as string, + hasAnswer: payload.has_answer as boolean, + role: payload.role as "user" | "assistant" | "combined", + turnIndex: payload.turn_index as number | undefined, + sessionIndex: payload.session_index as number, + }, + }; + }); + + const retrievalResult: RetrievalResult = { + documents, + scores: results.map((r) => r.score), + retrievedIds: documents.map((d) => d.id), + }; + + // Apply abstention detection if enabled + if (this.abstentionDetector && results.length > 0) { + const abstentionResult = this.abstentionDetector.checkRetrievalConfidence(results); + retrievalResult.abstained = abstentionResult.shouldAbstain; + retrievalResult.abstentionReason = abstentionResult.reason; + retrievalResult.retrievalConfidence = abstentionResult.confidence; + + if (abstentionResult.shouldAbstain) { + console.log(` [Abstention] ${abstentionResult.reason}: ${abstentionResult.details}`); + } + } + + return retrievalResult; + } catch (error) { + console.error("Search failed:", error); + return { documents: [], scores: [], retrievedIds: [] }; + } + } + + /** + * Dense-only vector search with retry and optional temporal filter + */ + private async denseSearch( + queryVector: number[] | Float32Array, + limit: number, + temporalFilter?: TemporalFilterType | null, + ): Promise { + if (!this.client) return []; + + const client = this.client; + const qdrantFilter = temporalFilter ? this.buildQdrantFilter(temporalFilter) : undefined; + + return this.retryOperation(async () => { + const results = await client.search(this.config.collectionName, { + vector: { name: "dense", vector: Array.from(queryVector) }, + limit, + with_payload: true, + filter: qdrantFilter, + }); + return results ?? []; + }); + } + + /** + * Build Qdrant filter from temporal constraints + */ + private buildQdrantFilter(filter: TemporalFilterType): Record { + const conditions: Array<{ key: string; range: { gte?: string; lte?: string } }> = []; + + if (filter.after) { + conditions.push({ + key: "valid_time", + range: { gte: filter.after.toISOString() }, + }); + } + + if (filter.before) { + conditions.push({ + key: "valid_time", + range: { lte: filter.before.toISOString() }, + }); + } + + return { must: conditions }; + } + + /** + * Hybrid search with RRF fusion (dense + sparse) and optional temporal filter + */ + private async hybridSearch( + denseQuery: number[] | Float32Array, + sparseQuery: SparseVector, + limit: number, + temporalFilter?: TemporalFilterType | null, + ): Promise { + if (!this.client) return []; + + const qdrantFilter = temporalFilter ? this.buildQdrantFilter(temporalFilter) : undefined; + + // Use Qdrant's native query API with prefetch for RRF + try { + const results = await this.client.query(this.config.collectionName, { + prefetch: [ + { + query: Array.from(denseQuery), + using: "dense", + limit: limit * 2, + filter: qdrantFilter, + }, + { + query: { + indices: sparseQuery.indices, + values: sparseQuery.values, + }, + using: "sparse", + limit: limit * 2, + filter: qdrantFilter, + }, + ], + query: { fusion: "rrf" }, + limit, + with_payload: true, + }); + + return results.points || []; + } catch { + // Fall back to dense-only if hybrid fails + console.warn("Hybrid search failed, falling back to dense-only"); + return this.denseSearch(denseQuery, limit, temporalFilter); + } + } + + /** + * Learned fusion search: fetch dense and sparse separately, then use MLP-predicted weights + */ + private async learnedFusionSearch( + query: string, + denseQuery: number[] | Float32Array, + sparseQuery: SparseVector, + limit: number, + temporalFilter?: TemporalFilterType | null, + ): Promise { + if (!this.client || !this.learnedFusion) { + return this.hybridSearch(denseQuery, sparseQuery, limit, temporalFilter); + } + + try { + // Fetch dense and sparse results separately + const denseResults = await this.denseSearch(denseQuery, limit * 2, temporalFilter); + const sparseResults = await this.sparseSearch(sparseQuery, limit * 2, temporalFilter); + + // Convert to SearchResult format for LearnedFusion + const denseSearchResults = denseResults.map((r) => { + const payload = r.payload as Record; + return { + id: payload.doc_id as string, + content: payload.content as string, + score: r.score, + }; + }); + + const sparseSearchResults = sparseResults.map((r) => { + const payload = r.payload as Record; + return { + id: payload.doc_id as string, + content: payload.content as string, + score: r.score, + }; + }); + + // Use learned fusion to combine results + const fusedResults = await this.learnedFusion.fuse( + query, + denseSearchResults, + sparseSearchResults, + ); + + // Map back to QdrantSearchResult format + const resultMap = new Map(); + for (const r of denseResults) { + const payload = r.payload as Record; + resultMap.set(payload.doc_id as string, r); + } + for (const r of sparseResults) { + const payload = r.payload as Record; + if (!resultMap.has(payload.doc_id as string)) { + resultMap.set(payload.doc_id as string, r); + } + } + + return fusedResults.slice(0, limit).map((f) => { + const original = resultMap.get(f.id); + if (!original) throw new Error(`Missing result for ${f.id}`); + return { ...original, score: f.score }; + }); + } catch (error) { + console.warn("Learned fusion failed, falling back to RRF:", error); + return this.hybridSearch(denseQuery, sparseQuery, limit, temporalFilter); + } + } + + /** + * Sparse-only search + */ + private async sparseSearch( + sparseQuery: SparseVector, + limit: number, + temporalFilter?: TemporalFilterType | null, + ): Promise { + if (!this.client) return []; + + const qdrantFilter = temporalFilter ? this.buildQdrantFilter(temporalFilter) : undefined; + + try { + const results = await this.client.query(this.config.collectionName, { + query: { + indices: sparseQuery.indices, + values: sparseQuery.values, + }, + using: "sparse", + limit, + with_payload: true, + filter: qdrantFilter, + }); + return results.points || []; + } catch { + return []; + } + } + + /** + * Rerank results using configured reranker + */ + private async rerank( + query: string, + results: QdrantSearchResult[], + topK: number, + ): Promise { + if (results.length === 0) return results; + + try { + if (this.config.rerankTier === "colbert" && this.colbertReranker) { + // ColBERT late interaction reranking + const candidates = results.map((r) => { + const payload = r.payload as Record; + const docId = payload.doc_id as string; + return { + id: docId, + content: payload.content as string, + score: r.score, + colbertEmbeddings: this.documentEmbeddings.get(docId), + }; + }); + + const reranked = await this.colbertReranker.rerank(query, candidates, topK); + + // Map back to QdrantSearchResult format + return reranked.map((item) => { + const original = results.find( + (r) => (r.payload as Record).doc_id === item.id, + ); + if (!original) throw new Error(`Original result not found for ${item.id}`); + return { + ...original, + score: item.score, + }; + }); + } else if (this.reranker) { + // Cross-encoder reranking + const candidates = results.map((r) => { + const payload = r.payload as Record; + return { + id: payload.doc_id as string, + content: payload.content as string, + score: r.score, + }; + }); + + const reranked = await this.reranker.rerank(query, candidates, topK); + + // Map back to QdrantSearchResult format + return reranked.map((item) => { + const original = results.find( + (r) => (r.payload as Record).doc_id === item.id, + ); + if (!original) throw new Error(`Original result not found for ${item.id}`); + return { + ...original, + score: item.score, + }; + }); + } + } catch (error) { + console.warn("Reranking failed, using retrieval scores:", error); + } + + return results.slice(0, topK); + } + + /** + * Clear the collection and release resources + */ + clear(): void { + this.indexed = false; + this.documentEmbeddings.clear(); + // Note: We don't delete the collection here as it will be recreated on next index + // This avoids unnecessary Qdrant operations between instances + } + + /** + * Generate numeric hash for Qdrant point ID + */ + private hashId(id: string): number { + let hash = 0; + for (let i = 0; i < id.length; i++) { + hash = (hash << 5) - hash + id.charCodeAt(i); + hash = hash >>> 0; + } + return hash; + } +} + +/** + * Engram embedding provider (wrapper for compatibility) + */ +export class EngramEmbeddingProvider implements EmbeddingProvider { + readonly dimension = 384; + private textEmbedder: TextEmbedderInterface | null = null; + + async embed(texts: string[]): Promise { + const embedder = await this.getEmbedder(); + return Promise.all(texts.map((text) => embedder.embed(text).then((v) => Array.from(v)))); + } + + async embedQuery(text: string): Promise { + const embedder = await this.getEmbedder(); + const result = await embedder.embedQuery(text); + return Array.from(result); + } + + private async getEmbedder(): Promise { + if (this.textEmbedder) return this.textEmbedder; + + try { + const { TextEmbedder } = await import("@engram/search"); + this.textEmbedder = new TextEmbedder() as unknown as TextEmbedderInterface; + } catch { + throw new Error("@engram/search not available"); + } + + return this.textEmbedder; + } +} + +// Type interfaces for search-core components +interface TextEmbedderInterface { + embed(text: string): Promise; + embedQuery(text: string): Promise; +} + +interface SpladeEmbedderInterface { + embed(text: string): Promise; + embedQuery(text: string): Promise; +} + +interface ColBERTEmbedderInterface { + encodeDocument(text: string): Promise; + encodeQuery(text: string): Promise; +} + +interface RerankerInterface { + rerank( + query: string, + candidates: Array<{ id: string; content: string; score: number }>, + topK: number, + ): Promise>; +} + +interface ColBERTRerankerInterface { + rerank( + query: string, + candidates: Array<{ + id: string; + content: string; + score: number; + colbertEmbeddings?: Float32Array[]; + }>, + topK: number, + ): Promise>; +} + +interface SparseVector { + indices: number[]; + values: number[]; +} + +interface QdrantClientInterface { + getCollection(name: string): Promise; + createCollection(name: string, config: unknown): Promise; + deleteCollection(name: string): Promise; + upsert(name: string, config: unknown): Promise; + search(name: string, config: unknown): Promise; + query(name: string, config: unknown): Promise<{ points?: QdrantSearchResult[] }>; +} + +interface QdrantPoint { + id: number; + vector: { + dense: number[]; + sparse?: SparseVector; + }; + payload: Record; +} + +interface QdrantSearchResult { + id: number | string; + score: number; + payload?: Record; +} + +interface XAIClientInterface { + chat(messages: Array<{ role: string; content: string }>): Promise; +} + +interface AbstentionDetectorInterface { + checkRetrievalConfidence(results: Array<{ score: number }>): { + shouldAbstain: boolean; + reason?: string; + confidence: number; + details?: string; + }; +} + +interface SessionSummarizerInterface { + summarize( + turns: Array<{ + id: string; + sessionId: string; + role: "user" | "assistant" | "system"; + content: string; + timestamp: Date; + }>, + ): Promise<{ + sessionId: string; + summary: string; + topics: string[]; + entities: string[]; + startTime: Date; + endTime: Date; + turnCount: number; + embedding: number[]; + }>; +} + +interface SessionRetrieverInterface { + retrieve(query: string): Promise< + Array<{ + id: string | number; + score: number; + sessionId: string; + sessionSummary?: string; + sessionScore?: number; + payload?: { + content?: string; + node_id?: string; + session_id?: string; + timestamp?: number; + }; + }> + >; +} + +interface LLMProviderInterface { + complete(prompt: string): Promise<{ text: string }>; +} + +interface TemporalFilterType { + after?: Date; + before?: Date; + sortByRecency?: boolean; + expression?: string; +} + +interface TemporalParserInterface { + parse(query: string): { + semanticQuery: string; + temporalFilter: TemporalFilterType | null; + confidence: number; + }; + setReferenceDate(date: Date): void; +} + +interface LearnedFusionInterface { + fuse( + query: string, + denseResults: Array<{ id: string; content: string; score: number }>, + sparseResults: Array<{ id: string; content: string; score: number }>, + rerankResults?: Array<{ id: string; content: string; score: number }>, + ): Promise>; +} diff --git a/packages/benchmark/src/longmemeval/providers/index.ts b/packages/benchmark/src/longmemeval/providers/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..754df66c4a34b363f7ef61d92944f0c6d8468b43 --- /dev/null +++ b/packages/benchmark/src/longmemeval/providers/index.ts @@ -0,0 +1,17 @@ +/** + * Provider integrations for LongMemEval benchmark + * + * These providers wrap Engram's search-core components for use in benchmarking. + * Includes LLM providers for Anthropic, OpenAI, Ollama, and Google Gemini. + */ + +export * from "./anthropic-provider.js"; +// Re-export specific providers for convenience +export { + AnthropicProvider, + GeminiProvider, + OllamaProvider, + OpenAICompatibleProvider, +} from "./anthropic-provider.js"; +export * from "./engram-provider.js"; +export * from "./qdrant-provider.js"; diff --git a/packages/benchmark/src/longmemeval/providers/qdrant-provider.ts b/packages/benchmark/src/longmemeval/providers/qdrant-provider.ts new file mode 100644 index 0000000000000000000000000000000000000000..6db2c94819c1217f28592cd77eb4629e3ac8cba0 --- /dev/null +++ b/packages/benchmark/src/longmemeval/providers/qdrant-provider.ts @@ -0,0 +1,283 @@ +import { QdrantClient } from "@qdrant/js-client-rest"; +import type { EngramDocument } from "../mapper.js"; +import type { EmbeddingProvider, RetrievalResult } from "../retriever.js"; + +/** + * Configuration for the Qdrant provider + */ +export interface QdrantProviderConfig { + /** Qdrant server URL */ + url: string; + /** Collection name for benchmark data */ + collectionName: string; + /** Embedding model to use */ + embeddingModel: "e5-small" | "e5-base" | "e5-large"; + /** Whether to use hybrid search (dense + sparse) */ + hybridSearch: boolean; +} + +const DEFAULT_CONFIG: QdrantProviderConfig = { + url: "http://localhost:6333", + collectionName: "longmemeval_benchmark", + embeddingModel: "e5-small", + hybridSearch: true, +}; + +/** + * Embedding dimensions by model + */ +const EMBEDDING_DIMENSIONS: Record = { + "e5-small": 384, + "e5-base": 768, + "e5-large": 1024, +}; + +/** + * Qdrant-based embedding provider using HuggingFace transformers + * + * Uses @engram/search's TextEmbedder under the hood when available, + * otherwise falls back to a lightweight implementation. + */ +export class QdrantEmbeddingProvider implements EmbeddingProvider { + readonly dimension: number; + private config: QdrantProviderConfig; + private embedder: TextEmbedderInterface | null = null; + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + this.dimension = EMBEDDING_DIMENSIONS[this.config.embeddingModel] ?? 384; + } + + /** + * Initialize the embedder (lazy loading) + */ + private async getEmbedder(): Promise { + if (this.embedder) { + return this.embedder; + } + + try { + // Try to import from search-core + const { TextEmbedder } = await import("@engram/search"); + this.embedder = new TextEmbedder() as unknown as TextEmbedderInterface; + } catch { + // Fall back to stub if search-core not available + console.warn("@engram/search not available, using stub embedder"); + this.embedder = new StubTextEmbedder(this.dimension); + } + + return this.embedder; + } + + /** + * Generate embeddings for a batch of texts + */ + async embed(texts: string[]): Promise { + const embedder = await this.getEmbedder(); + + // Embed in batches to avoid memory issues + const embeddings: number[][] = []; + const batchSize = 32; + + for (let i = 0; i < texts.length; i += batchSize) { + const batch = texts.slice(i, i + batchSize); + const batchEmbeddings = await Promise.all(batch.map((text) => embedder.embed(text))); + embeddings.push(...batchEmbeddings); + } + + return embeddings; + } + + /** + * Generate embedding for a query + */ + async embedQuery(text: string): Promise { + const embedder = await this.getEmbedder(); + return embedder.embedQuery(text); + } +} + +/** + * Interface for text embedders + */ +interface TextEmbedderInterface { + embed(text: string): Promise; + embedQuery(text: string): Promise; +} + +/** + * Stub embedder for when search-core is not available + */ +class StubTextEmbedder implements TextEmbedderInterface { + private dimension: number; + + constructor(dimension: number) { + this.dimension = dimension; + } + + async embed(text: string): Promise { + return this.generateEmbedding(text, "passage:"); + } + + async embedQuery(text: string): Promise { + return this.generateEmbedding(text, "query:"); + } + + private generateEmbedding(text: string, prefix: string): number[] { + // Simple deterministic embedding based on text hash + const hash = this.hashString(prefix + text); + return Array.from({ length: this.dimension }, (_, i) => { + const x = Math.sin(hash + i) * 10000; + return x - Math.floor(x); + }); + } + + private hashString(str: string): number { + let hash = 0; + for (let i = 0; i < str.length; i++) { + hash = (hash << 5) - hash + str.charCodeAt(i); + hash = hash & hash; + } + return Math.abs(hash); + } +} + +/** + * Qdrant-based retriever with hybrid search support + */ +export class QdrantRetriever { + private client: QdrantClient; + private config: QdrantProviderConfig; + private embedder: QdrantEmbeddingProvider; + private indexed: boolean = false; + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + this.client = new QdrantClient({ url: this.config.url }); + this.embedder = new QdrantEmbeddingProvider(config); + } + + /** + * Ensure collection exists with proper schema + */ + async ensureCollection(): Promise { + try { + await this.client.getCollection(this.config.collectionName); + } catch { + // Collection doesn't exist, create it + await this.client.createCollection(this.config.collectionName, { + vectors: { + dense: { + size: this.embedder.dimension, + distance: "Cosine", + }, + }, + }); + } + } + + /** + * Index documents for retrieval + */ + async index(documents: EngramDocument[]): Promise { + await this.ensureCollection(); + + // Generate embeddings + const texts = documents.map((d) => d.content); + const embeddings = await this.embedder.embed(texts); + + // Upsert to Qdrant + const points = documents.map((doc, i) => ({ + id: this.hashId(doc.id), + vector: { dense: embeddings[i] }, + payload: { + doc_id: doc.id, + instance_id: doc.instanceId, + session_id: doc.sessionId, + content: doc.content, + valid_time: doc.validTime.toISOString(), + has_answer: doc.metadata.hasAnswer, + role: doc.metadata.role, + turn_index: doc.metadata.turnIndex, + session_index: doc.metadata.sessionIndex, + }, + })); + + // Batch upsert + const batchSize = 100; + for (let i = 0; i < points.length; i += batchSize) { + const batch = points.slice(i, i + batchSize); + await this.client.upsert(this.config.collectionName, { + wait: true, + points: batch, + }); + } + + this.indexed = true; + } + + /** + * Search for relevant documents + */ + async search(query: string, topK: number): Promise { + if (!this.indexed) { + return { documents: [], scores: [], retrievedIds: [] }; + } + + const queryVector = await this.embedder.embedQuery(query); + + const results = await this.client.search(this.config.collectionName, { + vector: { name: "dense", vector: queryVector }, + limit: topK, + with_payload: true, + }); + + const documents: EngramDocument[] = results.map((r) => { + const payload = r.payload as Record; + return { + id: payload.doc_id as string, + instanceId: payload.instance_id as string, + sessionId: payload.session_id as string, + content: payload.content as string, + validTime: new Date(payload.valid_time as string), + metadata: { + questionId: payload.instance_id as string, + hasAnswer: payload.has_answer as boolean, + role: payload.role as "user" | "assistant" | "combined", + turnIndex: payload.turn_index as number | undefined, + sessionIndex: payload.session_index as number, + }, + }; + }); + + return { + documents, + scores: results.map((r) => r.score), + retrievedIds: documents.map((d) => d.id), + }; + } + + /** + * Clear the collection + */ + async clear(): Promise { + try { + await this.client.deleteCollection(this.config.collectionName); + this.indexed = false; + } catch { + // Collection might not exist + } + } + + /** + * Generate numeric hash for Qdrant point ID + */ + private hashId(id: string): number { + let hash = 0; + for (let i = 0; i < id.length; i++) { + hash = (hash << 5) - hash + id.charCodeAt(i); + hash = hash >>> 0; // Convert to unsigned + } + return hash; + } +} diff --git a/packages/benchmark/src/longmemeval/reader.ts b/packages/benchmark/src/longmemeval/reader.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5e188b53c54dadc2660171e765587299d9c1849 --- /dev/null +++ b/packages/benchmark/src/longmemeval/reader.ts @@ -0,0 +1,780 @@ +import type { EngramDocument } from "./mapper.js"; + +/** + * Configuration for the reading/answer generation stage + */ +export interface ReaderConfig { + /** Maximum tokens for context */ + maxContextTokens: number; + /** Whether to use Chain-of-Note (improves QA by ~10 points) */ + chainOfNote: boolean; + /** Whether to use enhanced Chain-of-Note with multi-step reasoning */ + enhancedChainOfNote: boolean; + /** Whether to use structured JSON format for context */ + structuredFormat: boolean; + /** Abstention confidence threshold (0-1, lower = more abstentions) */ + abstentionThreshold: number; + /** Whether to use calibrated confidence scoring */ + calibratedConfidence: boolean; + /** Whether to request JSON-structured output from LLM */ + jsonOutput: boolean; + /** Enable three-layer abstention detection (Layer 2 + 3) */ + abstentionDetection: boolean; + /** Enable NLI-based answer grounding check (Layer 2) - requires abstentionDetection */ + abstentionNLI: boolean; + /** NLI entailment threshold for abstention (0-1) */ + abstentionNLIThreshold: number; +} + +/** + * Default reader configuration based on LongMemEval findings + */ +export const DEFAULT_READER_CONFIG: ReaderConfig = { + maxContextTokens: 8000, + chainOfNote: true, + enhancedChainOfNote: true, + structuredFormat: true, + abstentionThreshold: 0.3, + calibratedConfidence: true, + jsonOutput: true, + abstentionDetection: false, + abstentionNLI: false, + abstentionNLIThreshold: 0.7, +}; + +/** + * Result of reading/answer generation + */ +export interface ReadResult { + /** Generated answer */ + hypothesis: string; + /** Chain-of-thought reasoning (if enabled) */ + reasoning?: string; + /** Key information extracted from context (Chain-of-Note) */ + keyInformation?: string[]; + /** Confidence score for abstention (0-1, calibrated) */ + confidence?: number; + /** Individual confidence signals for debugging */ + confidenceSignals?: ConfidenceSignals; + /** Whether the model chose to abstain */ + abstained: boolean; + /** Reason for abstention from AbstentionDetector */ + abstentionReason?: "low_retrieval_score" | "no_score_gap" | "not_grounded" | "hedging_detected"; + /** Original answer before abstention (if abstained) */ + originalAnswer?: string; +} + +/** + * Individual signals used to compute calibrated confidence + */ +export interface ConfidenceSignals { + /** Whether relevant documents were found */ + hasRelevantDocs: boolean; + /** Relevance score of top document (0-1) */ + topDocRelevance: number; + /** Number of documents supporting the answer */ + supportingDocCount: number; + /** Whether the question is answerable based on context */ + questionAnswerable: boolean; + /** LLM's self-reported confidence (if available) */ + llmConfidence?: number; + /** Whether abstention phrases were detected */ + abstentionDetected: boolean; +} + +/** + * Interface for LLM providers + */ +export interface LLMProvider { + /** Generate a completion */ + complete(prompt: string, options?: LLMOptions): Promise; +} + +export interface LLMOptions { + temperature?: number; + maxTokens?: number; + stopSequences?: string[]; +} + +export interface LLMResponse { + text: string; + usage?: { + inputTokens: number; + outputTokens: number; + }; +} + +/** + * Interface for AbstentionDetector from @engram/search + */ +interface AbstentionDetectorInterface { + checkHedgingPatterns(answer: string): { + shouldAbstain: boolean; + reason?: string; + confidence: number; + details?: string; + }; + checkAnswerGrounding( + answer: string, + context: string, + ): Promise<{ + shouldAbstain: boolean; + reason?: string; + confidence: number; + details?: string; + }>; +} + +/** + * Reader class that generates answers from retrieved context + * + * Implements Milestone 3 optimizations: + * - Enhanced Chain-of-Note with multi-step reasoning + * - JSON-structured prompts for better parsing + * - Calibrated abstention confidence scoring + * - Three-layer abstention detection (Layer 2: NLI, Layer 3: Hedging) + */ +export class Reader { + private config: ReaderConfig; + private llm: LLMProvider; + private abstentionDetector: AbstentionDetectorInterface | null = null; + private abstentionDetectorInitPromise: Promise | null = null; + + constructor(llm: LLMProvider, config?: Partial) { + this.config = { ...DEFAULT_READER_CONFIG, ...config }; + this.llm = llm; + + // Initialize abstention detector if enabled + if (this.config.abstentionDetection) { + this.abstentionDetectorInitPromise = this.initAbstentionDetector(); + } + } + + /** + * Initialize the AbstentionDetector from @engram/search + */ + private async initAbstentionDetector(): Promise { + try { + const { AbstentionDetector } = await import("@engram/search"); + this.abstentionDetector = new AbstentionDetector({ + useNLI: this.config.abstentionNLI, + nliThreshold: this.config.abstentionNLIThreshold, + }) as unknown as AbstentionDetectorInterface; + } catch (error) { + console.warn( + "[Reader] AbstentionDetector not available, disabling abstention detection:", + error, + ); + this.abstentionDetector = null; + } + } + + /** + * Generate an answer given retrieved documents and a question + */ + async read( + question: string, + documents: EngramDocument[], + questionDate?: Date, + retrievalScores?: number[], + ): Promise { + // Wait for abstention detector initialization if in progress + if (this.abstentionDetectorInitPromise) { + await this.abstentionDetectorInitPromise; + } + + const prompt = this.buildPrompt(question, documents, questionDate); + + const response = await this.llm.complete(prompt, { + temperature: 0.1, + maxTokens: 1024, + }); + + const result = this.parseResponse(response.text, documents, retrievalScores); + + // Apply abstention detection (Layers 2 & 3) if enabled and detector available + if (this.abstentionDetector && !result.abstained) { + const abstentionResult = await this.applyAbstentionDetection( + result.hypothesis, + documents.map((d) => d.content).join("\n\n"), + ); + + if (abstentionResult.shouldAbstain) { + return { + ...result, + hypothesis: "I don't have enough information to answer this question.", + abstained: true, + abstentionReason: abstentionResult.reason as ReadResult["abstentionReason"], + originalAnswer: result.hypothesis, + }; + } + } + + return result; + } + + /** + * Apply Layer 2 (NLI) and Layer 3 (Hedging) abstention detection + */ + private async applyAbstentionDetection( + answer: string, + context: string, + ): Promise<{ shouldAbstain: boolean; reason?: string; details?: string }> { + if (!this.abstentionDetector) { + return { shouldAbstain: false }; + } + + // Layer 3: Hedging pattern detection (sync, fast) + const hedgingResult = this.abstentionDetector.checkHedgingPatterns(answer); + if (hedgingResult.shouldAbstain) { + console.log(` [Abstention:Hedging] ${hedgingResult.details}`); + return hedgingResult; + } + + // Layer 2: NLI answer grounding check (async, slower - only if NLI enabled) + if (this.config.abstentionNLI) { + const nliResult = await this.abstentionDetector.checkAnswerGrounding(answer, context); + if (nliResult.shouldAbstain) { + console.log(` [Abstention:NLI] ${nliResult.details}`); + return nliResult; + } + } + + return { shouldAbstain: false }; + } + + /** + * Builds the prompt for answer generation + */ + private buildPrompt(question: string, documents: EngramDocument[], questionDate?: Date): string { + const context = this.config.structuredFormat + ? this.formatAsJSON(documents) + : documents.map((d) => d.content).join("\n\n---\n\n"); + + const dateContext = questionDate + ? `Today's date: ${questionDate.toISOString().split("T")[0]}\n\n` + : ""; + + if (this.config.enhancedChainOfNote) { + return this.buildEnhancedChainOfNotePrompt(question, context, dateContext); + } + + if (this.config.chainOfNote) { + return this.buildChainOfNotePrompt(question, context, dateContext); + } + + return this.buildDirectPrompt(question, context, dateContext); + } + + /** + * Format documents as JSON for structured context + */ + private formatAsJSON(documents: EngramDocument[]): string { + const items = documents.map((doc, idx) => ({ + index: idx + 1, + timestamp: doc.validTime.toISOString().split("T")[0], + role: doc.metadata.role, + content: doc.content, + sessionId: doc.sessionId, + })); + + return JSON.stringify(items, null, 2); + } + + /** + * Builds an enhanced Chain-of-Note prompt with multi-step reasoning + * Based on LongMemEval findings: +10 points QA accuracy + */ + private buildEnhancedChainOfNotePrompt( + question: string, + context: string, + dateContext: string, + ): string { + const outputFormat = this.config.jsonOutput + ? `Respond in JSON format: +\`\`\`json +{ + "key_information": ["fact1", "fact2", ...], + "reasoning_steps": ["step1", "step2", ...], + "answer": "your answer", + "confidence": 0.0-1.0, + "answerable": true/false +} +\`\`\`` + : `### Key Information: +(List facts from conversation relevant to the question) + +### Reasoning Steps: +(Your step-by-step reasoning process) + +### Confidence: +(0.0 to 1.0 - how confident are you?) + +### Answerable: +(yes/no - is this answerable from the context?) + +### Answer: +(Your final answer - be direct and concise)`; + + return `You are a memory assistant analyzing conversation history to answer questions. + +${dateContext}## Conversation History (JSON format) + +${context} + +## Task + +Analyze the conversation history and answer the question below. + +**Step-by-step approach:** +1. EXTRACT: Identify all facts in the conversation that could be relevant to the question +2. VERIFY: Check if the extracted facts directly answer the question or if information is missing +3. REASON: If answerable, reason through the facts to derive the answer +4. CONFIDENCE: Assess your confidence (1.0 = certain from direct evidence, 0.5 = inferred, 0.0 = cannot answer) +5. ANSWER: Provide a direct, concise answer OR state you cannot answer + +**Important:** +- Only use information explicitly stated in the conversation history +- If the question cannot be answered from the history, set confidence to 0 and answerable to false +- For temporal questions, pay attention to dates and time references +- For knowledge updates, use the most recent information + +## Question + +${question} + +## Response + +${outputFormat}`; + } + + /** + * Builds a Chain-of-Note prompt (recommended by LongMemEval) + */ + private buildChainOfNotePrompt(question: string, context: string, dateContext: string): string { + return `You are a helpful assistant with access to conversation history. + +${dateContext}## Retrieved Conversation History + +${context} + +## Task + +Based on the conversation history above, answer the following question. + +**Important Instructions:** +1. First, extract the key information from the conversation history that is relevant to the question. +2. Then, reason step by step to arrive at your answer. +3. If the information needed to answer the question is not present in the history, respond with "I don't have that information." +4. Be concise and direct in your final answer. + +## Question + +${question} + +## Response + +### Key Information Extracted: +(List the relevant facts from the conversation history) + +### Reasoning: +(Your step-by-step reasoning) + +### Answer: +(Your final answer - be direct and concise)`; + } + + /** + * Builds a direct prompt without Chain-of-Note + */ + private buildDirectPrompt(question: string, context: string, dateContext: string): string { + return `You are a helpful assistant with access to conversation history. + +${dateContext}## Retrieved Conversation History + +${context} + +## Question + +${question} + +## Instructions + +Answer the question based on the conversation history above. +If the information is not available in the history, respond with "I don't have that information." +Be concise and direct. + +## Answer:`; + } + + /** + * Parses the LLM response to extract the answer with calibrated confidence + */ + private parseResponse( + text: string, + documents: EngramDocument[], + retrievalScores?: number[], + ): ReadResult { + // Try JSON parsing first + const jsonResult = this.parseJsonResponse(text); + if (jsonResult) { + const signals = this.computeConfidenceSignals(jsonResult, documents, retrievalScores, text); + const calibratedConfidence = this.config.calibratedConfidence + ? this.calibrateConfidence(signals) + : (jsonResult.confidence ?? (jsonResult.answerable ? 1 : 0)); + + return { + hypothesis: jsonResult.answer, + reasoning: jsonResult.reasoning_steps?.join(" → "), + keyInformation: jsonResult.key_information, + confidence: calibratedConfidence, + confidenceSignals: signals, + abstained: calibratedConfidence < this.config.abstentionThreshold, + }; + } + + // Fall back to markdown parsing + return this.parseMarkdownResponse(text, documents, retrievalScores); + } + + /** + * Parse JSON-formatted response + */ + private parseJsonResponse(text: string): JsonResponse | null { + try { + // Extract JSON from markdown code blocks + const jsonMatch = text.match(/```json\s*([\s\S]*?)\s*```/); + if (jsonMatch) { + return JSON.parse(jsonMatch[1]); + } + + // Try parsing entire response as JSON + const directMatch = text.match(/\{[\s\S]*\}/); + if (directMatch) { + return JSON.parse(directMatch[0]); + } + } catch { + // JSON parsing failed, fall back to markdown + } + return null; + } + + /** + * Parse markdown-formatted response (fallback) + */ + private parseMarkdownResponse( + text: string, + documents: EngramDocument[], + retrievalScores?: number[], + ): ReadResult { + // Check for abstention phrases + const abstentionPhrases = [ + "i don't have that information", + "i do not have that information", + "not mentioned in the conversation", + "no information about", + "cannot find", + "not available in the history", + "not present in the conversation", + "cannot answer", + "unable to answer", + ]; + + const lowerText = text.toLowerCase(); + const abstentionDetected = abstentionPhrases.some((phrase) => lowerText.includes(phrase)); + + // Extract key information + let keyInformation: string[] | undefined; + const keyInfoMatch = text.match(/### Key Information[:\s]*([\s\S]*?)(?:\n###|$)/i); + if (keyInfoMatch) { + keyInformation = keyInfoMatch[1] + .split(/\n[-•*]\s*/) + .map((s) => s.trim()) + .filter((s) => s.length > 0); + } + + // Extract reasoning + let reasoning: string | undefined; + const reasoningMatch = text.match( + /### Reasoning(?:\s+Steps)?[:\s]*([\s\S]*?)(?:\n### (?:Answer|Confidence)|$)/i, + ); + if (reasoningMatch) { + reasoning = reasoningMatch[1].trim(); + } + + // Extract confidence + let llmConfidence: number | undefined; + const confidenceMatch = text.match(/### Confidence[:\s]*(\d*\.?\d+)/i); + if (confidenceMatch) { + llmConfidence = Number.parseFloat(confidenceMatch[1]); + } + + // Extract answerable + let questionAnswerable = true; + const answerableMatch = text.match(/### Answerable[:\s]*(yes|no|true|false)/i); + if (answerableMatch) { + questionAnswerable = ["yes", "true"].includes(answerableMatch[1].toLowerCase()); + } + + // Extract answer + let hypothesis = text; + const answerMatch = text.match(/### Answer[:\s]*([\s\S]*?)(?:\n###|$)/i); + if (answerMatch) { + hypothesis = answerMatch[1].trim(); + } + + // Clean up the hypothesis + hypothesis = hypothesis.trim(); + if (hypothesis.includes("###")) { + hypothesis = hypothesis.split("###")[0].trim(); + } + + // Compute confidence signals + const signals: ConfidenceSignals = { + hasRelevantDocs: documents.length > 0, + topDocRelevance: retrievalScores?.[0] ?? 0, + supportingDocCount: documents.length, + questionAnswerable, + llmConfidence, + abstentionDetected, + }; + + const calibratedConfidence = this.config.calibratedConfidence + ? this.calibrateConfidence(signals) + : abstentionDetected + ? 0 + : 1; + + return { + hypothesis, + reasoning, + keyInformation, + confidence: calibratedConfidence, + confidenceSignals: signals, + abstained: calibratedConfidence < this.config.abstentionThreshold, + }; + } + + /** + * Compute confidence signals from various sources + */ + private computeConfidenceSignals( + jsonResponse: JsonResponse, + documents: EngramDocument[], + retrievalScores?: number[], + rawText?: string, + ): ConfidenceSignals { + const lowerText = (rawText ?? "").toLowerCase(); + const abstentionPhrases = [ + "cannot answer", + "don't have", + "do not have", + "not available", + "not found", + ]; + + return { + hasRelevantDocs: documents.length > 0, + topDocRelevance: retrievalScores?.[0] ?? 0, + supportingDocCount: documents.length, + questionAnswerable: jsonResponse.answerable ?? true, + llmConfidence: jsonResponse.confidence, + abstentionDetected: abstentionPhrases.some((p) => lowerText.includes(p)), + }; + } + + /** + * Calibrate confidence using multiple signals + * + * Weighted combination based on LongMemEval findings: + * - LLM self-reported confidence is somewhat reliable + * - Retrieval score indicates evidence quality + * - Abstention detection catches explicit uncertainty + */ + private calibrateConfidence(signals: ConfidenceSignals): number { + // If abstention explicitly detected, low confidence + if (signals.abstentionDetected) { + return 0.1; + } + + // If question marked as unanswerable + if (!signals.questionAnswerable) { + return 0.15; + } + + // If no relevant documents retrieved + if (!signals.hasRelevantDocs) { + return 0.2; + } + + // Weighted combination of signals + const weights = { + llmConfidence: 0.4, + topDocRelevance: 0.3, + docCountScore: 0.2, + baseConfidence: 0.1, + }; + + // LLM confidence (default to 0.7 if not provided) + const llmScore = signals.llmConfidence ?? 0.7; + + // Document relevance score (already 0-1) + const relevanceScore = signals.topDocRelevance; + + // Document count score (more docs = higher confidence, capped) + const docCountScore = Math.min(signals.supportingDocCount / 5, 1); + + // Base confidence (always some uncertainty) + const baseScore = 0.5; + + const calibrated = + weights.llmConfidence * llmScore + + weights.topDocRelevance * relevanceScore + + weights.docCountScore * docCountScore + + weights.baseConfidence * baseScore; + + // Clamp to 0-1 range + return Math.max(0, Math.min(1, calibrated)); + } +} + +/** + * JSON response structure from LLM + */ +interface JsonResponse { + key_information?: string[]; + reasoning_steps?: string[]; + answer: string; + confidence?: number; + answerable?: boolean; +} + +/** + * Stub LLM provider for testing - returns JSON-formatted responses + */ +export class StubLLMProvider implements LLMProvider { + private responses: Map = new Map(); + + /** + * Set a canned response for a question pattern + */ + setResponse(questionPattern: string, response: string): void { + this.responses.set(questionPattern.toLowerCase(), response); + } + + async complete(prompt: string): Promise { + // Extract the question from the prompt + const questionMatch = prompt.match(/## Question\s+([\s\S]*?)(?:\n##|$)/); + const question = questionMatch?.[1]?.trim() ?? "Unknown question"; + const lowerQuestion = question.toLowerCase(); + + // Check for canned responses + for (const [pattern, response] of this.responses) { + if (lowerQuestion.includes(pattern)) { + return { text: response, usage: { inputTokens: 0, outputTokens: 0 } }; + } + } + + // Default JSON response indicating unable to answer + const jsonResponse = { + key_information: [], + reasoning_steps: ["No context provided", "Cannot determine answer"], + answer: `Unable to answer: "${question}"`, + confidence: 0.1, + answerable: false, + }; + + return { + text: `\`\`\`json\n${JSON.stringify(jsonResponse, null, 2)}\n\`\`\``, + usage: { inputTokens: 0, outputTokens: 0 }, + }; + } +} + +/** + * Mock LLM provider for testing with configurable behavior + */ +export class MockLLMProvider implements LLMProvider { + private fixedResponse: JsonResponse | null = null; + private confidenceOverride: number | null = null; + + /** + * Set a fixed JSON response + */ + setFixedResponse(response: JsonResponse): void { + this.fixedResponse = response; + } + + /** + * Override confidence in responses + */ + setConfidenceOverride(confidence: number): void { + this.confidenceOverride = confidence; + } + + async complete(prompt: string): Promise { + if (this.fixedResponse) { + const response = { ...this.fixedResponse }; + if (this.confidenceOverride !== null) { + response.confidence = this.confidenceOverride; + } + return { + text: `\`\`\`json\n${JSON.stringify(response, null, 2)}\n\`\`\``, + usage: { inputTokens: 0, outputTokens: 0 }, + }; + } + + // Default behavior - extract question and return generic response + const questionMatch = prompt.match(/## Question\s+([\s\S]*?)(?:\n##|$)/); + const question = questionMatch?.[1]?.trim() ?? "Unknown question"; + + const response: JsonResponse = { + key_information: ["Extracted from context"], + reasoning_steps: ["Analyzed the question", "Found relevant information"], + answer: `Answer to: ${question}`, + confidence: this.confidenceOverride ?? 0.8, + answerable: true, + }; + + return { + text: `\`\`\`json\n${JSON.stringify(response, null, 2)}\n\`\`\``, + usage: { inputTokens: 0, outputTokens: 0 }, + }; + } +} + +/** + * Simple embedding provider for testing (random embeddings) + */ +export class StubEmbeddingProvider { + readonly dimension = 384; + + async embed(texts: string[]): Promise { + // Generate deterministic pseudo-random embeddings based on text hash + return texts.map((text) => { + const seed = hashString(text); + return Array.from({ length: this.dimension }, (_, i) => seededRandom(seed + i)); + }); + } +} + +/** + * Simple string hash function + */ +function hashString(str: string): number { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; // Convert to 32-bit integer + } + return Math.abs(hash); +} + +/** + * Seeded random number generator + */ +function seededRandom(seed: number): number { + const x = Math.sin(seed) * 10000; + return x - Math.floor(x); +} diff --git a/packages/benchmark/src/longmemeval/retriever.ts b/packages/benchmark/src/longmemeval/retriever.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5c40d3a649f97366eb4b11bfd7c4fdb3f52ba07 --- /dev/null +++ b/packages/benchmark/src/longmemeval/retriever.ts @@ -0,0 +1,321 @@ +import type { EngramDocument, MappedInstance } from "./mapper.js"; + +/** + * Configuration for the retrieval stage + */ +export interface RetrieverConfig { + /** Retrieval method */ + method: "dense" | "bm25" | "hybrid"; + /** Number of documents to retrieve */ + topK: number; + /** Time-aware query expansion (improves temporal reasoning by 7-11%) */ + timeAwareExpansion: boolean; + /** Similarity threshold (0-1) */ + similarityThreshold?: number; +} + +/** + * Default retriever configuration + */ +export const DEFAULT_RETRIEVER_CONFIG: RetrieverConfig = { + method: "dense", + topK: 10, + timeAwareExpansion: false, + similarityThreshold: 0.5, +}; + +/** + * Result of a retrieval operation + */ +export interface RetrievalResult { + /** Retrieved documents */ + documents: EngramDocument[]; + /** Similarity scores for each document */ + scores: number[]; + /** IDs of retrieved documents */ + retrievedIds: string[]; + /** Time range extracted from query (if time-aware) */ + extractedTimeRange?: { start: Date; end: Date }; + /** Whether abstention detection indicated low confidence */ + abstained?: boolean; + /** Reason for abstention (if applicable) */ + abstentionReason?: string; + /** Retrieval confidence score from abstention detector */ + retrievalConfidence?: number; +} + +/** + * Interface for embedding providers + */ +export interface EmbeddingProvider { + /** Generate embeddings for texts */ + embed(texts: string[]): Promise; + /** Get the embedding dimension */ + dimension: number; +} + +/** + * Simple in-memory vector store for benchmarking + * In production, this would use Qdrant + */ +export class InMemoryVectorStore { + private documents: EngramDocument[] = []; + private embeddings: number[][] = []; + private embeddingProvider: EmbeddingProvider; + + constructor(embeddingProvider: EmbeddingProvider) { + this.embeddingProvider = embeddingProvider; + } + + /** + * Index documents for retrieval + */ + async index(documents: EngramDocument[]): Promise { + const texts = documents.map((d) => d.content); + const embeddings = await this.embeddingProvider.embed(texts); + + this.documents = documents; + this.embeddings = embeddings; + } + + /** + * Search for similar documents + */ + async search(query: string, topK: number): Promise { + const [queryEmbedding] = await this.embeddingProvider.embed([query]); + + // Compute cosine similarities + const similarities = this.embeddings.map((docEmb) => cosineSimilarity(queryEmbedding, docEmb)); + + // Get top-K indices + const indices = similarities + .map((score, index) => ({ score, index })) + .sort((a, b) => b.score - a.score) + .slice(0, topK) + .map((item) => item.index); + + const documents = indices.map((i) => this.documents[i]); + const scores = indices.map((i) => similarities[i]); + const retrievedIds = documents.map((d) => d.id); + + return { + documents, + scores, + retrievedIds, + }; + } + + /** + * Clear the index + */ + clear(): void { + this.documents = []; + this.embeddings = []; + } +} + +/** + * Computes cosine similarity between two vectors + */ +function cosineSimilarity(a: number[], b: number[]): number { + if (a.length !== b.length) { + throw new Error("Vectors must have the same dimension"); + } + + let dotProduct = 0; + let normA = 0; + let normB = 0; + + for (let i = 0; i < a.length; i++) { + dotProduct += a[i] * b[i]; + normA += a[i] * a[i]; + normB += b[i] * b[i]; + } + + normA = Math.sqrt(normA); + normB = Math.sqrt(normB); + + if (normA === 0 || normB === 0) { + return 0; + } + + return dotProduct / (normA * normB); +} + +/** + * Retriever class that handles document retrieval for LongMemEval + */ +export class Retriever { + private config: RetrieverConfig; + private vectorStore: InMemoryVectorStore; + + constructor(embeddingProvider: EmbeddingProvider, config?: Partial) { + this.config = { ...DEFAULT_RETRIEVER_CONFIG, ...config }; + this.vectorStore = new InMemoryVectorStore(embeddingProvider); + } + + /** + * Index a mapped instance for retrieval + */ + async indexInstance(mapped: MappedInstance): Promise { + await this.vectorStore.index(mapped.documents); + } + + /** + * Retrieve relevant documents for a question + */ + async retrieve(question: string, questionDate?: Date): Promise { + let query = question; + let extractedTimeRange: { start: Date; end: Date } | undefined; + + // Apply time-aware query expansion if enabled + if (this.config.timeAwareExpansion && questionDate) { + const extraction = extractTemporalContext(question, questionDate); + if (extraction) { + query = extraction.expandedQuery; + extractedTimeRange = extraction.timeRange; + } + } + + const result = await this.vectorStore.search(query, this.config.topK); + + // Filter by time range if extracted + if (extractedTimeRange) { + const filtered = result.documents.filter((doc) => { + const docTime = doc.validTime.getTime(); + return ( + docTime >= extractedTimeRange?.start.getTime() && + docTime <= extractedTimeRange?.end.getTime() + ); + }); + + // If filtering removes too many, fall back to unfiltered + if (filtered.length >= this.config.topK / 2) { + result.documents = filtered.slice(0, this.config.topK); + result.retrievedIds = result.documents.map((d) => d.id); + result.scores = result.scores.slice(0, result.documents.length); + } + } + + result.extractedTimeRange = extractedTimeRange; + + return result; + } + + /** + * Clear the index + */ + clear(): void { + this.vectorStore.clear(); + } +} + +/** + * Extracts temporal context from a question + * This is a simplified version - production would use LLM extraction + */ +function extractTemporalContext( + question: string, + questionDate: Date, +): { expandedQuery: string; timeRange: { start: Date; end: Date } } | null { + const lowerQuestion = question.toLowerCase(); + + // Common temporal patterns + const patterns = [ + { regex: /last (?:week|7 days)/i, daysBack: 7 }, + { regex: /last (?:month|30 days)/i, daysBack: 30 }, + { regex: /last (?:year|12 months)/i, daysBack: 365 }, + { regex: /yesterday/i, daysBack: 1 }, + { regex: /this (?:week|month)/i, daysBack: 7 }, + ]; + + for (const pattern of patterns) { + if (pattern.regex.test(lowerQuestion)) { + const end = new Date(questionDate); + const start = new Date(questionDate); + start.setDate(start.getDate() - pattern.daysBack); + + return { + expandedQuery: question, + timeRange: { start, end }, + }; + } + } + + // Check for specific month/year mentions + const monthYearMatch = lowerQuestion.match( + /(january|february|march|april|may|june|july|august|september|october|november|december)\s*(\d{4})?/i, + ); + + if (monthYearMatch) { + const monthNames = [ + "january", + "february", + "march", + "april", + "may", + "june", + "july", + "august", + "september", + "october", + "november", + "december", + ]; + const monthIndex = monthNames.indexOf(monthYearMatch[1].toLowerCase()); + const year = monthYearMatch[2] + ? Number.parseInt(monthYearMatch[2], 10) + : questionDate.getFullYear(); + + const start = new Date(year, monthIndex, 1); + const end = new Date(year, monthIndex + 1, 0); + + return { + expandedQuery: question, + timeRange: { start, end }, + }; + } + + return null; +} + +/** + * Computes retrieval metrics for evaluation + */ +export function computeRetrievalMetrics( + result: RetrievalResult, + evidenceDocIds: string[], +): { + recall: number; + precision: number; + recallAtK: Record; +} { + const evidenceSet = new Set(evidenceDocIds); + const _retrievedSet = new Set(result.retrievedIds); + + // Compute recall and precision + let hits = 0; + for (const id of result.retrievedIds) { + if (evidenceSet.has(id)) { + hits++; + } + } + + const recall = evidenceDocIds.length > 0 ? hits / evidenceDocIds.length : 0; + const precision = result.retrievedIds.length > 0 ? hits / result.retrievedIds.length : 0; + + // Compute recall@K for K = 1, 5, 10 + const recallAtK: Record = {}; + for (const k of [1, 5, 10]) { + const topKIds = result.retrievedIds.slice(0, k); + let hitsAtK = 0; + for (const id of topKIds) { + if (evidenceSet.has(id)) { + hitsAtK++; + } + } + recallAtK[k] = evidenceDocIds.length > 0 ? hitsAtK / evidenceDocIds.length : 0; + } + + return { recall, precision, recallAtK }; +} diff --git a/packages/benchmark/src/longmemeval/temporal.ts b/packages/benchmark/src/longmemeval/temporal.ts new file mode 100644 index 0000000000000000000000000000000000000000..1800ad6dfc3bb9ffa2422cdea5fcd22332b0af36 --- /dev/null +++ b/packages/benchmark/src/longmemeval/temporal.ts @@ -0,0 +1,430 @@ +import type { LLMProvider } from "./reader.js"; + +/** + * Time-Aware Query Expansion + * + * Based on LongMemEval findings: + * - Time-aware indexing and query expansion improves temporal reasoning by 7-11% + * - Extracting temporal ranges from queries narrows search scope + * + * @see https://arxiv.org/abs/2410.10813 + */ + +/** + * Configuration for temporal query expansion + */ +export interface TemporalConfig { + /** LLM for extraction (optional - uses heuristics if not provided) */ + llm?: LLMProvider; + /** Default time window in days when no explicit range */ + defaultWindowDays: number; +} + +const DEFAULT_CONFIG: TemporalConfig = { + defaultWindowDays: 30, +}; + +/** + * Result of temporal query analysis + */ +export interface TemporalAnalysis { + /** Original query */ + originalQuery: string; + /** Expanded query with temporal context */ + expandedQuery: string; + /** Extracted time range for filtering */ + timeRange?: TimeRange; + /** Temporal keywords found */ + temporalKeywords: string[]; + /** Whether query requires temporal reasoning */ + isTemporalQuery: boolean; +} + +/** + * Time range for filtering + */ +export interface TimeRange { + start: Date; + end: Date; + confidence: "high" | "medium" | "low"; + source: string; // What triggered this range +} + +/** + * Temporal query analyzer and expander + */ +export class TemporalAnalyzer { + private config: TemporalConfig; + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + } + + /** + * Analyze and expand a query for temporal context + */ + async analyze(query: string, queryDate: Date): Promise { + // Extract temporal keywords + const temporalKeywords = this.extractTemporalKeywords(query); + const isTemporalQuery = temporalKeywords.length > 0 || this.hasTemporalIntent(query); + + // Extract time range + let timeRange: TimeRange | undefined; + if (isTemporalQuery) { + timeRange = this.config.llm + ? await this.llmExtractTimeRange(query, queryDate) + : this.heuristicTimeRange(query, queryDate); + } + + // Expand query + const expandedQuery = this.expandQuery(query, timeRange, queryDate); + + return { + originalQuery: query, + expandedQuery, + timeRange, + temporalKeywords, + isTemporalQuery, + }; + } + + /** + * Extract temporal keywords from query + */ + private extractTemporalKeywords(query: string): string[] { + const keywords: string[] = []; + const lowerQuery = query.toLowerCase(); + + // Temporal keyword patterns + const patterns = [ + // Relative time + /\b(yesterday|today|tomorrow|last|next|recent|recently|previous|current|now)\b/g, + // Time units + /\b(week|month|year|day|hour|minute|morning|afternoon|evening|night)\b/g, + // Ordinals + /\b(first|second|third|latest|earliest|oldest|newest)\b/g, + // Temporal questions + /\b(when|since|until|before|after|during|while)\b/g, + // Specific time references + /\b(january|february|march|april|may|june|july|august|september|october|november|december)\b/g, + /\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b/g, + // Date patterns + /\b\d{4}\b/g, // Year + /\b\d{1,2}\/\d{1,2}\b/g, // Date format + ]; + + for (const pattern of patterns) { + for (const match of lowerQuery.matchAll(pattern)) { + keywords.push(match[0]); + } + } + + return [...new Set(keywords)]; + } + + /** + * Check if query has temporal intent without explicit keywords + */ + private hasTemporalIntent(query: string): boolean { + const lowerQuery = query.toLowerCase(); + + // Questions that often require temporal context + const temporalPatterns = [ + /how long/, + /how many times/, + /what time/, + /what date/, + /which day/, + /most recent/, + /changed|updated|modified/, + /started|began|ended|finished/, + /first time|last time/, + /ever since/, + /up to now/, + /so far/, + /at the moment/, + /currently/, + ]; + + return temporalPatterns.some((pattern) => pattern.test(lowerQuery)); + } + + /** + * Extract time range using heuristics + */ + private heuristicTimeRange(query: string, queryDate: Date): TimeRange | undefined { + const lowerQuery = query.toLowerCase(); + + // Yesterday + if (/\byesterday\b/.test(lowerQuery)) { + const start = new Date(queryDate); + start.setDate(start.getDate() - 1); + start.setHours(0, 0, 0, 0); + const end = new Date(start); + end.setHours(23, 59, 59, 999); + return { start, end, confidence: "high", source: "yesterday" }; + } + + // Today + if (/\btoday\b/.test(lowerQuery)) { + const start = new Date(queryDate); + start.setHours(0, 0, 0, 0); + const end = new Date(queryDate); + end.setHours(23, 59, 59, 999); + return { start, end, confidence: "high", source: "today" }; + } + + // Tomorrow + if (/\btomorrow\b/.test(lowerQuery)) { + const start = new Date(queryDate); + start.setDate(start.getDate() + 1); + start.setHours(0, 0, 0, 0); + const end = new Date(start); + end.setHours(23, 59, 59, 999); + return { start, end, confidence: "high", source: "tomorrow" }; + } + + // Last week + if (/\blast\s+week\b/.test(lowerQuery)) { + const end = new Date(queryDate); + const start = new Date(queryDate); + start.setDate(start.getDate() - 7); + return { start, end, confidence: "high", source: "last week" }; + } + + // Last month + if (/\blast\s+month\b/.test(lowerQuery)) { + const end = new Date(queryDate); + const start = new Date(queryDate); + start.setMonth(start.getMonth() - 1); + return { start, end, confidence: "high", source: "last month" }; + } + + // Last year + if (/\blast\s+year\b/.test(lowerQuery)) { + const end = new Date(queryDate); + const start = new Date(queryDate); + start.setFullYear(start.getFullYear() - 1); + return { start, end, confidence: "high", source: "last year" }; + } + + // Last N days/weeks/months + const lastNMatch = lowerQuery.match(/\blast\s+(\d+)\s+(day|week|month|year)s?\b/); + if (lastNMatch) { + const n = Number.parseInt(lastNMatch[1], 10); + const unit = lastNMatch[2]; + const end = new Date(queryDate); + const start = new Date(queryDate); + + switch (unit) { + case "day": + start.setDate(start.getDate() - n); + break; + case "week": + start.setDate(start.getDate() - n * 7); + break; + case "month": + start.setMonth(start.getMonth() - n); + break; + case "year": + start.setFullYear(start.getFullYear() - n); + break; + } + + return { start, end, confidence: "high", source: `last ${n} ${unit}s` }; + } + + // Specific month + const monthMatch = lowerQuery.match( + /\b(january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+(\d{4}))?\b/, + ); + if (monthMatch) { + const monthNames = [ + "january", + "february", + "march", + "april", + "may", + "june", + "july", + "august", + "september", + "october", + "november", + "december", + ]; + const monthIndex = monthNames.indexOf(monthMatch[1]); + const year = monthMatch[2] ? Number.parseInt(monthMatch[2], 10) : queryDate.getFullYear(); + + const start = new Date(year, monthIndex, 1); + const end = new Date(year, monthIndex + 1, 0, 23, 59, 59, 999); + + return { + start, + end, + confidence: monthMatch[2] ? "high" : "medium", + source: `${monthMatch[1]} ${year}`, + }; + } + + // Specific year + const yearMatch = lowerQuery.match(/\bin\s+(\d{4})\b/); + if (yearMatch) { + const year = Number.parseInt(yearMatch[1], 10); + const start = new Date(year, 0, 1); + const end = new Date(year, 11, 31, 23, 59, 59, 999); + return { start, end, confidence: "high", source: `year ${year}` }; + } + + // Recent/recently - default window + if (/\brecent(ly)?\b/.test(lowerQuery)) { + const end = new Date(queryDate); + const start = new Date(queryDate); + start.setDate(start.getDate() - this.config.defaultWindowDays); + return { start, end, confidence: "medium", source: "recently" }; + } + + // Day of week (assume most recent occurrence) + const dayMatch = lowerQuery.match( + /\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b/, + ); + if (dayMatch) { + const dayNames = [ + "sunday", + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday", + ]; + const targetDay = dayNames.indexOf(dayMatch[1]); + const currentDay = queryDate.getDay(); + let daysBack = currentDay - targetDay; + if (daysBack <= 0) daysBack += 7; + + const start = new Date(queryDate); + start.setDate(start.getDate() - daysBack); + start.setHours(0, 0, 0, 0); + const end = new Date(start); + end.setHours(23, 59, 59, 999); + + return { start, end, confidence: "medium", source: dayMatch[1] }; + } + + return undefined; + } + + /** + * Extract time range using LLM + */ + private async llmExtractTimeRange( + query: string, + queryDate: Date, + ): Promise { + const prompt = `Analyze this question and extract any time constraints. + +Question: "${query}" +Current date: ${queryDate.toISOString().split("T")[0]} + +If the question references a specific time period, return JSON with: +{ + "start": "YYYY-MM-DD", + "end": "YYYY-MM-DD", + "confidence": "high" | "medium" | "low", + "source": "what triggered this range" +} + +If no time constraint is implied, return: {"noTimeConstraint": true} + +JSON response:`; + + const response = await this.config.llm?.complete(prompt, { maxTokens: 100 }); + if (!response) return undefined; + + try { + const jsonMatch = response.text.match(/\{[\s\S]*\}/); + if (jsonMatch) { + const parsed = JSON.parse(jsonMatch[0]); + if (parsed.noTimeConstraint) { + return undefined; + } + return { + start: new Date(parsed.start), + end: new Date(parsed.end), + confidence: parsed.confidence ?? "medium", + source: parsed.source ?? "llm extraction", + }; + } + } catch { + // Fall back to heuristic + return this.heuristicTimeRange(query, queryDate); + } + + return undefined; + } + + /** + * Expand query with temporal context + */ + private expandQuery(query: string, timeRange: TimeRange | undefined, _queryDate: Date): string { + if (!timeRange) { + return query; + } + + // Add temporal context to query + const dateContext = `[Time context: ${formatDateRange(timeRange.start, timeRange.end)}]`; + return `${query}\n${dateContext}`; + } +} + +/** + * Format a date range for display + */ +function formatDateRange(start: Date, end: Date): string { + // Validate dates before formatting + if (!isValidDate(start) || !isValidDate(end)) { + return "unknown date range"; + } + + const startStr = start.toISOString().split("T")[0]; + const endStr = end.toISOString().split("T")[0]; + + if (startStr === endStr) { + return startStr; + } + + return `${startStr} to ${endStr}`; +} + +/** + * Check if a date is valid + */ +function isValidDate(date: Date): boolean { + return date instanceof Date && !Number.isNaN(date.getTime()); +} + +/** + * Quick function to analyze temporal aspects of a query + */ +export async function analyzeTemporalQuery( + query: string, + queryDate: Date, + config?: Partial, +): Promise { + const analyzer = new TemporalAnalyzer(config); + return analyzer.analyze(query, queryDate); +} + +/** + * Filter documents by time range + */ +export function filterByTimeRange( + documents: T[], + timeRange: TimeRange | { start: Date; end: Date }, +): T[] { + return documents.filter((doc) => { + const docTime = doc.validTime.getTime(); + return docTime >= timeRange.start.getTime() && docTime <= timeRange.end.getTime(); + }); +} diff --git a/packages/benchmark/src/longmemeval/types.ts b/packages/benchmark/src/longmemeval/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e8d2e5fc8804683a26ce8c7ca9f856e8b20a5a3 --- /dev/null +++ b/packages/benchmark/src/longmemeval/types.ts @@ -0,0 +1,216 @@ +import { z } from "zod"; + +/** + * LongMemEval Dataset Schema + * + * Based on the LongMemEval benchmark (ICLR 2025) + * @see https://github.com/xiaowu0162/LongMemEval + * @see https://huggingface.co/datasets/xiaowu0162/longmemeval-cleaned + */ + +/** + * Question types representing the 5 core memory abilities: + * - IE (Information Extraction): single-session-* + * - MR (Multi-Session Reasoning): multi-session + * - TR (Temporal Reasoning): temporal-reasoning + * - KU (Knowledge Update): knowledge-update + * - ABS (Abstention): indicated by _abs suffix on question_id + */ +export const QuestionTypeSchema = z.enum([ + "single-session-user", + "single-session-assistant", + "single-session-preference", + "multi-session", + "temporal-reasoning", + "knowledge-update", +]); + +export type QuestionType = z.infer; + +/** + * A single turn in a conversation (user or assistant message) + */ +export const TurnSchema = z.object({ + role: z.enum(["user", "assistant"]), + content: z.string(), + has_answer: z.boolean().optional(), +}); + +export type Turn = z.infer; + +/** + * A session is an array of turns representing a conversation + */ +export const SessionSchema = z.array(TurnSchema); + +export type Session = z.infer; + +/** + * A single evaluation instance from LongMemEval + * Note: answer field uses coerce because some answers are numeric in the dataset + */ +export const LongMemEvalInstanceSchema = z.object({ + question_id: z.string(), + question_type: QuestionTypeSchema, + question: z.string(), + answer: z.coerce.string(), // Coerce numbers to strings + question_date: z.string(), + haystack_session_ids: z.array(z.string()), + haystack_dates: z.array(z.string()), + haystack_sessions: z.array(SessionSchema), + answer_session_ids: z.array(z.string()), +}); + +export type LongMemEvalInstance = z.infer; + +/** + * The full dataset is an array of instances + */ +export const LongMemEvalDatasetSchema = z.array(LongMemEvalInstanceSchema); + +export type LongMemEvalDataset = z.infer; + +/** + * Dataset variants available + */ +export type DatasetVariant = "s" | "m" | "oracle"; + +/** + * Memory ability category derived from question type + */ +export type MemoryAbility = "IE" | "MR" | "TR" | "KU" | "ABS"; + +/** + * Maps question type to memory ability + */ +export function getMemoryAbility(questionType: QuestionType, questionId: string): MemoryAbility { + // Abstention is indicated by _abs suffix + if (questionId.endsWith("_abs")) { + return "ABS"; + } + + switch (questionType) { + case "single-session-user": + case "single-session-assistant": + case "single-session-preference": + return "IE"; + case "multi-session": + return "MR"; + case "temporal-reasoning": + return "TR"; + case "knowledge-update": + return "KU"; + } +} + +/** + * Parsed instance with normalized data types + */ +export interface ParsedInstance { + questionId: string; + questionType: QuestionType; + memoryAbility: MemoryAbility; + question: string; + answer: string; + questionDate: Date; + sessions: ParsedSession[]; + answerSessionIds: string[]; + isAbstention: boolean; +} + +/** + * Parsed session with normalized data + */ +export interface ParsedSession { + sessionId: string; + timestamp: Date; + turns: ParsedTurn[]; +} + +/** + * Parsed turn with sequence index + */ +export interface ParsedTurn { + role: "user" | "assistant"; + content: string; + hasAnswer: boolean; + sequenceIndex: number; +} + +/** + * Output format for benchmark results + */ +export interface BenchmarkResult { + questionId: string; + hypothesis: string; +} + +/** + * Evaluation output with judgment + */ +export interface EvaluatedResult extends BenchmarkResult { + answer: string; + questionType: QuestionType; + memoryAbility: MemoryAbility; + correct: boolean; + reasoning?: string; +} + +/** + * Aggregate metrics per memory ability + */ +export interface AbilityMetrics { + total: number; + correct: number; + accuracy: number; +} + +/** + * Full evaluation metrics + */ +export interface EvaluationMetrics { + overall: { + total: number; + correct: number; + accuracy: number; + }; + byAbility: Record; + retrieval?: RetrievalMetrics; + abstention?: AbstentionMetrics; +} + +/** + * Retrieval quality metrics + */ +export interface RetrievalMetrics { + /** Percentage of evidence turns retrieved */ + turnRecall: number; + /** Percentage of evidence sessions retrieved */ + sessionRecall: number; + /** Recall at different K values (1, 5, 10) */ + recallAtK: Record; + /** NDCG at different K values (1, 5, 10) - measures ranking quality */ + ndcgAtK: Record; + /** Mean Reciprocal Rank */ + mrr: number; +} + +/** + * Abstention-specific metrics + */ +export interface AbstentionMetrics { + /** True positives: correctly abstained */ + truePositives: number; + /** False positives: incorrectly abstained */ + falsePositives: number; + /** False negatives: should have abstained but didn't */ + falseNegatives: number; + /** True negatives: correctly answered */ + trueNegatives: number; + /** Precision: correct abstentions / total abstentions */ + precision: number; + /** Recall: correct abstentions / questions requiring abstention */ + recall: number; + /** F1 score: harmonic mean of precision and recall */ + f1: number; +} diff --git a/packages/benchmark/tests/core/config.test.ts b/packages/benchmark/tests/core/config.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..863a85182f35f85020cc35bf397a2153c681a6e5 --- /dev/null +++ b/packages/benchmark/tests/core/config.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; +import { buildBenchmarkConfig, DEFAULT_BENCHMARK_CONFIG } from "../../src/core/config.js"; + +describe("buildBenchmarkConfig", () => { + it("should require dataset", () => { + const config = buildBenchmarkConfig({ dataset: "/path/to/data.json" }); + expect(config.dataset).toBe("/path/to/data.json"); + }); + + it("should apply defaults for missing fields", () => { + const config = buildBenchmarkConfig({ dataset: "/path/to/data.json" }); + + expect(config.variant).toBe(DEFAULT_BENCHMARK_CONFIG.variant); + expect(config.topK).toBe(DEFAULT_BENCHMARK_CONFIG.topK); + expect(config.retriever).toBe(DEFAULT_BENCHMARK_CONFIG.retriever); + expect(config.embeddings).toBe(DEFAULT_BENCHMARK_CONFIG.embeddings); + expect(config.hybridSearch).toBe(DEFAULT_BENCHMARK_CONFIG.hybridSearch); + expect(config.rerank).toBe(DEFAULT_BENCHMARK_CONFIG.rerank); + expect(config.rerankTier).toBe(DEFAULT_BENCHMARK_CONFIG.rerankTier); + expect(config.rerankDepth).toBe(DEFAULT_BENCHMARK_CONFIG.rerankDepth); + expect(config.llm).toBe(DEFAULT_BENCHMARK_CONFIG.llm); + }); + + it("should allow overriding defaults", () => { + const config = buildBenchmarkConfig({ + dataset: "/path/to/data.json", + variant: "s", + topK: 5, + retriever: "dense", + embeddings: "qdrant", + rerank: false, + llm: "anthropic", + limit: 100, + }); + + expect(config.variant).toBe("s"); + expect(config.topK).toBe(5); + expect(config.retriever).toBe("dense"); + expect(config.embeddings).toBe("qdrant"); + expect(config.rerank).toBe(false); + expect(config.llm).toBe("anthropic"); + expect(config.limit).toBe(100); + }); + + it("should use environment variable fallback for qdrantUrl", () => { + const originalQdrantUrl = process.env.QDRANT_URL; + + process.env.QDRANT_URL = "http://qdrant.example.com:6333"; + + const config = buildBenchmarkConfig({ dataset: "/path/to/data.json" }); + expect(config.qdrantUrl).toBe("http://qdrant.example.com:6333"); + + // Restore + if (originalQdrantUrl === undefined) { + delete process.env.QDRANT_URL; + } else { + process.env.QDRANT_URL = originalQdrantUrl; + } + }); + + it("should prefer explicit option over env var", () => { + const originalQdrantUrl = process.env.QDRANT_URL; + process.env.QDRANT_URL = "http://env.example.com:6333"; + + const config = buildBenchmarkConfig({ + dataset: "/path/to/data.json", + qdrantUrl: "http://explicit.example.com:6333", + }); + + expect(config.qdrantUrl).toBe("http://explicit.example.com:6333"); + + // Restore + if (originalQdrantUrl === undefined) { + delete process.env.QDRANT_URL; + } else { + process.env.QDRANT_URL = originalQdrantUrl; + } + }); + + it("should configure multi-query settings", () => { + const config = buildBenchmarkConfig({ + dataset: "/path/to/data.json", + multiQuery: true, + multiQueryVariations: 5, + }); + + expect(config.multiQuery).toBe(true); + expect(config.multiQueryVariations).toBe(5); + }); + + it("should configure abstention settings", () => { + const config = buildBenchmarkConfig({ + dataset: "/path/to/data.json", + abstention: true, + abstentionThreshold: 0.5, + }); + + expect(config.abstention).toBe(true); + expect(config.abstentionThreshold).toBe(0.5); + }); + + it("should configure session-aware settings", () => { + const config = buildBenchmarkConfig({ + dataset: "/path/to/data.json", + sessionAware: true, + topSessions: 10, + turnsPerSession: 5, + }); + + expect(config.sessionAware).toBe(true); + expect(config.topSessions).toBe(10); + expect(config.turnsPerSession).toBe(5); + }); + + it("should configure temporal settings", () => { + const config = buildBenchmarkConfig({ + dataset: "/path/to/data.json", + temporalAware: true, + temporalConfidenceThreshold: 0.9, + }); + + expect(config.temporalAware).toBe(true); + expect(config.temporalConfidenceThreshold).toBe(0.9); + }); +}); + +describe("DEFAULT_BENCHMARK_CONFIG", () => { + it("should have sensible defaults", () => { + expect(DEFAULT_BENCHMARK_CONFIG.variant).toBe("oracle"); + expect(DEFAULT_BENCHMARK_CONFIG.topK).toBe(10); + expect(DEFAULT_BENCHMARK_CONFIG.retriever).toBe("hybrid"); + expect(DEFAULT_BENCHMARK_CONFIG.embeddings).toBe("engram"); + expect(DEFAULT_BENCHMARK_CONFIG.hybridSearch).toBe(true); + expect(DEFAULT_BENCHMARK_CONFIG.rerank).toBe(true); + expect(DEFAULT_BENCHMARK_CONFIG.rerankTier).toBe("accurate"); + expect(DEFAULT_BENCHMARK_CONFIG.rerankDepth).toBe(30); + expect(DEFAULT_BENCHMARK_CONFIG.llm).toBe("stub"); + }); +}); diff --git a/packages/benchmark/tests/core/latency.test.ts b/packages/benchmark/tests/core/latency.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe4ebc15171088e2d5a0441d0b838d748313b011 --- /dev/null +++ b/packages/benchmark/tests/core/latency.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, it } from "vitest"; +import type { LatencyMetrics } from "../../src/longmemeval/pipeline.js"; + +/** + * Helper to compute latency metrics (mirrors the private function in pipeline.ts) + */ +function computeLatencyMetrics(latencies: number[], totalDurationMs: number): LatencyMetrics { + if (latencies.length === 0) { + return { + perQueryLatencies: [], + p50: 0, + p95: 0, + p99: 0, + mean: 0, + totalDurationMs, + }; + } + + const sorted = [...latencies].sort((a, b) => a - b); + const len = sorted.length; + + const p50Index = Math.floor(len * 0.5); + const p95Index = Math.min(Math.floor(len * 0.95), len - 1); + const p99Index = Math.min(Math.floor(len * 0.99), len - 1); + + const sum = latencies.reduce((acc, val) => acc + val, 0); + const mean = sum / len; + + return { + perQueryLatencies: latencies, + p50: sorted[p50Index], + p95: sorted[p95Index], + p99: sorted[p99Index], + mean: Math.round(mean), + totalDurationMs, + }; +} + +describe("computeLatencyMetrics", () => { + it("should return zeros for empty array", () => { + const result = computeLatencyMetrics([], 1000); + + expect(result.p50).toBe(0); + expect(result.p95).toBe(0); + expect(result.p99).toBe(0); + expect(result.mean).toBe(0); + expect(result.perQueryLatencies).toEqual([]); + expect(result.totalDurationMs).toBe(1000); + }); + + it("should compute correct percentiles for 100 uniform samples", () => { + // Create 100 samples from 1 to 100 + const latencies = Array.from({ length: 100 }, (_, i) => i + 1); + + const result = computeLatencyMetrics(latencies, 5000); + + // p50 should be around 50 + expect(result.p50).toBe(51); // floor(100 * 0.5) = 50, sorted[50] = 51 + // p95 should be around 95 + expect(result.p95).toBe(96); // floor(100 * 0.95) = 95, sorted[95] = 96 + // p99 should be around 99 + expect(result.p99).toBe(100); // floor(100 * 0.99) = 99, sorted[99] = 100 + // mean should be 50.5 + expect(result.mean).toBe(51); // (1+100)/2 = 50.5, rounded = 51 + }); + + it("should handle single element", () => { + const result = computeLatencyMetrics([42], 100); + + expect(result.p50).toBe(42); + expect(result.p95).toBe(42); + expect(result.p99).toBe(42); + expect(result.mean).toBe(42); + }); + + it("should handle two elements", () => { + const result = computeLatencyMetrics([10, 20], 100); + + // With 2 elements, floor(2 * 0.5) = 1, sorted[1] = 20 + expect(result.p50).toBe(20); + // floor(2 * 0.95) = 1, sorted[1] = 20 + expect(result.p95).toBe(20); + // floor(2 * 0.99) = 1, sorted[1] = 20 + expect(result.p99).toBe(20); + expect(result.mean).toBe(15); + }); + + it("should preserve original latencies", () => { + const latencies = [100, 50, 200, 150]; + + const result = computeLatencyMetrics(latencies, 500); + + expect(result.perQueryLatencies).toEqual(latencies); + }); + + it("should sort correctly for percentile computation", () => { + // Out of order latencies + const latencies = [500, 100, 300, 200, 400]; + + const result = computeLatencyMetrics(latencies, 1000); + + // Sorted: [100, 200, 300, 400, 500] + // p50: floor(5 * 0.5) = 2, sorted[2] = 300 + expect(result.p50).toBe(300); + // p95: min(floor(5 * 0.95), 4) = min(4, 4) = 4, sorted[4] = 500 + expect(result.p95).toBe(500); + // p99: min(floor(5 * 0.99), 4) = min(4, 4) = 4, sorted[4] = 500 + expect(result.p99).toBe(500); + }); + + it("should correctly compute mean with varying values", () => { + const latencies = [10, 20, 30, 40, 50]; + const expectedMean = (10 + 20 + 30 + 40 + 50) / 5; // 30 + + const result = computeLatencyMetrics(latencies, 1000); + + expect(result.mean).toBe(expectedMean); + }); + + it("should round mean to integer", () => { + const latencies = [10, 11, 12]; // mean = 11 + const result = computeLatencyMetrics(latencies, 100); + expect(result.mean).toBe(11); + + const latencies2 = [10, 11]; // mean = 10.5 + const result2 = computeLatencyMetrics(latencies2, 100); + expect(result2.mean).toBe(11); // rounded up + }); +}); + +describe("LatencyMetrics interface", () => { + it("should have all required fields", () => { + const metrics: LatencyMetrics = { + perQueryLatencies: [10, 20, 30], + p50: 20, + p95: 30, + p99: 30, + mean: 20, + totalDurationMs: 100, + }; + + expect(metrics.perQueryLatencies).toHaveLength(3); + expect(metrics.p50).toBeDefined(); + expect(metrics.p95).toBeDefined(); + expect(metrics.p99).toBeDefined(); + expect(metrics.mean).toBeDefined(); + expect(metrics.totalDurationMs).toBeDefined(); + }); +}); diff --git a/packages/benchmark/tests/evaluator.test.ts b/packages/benchmark/tests/evaluator.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f68e5791a9fe6e88289cde0fd036dfb4ba90fb76 --- /dev/null +++ b/packages/benchmark/tests/evaluator.test.ts @@ -0,0 +1,421 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_EVALUATOR_CONFIG, + Evaluator, + formatMetricsReport, + parseJsonlResults, + type RetrievalData, + resultsToJsonl, +} from "../src/longmemeval/evaluator.js"; +import type { LLMProvider, LLMResponse } from "../src/longmemeval/reader.js"; +import type { BenchmarkResult, MemoryAbility, ParsedInstance } from "../src/longmemeval/types.js"; + +const createMockInstance = ( + questionId: string, + answer: string, + memoryAbility: MemoryAbility = "IE", +): ParsedInstance => ({ + questionId, + questionType: "single-session-user", + memoryAbility, + question: `Question for ${questionId}`, + answer, + questionDate: new Date("2024-03-15"), + sessions: [], + answerSessionIds: [], + isAbstention: memoryAbility === "ABS", +}); + +const createMockResult = (questionId: string, hypothesis: string): BenchmarkResult => ({ + questionId, + hypothesis, +}); + +describe("Evaluator", () => { + describe("string matching", () => { + const evaluator = new Evaluator({ strictMatching: false }); + + it("should match exact answers", async () => { + const instance = createMockInstance("q1", "blue"); + const result = createMockResult("q1", "blue"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(true); + }); + + it("should match case-insensitive", async () => { + const instance = createMockInstance("q1", "Blue"); + const result = createMockResult("q1", "BLUE"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(true); + }); + + it("should match answer contained in hypothesis", async () => { + const instance = createMockInstance("q1", "blue"); + const result = createMockResult("q1", "The color is blue."); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(true); + }); + + it("should match hypothesis contained in answer", async () => { + const instance = createMockInstance("q1", "The user's favorite color is blue"); + const result = createMockResult("q1", "blue"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(true); + }); + + it("should match with word overlap", async () => { + const instance = createMockInstance("q1", "favorite color blue"); + const result = createMockResult("q1", "blue is the favorite color"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(true); + }); + + it("should not match unrelated answers", async () => { + const instance = createMockInstance("q1", "blue"); + const result = createMockResult("q1", "red"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(false); + }); + }); + + describe("strict matching", () => { + const evaluator = new Evaluator({ strictMatching: true }); + + it("should require exact match", async () => { + const instance = createMockInstance("q1", "blue"); + const result = createMockResult("q1", "Blue"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + // Still matches because normalization lowercases + expect(evaluated[0].correct).toBe(true); + }); + + it("should not match partial answers in strict mode", async () => { + const instance = createMockInstance("q1", "blue"); + const result = createMockResult("q1", "The color is blue"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(false); + }); + }); + + describe("per-ability metrics", () => { + it("should compute metrics by memory ability", async () => { + const evaluator = new Evaluator(); + const instances = [ + createMockInstance("q1", "blue", "IE"), + createMockInstance("q2", "red", "IE"), + createMockInstance("q3", "2023", "TR"), + createMockInstance("q4", "I don't know", "ABS"), // Match the expected response + ]; + + const results = [ + createMockResult("q1", "blue"), // correct IE + createMockResult("q2", "green"), // wrong IE + createMockResult("q3", "2023"), // correct TR + createMockResult("q4", "I don't know"), // correct ABS + ]; + + const { metrics } = await evaluator.evaluateAll(results, instances); + + expect(metrics.byAbility.IE.total).toBe(2); + expect(metrics.byAbility.IE.correct).toBe(1); + expect(metrics.byAbility.IE.accuracy).toBe(0.5); + + expect(metrics.byAbility.TR.total).toBe(1); + expect(metrics.byAbility.TR.correct).toBe(1); + expect(metrics.byAbility.TR.accuracy).toBe(1); + + expect(metrics.overall.total).toBe(4); + expect(metrics.overall.correct).toBe(3); + }); + }); + + describe("LLM-based evaluation", () => { + class MockLLMJudge implements LLMProvider { + async complete(prompt: string): Promise { + // Simple mock that checks if "blue" is in both + if (prompt.includes("blue") && prompt.includes("Generated Answer")) { + return { text: "CORRECT" }; + } + return { text: "INCORRECT" }; + } + } + + it("should use LLM for evaluation when enabled", async () => { + const llm = new MockLLMJudge(); + const evaluator = new Evaluator({ useLLMEvaluation: true }, llm); + + const instance = createMockInstance("q1", "blue"); + const result = createMockResult("q1", "The color is blue"); + + const { evaluated } = await evaluator.evaluateAll([result], [instance]); + + expect(evaluated[0].correct).toBe(true); + }); + + it("should use GPT-4o prompt by default", () => { + expect(DEFAULT_EVALUATOR_CONFIG.useGPT4oPrompt).toBe(true); + }); + }); + + describe("NDCG computation", () => { + it("should compute NDCG for perfect ranking", async () => { + const evaluator = new Evaluator({ kValues: [3, 5] }); + + const retrievalData: RetrievalData[] = [ + { + questionId: "q1", + retrievedIds: ["doc1", "doc2", "doc3"], + scores: [0.9, 0.8, 0.7], + evidenceIds: ["doc1", "doc2"], + }, + ]; + + const { metrics } = await evaluator.evaluateAll( + [createMockResult("q1", "answer")], + [createMockInstance("q1", "answer")], + retrievalData, + ); + + // Perfect ranking - NDCG should be 1 + expect(metrics.retrieval?.ndcgAtK[3]).toBe(1); + }); + + it("should compute lower NDCG for imperfect ranking", async () => { + const evaluator = new Evaluator({ kValues: [3] }); + + const retrievalData: RetrievalData[] = [ + { + questionId: "q1", + retrievedIds: ["irrelevant", "doc1", "doc2"], + scores: [0.9, 0.8, 0.7], + evidenceIds: ["doc1", "doc2"], + }, + ]; + + const { metrics } = await evaluator.evaluateAll( + [createMockResult("q1", "answer")], + [createMockInstance("q1", "answer")], + retrievalData, + ); + + // Imperfect ranking - NDCG should be less than 1 + expect(metrics.retrieval?.ndcgAtK[3]).toBeLessThan(1); + expect(metrics.retrieval?.ndcgAtK[3]).toBeGreaterThan(0); + }); + + it("should compute MRR correctly", async () => { + const evaluator = new Evaluator({ kValues: [5] }); + + const retrievalData: RetrievalData[] = [ + { + questionId: "q1", + retrievedIds: ["x", "x", "doc1", "x", "x"], + scores: [0.9, 0.8, 0.7, 0.6, 0.5], + evidenceIds: ["doc1"], + }, + ]; + + const { metrics } = await evaluator.evaluateAll( + [createMockResult("q1", "answer")], + [createMockInstance("q1", "answer")], + retrievalData, + ); + + // First relevant at position 3, so MRR = 1/3 + expect(metrics.retrieval?.mrr).toBeCloseTo(1 / 3); + }); + + it("should compute Recall@K correctly", async () => { + const evaluator = new Evaluator({ kValues: [1, 5, 10] }); + + const retrievalData: RetrievalData[] = [ + { + questionId: "q1", + retrievedIds: ["doc1", "x", "doc2", "x", "doc3", "x", "x", "x", "x", "x"], + scores: [0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.45], + evidenceIds: ["doc1", "doc2", "doc3", "doc4"], // 4 evidence docs + }, + ]; + + const { metrics } = await evaluator.evaluateAll( + [createMockResult("q1", "answer")], + [createMockInstance("q1", "answer")], + retrievalData, + ); + + // Recall@1 = 1/4 (only doc1 in top 1) + expect(metrics.retrieval?.recallAtK[1]).toBe(0.25); + // Recall@5 = 3/4 (doc1, doc2, doc3 in top 5) + expect(metrics.retrieval?.recallAtK[5]).toBe(0.75); + // Recall@10 = 3/4 (still only 3 found) + expect(metrics.retrieval?.recallAtK[10]).toBe(0.75); + }); + }); + + describe("abstention metrics", () => { + it("should compute abstention precision and recall", async () => { + const evaluator = new Evaluator(); + + const instances = [ + createMockInstance("q1", "unknown", "ABS"), + createMockInstance("q2", "unknown", "ABS"), + createMockInstance("q3", "blue", "IE"), + createMockInstance("q4", "red", "IE"), + ]; + + const results = [ + createMockResult("q1", "I don't know"), + createMockResult("q2", "Some answer"), // Wrong - should abstain + createMockResult("q3", "I don't know"), // Wrong - shouldn't abstain + createMockResult("q4", "red"), + ]; + + const abstentionFlags = new Map([ + ["q1", true], // Correctly abstained + ["q2", false], // Should have abstained + ["q3", true], // Incorrectly abstained + ["q4", false], // Correctly answered + ]); + + const { metrics } = await evaluator.evaluateAll( + results, + instances, + undefined, + abstentionFlags, + ); + + expect(metrics.abstention).toBeDefined(); + expect(metrics.abstention?.truePositives).toBe(1); // q1 + expect(metrics.abstention?.falseNegatives).toBe(1); // q2 + expect(metrics.abstention?.falsePositives).toBe(1); // q3 + expect(metrics.abstention?.trueNegatives).toBe(1); // q4 + + // Precision = TP / (TP + FP) = 1 / 2 = 0.5 + expect(metrics.abstention?.precision).toBe(0.5); + // Recall = TP / (TP + FN) = 1 / 2 = 0.5 + expect(metrics.abstention?.recall).toBe(0.5); + // F1 = 2 * P * R / (P + R) = 0.5 + expect(metrics.abstention?.f1).toBe(0.5); + }); + }); +}); + +describe("formatMetricsReport", () => { + it("should format basic metrics", () => { + const metrics = { + overall: { total: 10, correct: 7, accuracy: 0.7 }, + byAbility: { + IE: { total: 4, correct: 3, accuracy: 0.75 }, + MR: { total: 2, correct: 1, accuracy: 0.5 }, + TR: { total: 2, correct: 2, accuracy: 1 }, + KU: { total: 1, correct: 0, accuracy: 0 }, + ABS: { total: 1, correct: 1, accuracy: 1 }, + }, + }; + + const report = formatMetricsReport(metrics); + + expect(report).toContain("LongMemEval Benchmark Results"); + expect(report).toContain("70.0%"); + expect(report).toContain("Information Extraction"); + }); + + it("should include retrieval metrics when present", () => { + const metrics = { + overall: { total: 10, correct: 7, accuracy: 0.7 }, + byAbility: { + IE: { total: 10, correct: 7, accuracy: 0.7 }, + MR: { total: 0, correct: 0, accuracy: 0 }, + TR: { total: 0, correct: 0, accuracy: 0 }, + KU: { total: 0, correct: 0, accuracy: 0 }, + ABS: { total: 0, correct: 0, accuracy: 0 }, + }, + retrieval: { + turnRecall: 0.8, + sessionRecall: 0.85, + recallAtK: { 1: 0.5, 5: 0.7, 10: 0.8 }, + ndcgAtK: { 1: 0.5, 5: 0.65, 10: 0.75 }, + mrr: 0.6, + }, + }; + + const report = formatMetricsReport(metrics); + + expect(report).toContain("Retrieval Metrics"); + expect(report).toContain("Turn Recall"); + expect(report).toContain("NDCG@K"); + expect(report).toContain("MRR"); + }); + + it("should include abstention metrics when present", () => { + const metrics = { + overall: { total: 10, correct: 7, accuracy: 0.7 }, + byAbility: { + IE: { total: 10, correct: 7, accuracy: 0.7 }, + MR: { total: 0, correct: 0, accuracy: 0 }, + TR: { total: 0, correct: 0, accuracy: 0 }, + KU: { total: 0, correct: 0, accuracy: 0 }, + ABS: { total: 0, correct: 0, accuracy: 0 }, + }, + abstention: { + truePositives: 5, + falsePositives: 2, + falseNegatives: 1, + trueNegatives: 12, + precision: 0.714, + recall: 0.833, + f1: 0.769, + }, + }; + + const report = formatMetricsReport(metrics); + + expect(report).toContain("Abstention Metrics"); + expect(report).toContain("Precision"); + expect(report).toContain("Recall"); + expect(report).toContain("F1 Score"); + expect(report).toContain("Confusion Matrix"); + }); +}); + +describe("JSONL utilities", () => { + it("should convert results to JSONL", () => { + const results: BenchmarkResult[] = [ + { questionId: "q1", hypothesis: "blue" }, + { questionId: "q2", hypothesis: "red" }, + ]; + + const jsonl = resultsToJsonl(results); + + expect(jsonl).toContain("q1"); + expect(jsonl).toContain("blue"); + expect(jsonl.split("\n")).toHaveLength(2); + }); + + it("should parse JSONL to results", () => { + const jsonl = `{"question_id": "q1", "hypothesis": "blue"} +{"question_id": "q2", "hypothesis": "red"}`; + + const results = parseJsonlResults(jsonl); + + expect(results).toHaveLength(2); + expect(results[0].questionId).toBe("q1"); + expect(results[0].hypothesis).toBe("blue"); + }); +}); diff --git a/packages/benchmark/tests/key-expansion.test.ts b/packages/benchmark/tests/key-expansion.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b05a98dab7a29b3285bdf3cb59c4e32381471b0f --- /dev/null +++ b/packages/benchmark/tests/key-expansion.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "vitest"; +import { expandDocuments, KeyExpander } from "../src/longmemeval/key-expansion.js"; +import type { EngramDocument } from "../src/longmemeval/mapper.js"; + +const createMockDocument = (content: string, id = "test-1"): EngramDocument => ({ + id, + instanceId: "instance-1", + sessionId: "session-1", + content, + validTime: new Date("2024-03-15T10:00:00Z"), + metadata: { + questionId: "q1", + role: "user", + hasAnswer: false, + sessionIndex: 0, + }, +}); + +describe("Key Expansion", () => { + describe("KeyExpander", () => { + const expander = new KeyExpander({ types: ["keyphrase", "userfact"] }); + + it("should expand a document", async () => { + const doc = createMockDocument( + "My favorite color is blue and I work as a software engineer.", + ); + const expanded = await expander.expand(doc); + + expect(expanded.originalContent).toBe(doc.content); + expect(expanded.expandedContent).toContain(doc.content); + expect(expanded.expansion).toBeDefined(); + }); + + it("should extract keyphrases", async () => { + const doc = createMockDocument( + "I went to the doctor yesterday for my annual checkup. The appointment went well.", + ); + const expanded = await expander.expand(doc); + + expect(expanded.expansion.keyphrases).toBeDefined(); + expect(expanded.expansion.keyphrases?.length).toBeGreaterThan(0); + }); + + it("should extract user facts", async () => { + const doc = createMockDocument("My favorite color is blue. I am a software engineer."); + const expanded = await expander.expand(doc); + + expect(expanded.expansion.userFacts).toBeDefined(); + // Should extract facts about color and occupation + const facts = expanded.expansion.userFacts?.join(" ").toLowerCase(); + expect(facts).toMatch(/favorite|color|blue|engineer/); + }); + + it("should include expansion in content", async () => { + const doc = createMockDocument("I love programming in TypeScript."); + const expanded = await expander.expand(doc); + + expect(expanded.expandedContent).toContain("[Keywords:"); + }); + }); + + describe("KeyExpander with summary", () => { + const expander = new KeyExpander({ types: ["summary"] }); + + it("should extract summary", async () => { + const doc = createMockDocument( + "Yesterday I went to the grocery store and bought some vegetables. " + + "I was looking for organic produce but they were out of most items. " + + "Finally found some carrots and spinach.", + ); + const expanded = await expander.expand(doc); + + expect(expanded.expansion.summary).toBeDefined(); + expect(expanded.expansion.summary?.length).toBeLessThan(doc.content.length); + }); + }); + + describe("KeyExpander with events", () => { + const expander = new KeyExpander({ types: ["event"] }); + + it("should extract events", async () => { + const doc = createMockDocument( + "I visited the doctor on Monday. Then I went shopping yesterday.", + ); + const expanded = await expander.expand(doc); + + expect(expanded.expansion.events).toBeDefined(); + }); + }); + + describe("expandDocuments helper", () => { + it("should expand batch of documents", async () => { + const docs = [ + createMockDocument("My favorite food is pizza.", "doc-1"), + createMockDocument("I work at a tech company.", "doc-2"), + ]; + + const expanded = await expandDocuments(docs, { types: ["keyphrase"] }); + + expect(expanded).toHaveLength(2); + expect(expanded[0].id).toBe("doc-1"); + expect(expanded[1].id).toBe("doc-2"); + }); + }); +}); diff --git a/packages/benchmark/tests/loader.test.ts b/packages/benchmark/tests/loader.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0fdc6b176fbb2da9eab5cc82c2ee15cb26949ae --- /dev/null +++ b/packages/benchmark/tests/loader.test.ts @@ -0,0 +1,127 @@ +import { mkdir, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { beforeAll, describe, expect, it } from "vitest"; +import { loadDataset, validateDataset } from "../src/longmemeval/loader.js"; +import type { LongMemEvalInstance } from "../src/longmemeval/types.js"; + +const TEST_DIR = join(import.meta.dirname, ".test-data"); + +// Sample test instance matching LongMemEval schema +const sampleInstance: LongMemEvalInstance = { + question_id: "test_001", + question_type: "single-session-user", + question: "What is the user's favorite color?", + answer: "blue", + question_date: "2024-03-15T10:00:00Z", + haystack_session_ids: ["session_1", "session_2"], + haystack_dates: ["2024-03-01T09:00:00Z", "2024-03-10T14:00:00Z"], + haystack_sessions: [ + [ + { role: "user", content: "My favorite color is blue." }, + { role: "assistant", content: "That's a nice color!" }, + ], + [ + { role: "user", content: "I went to the store today.", has_answer: false }, + { role: "assistant", content: "What did you buy?" }, + ], + ], + answer_session_ids: ["session_1"], +}; + +const sampleInstanceAbstention: LongMemEvalInstance = { + question_id: "test_002_abs", + question_type: "single-session-user", + question: "What is the user's favorite food?", + answer: "Not mentioned", + question_date: "2024-03-15T10:00:00Z", + haystack_session_ids: ["session_1"], + haystack_dates: ["2024-03-01T09:00:00Z"], + haystack_sessions: [ + [ + { role: "user", content: "My favorite color is blue." }, + { role: "assistant", content: "That's a nice color!" }, + ], + ], + answer_session_ids: [], +}; + +const sampleDataset = [sampleInstance, sampleInstanceAbstention]; + +describe("LongMemEval Loader", () => { + beforeAll(async () => { + // Create test directory and sample dataset + await mkdir(TEST_DIR, { recursive: true }); + await writeFile(join(TEST_DIR, "test_dataset.json"), JSON.stringify(sampleDataset)); + }); + + it("should load and parse a valid dataset", async () => { + const result = await loadDataset({ + datasetPath: join(TEST_DIR, "test_dataset.json"), + }); + + expect(result.instances).toHaveLength(2); + expect(result.stats.totalInstances).toBe(2); + }); + + it("should correctly identify memory abilities", async () => { + const result = await loadDataset({ + datasetPath: join(TEST_DIR, "test_dataset.json"), + }); + + const instance1 = result.instances[0]; + expect(instance1.memoryAbility).toBe("IE"); + expect(instance1.isAbstention).toBe(false); + + const instance2 = result.instances[1]; + expect(instance2.memoryAbility).toBe("ABS"); + expect(instance2.isAbstention).toBe(true); + }); + + it("should parse timestamps correctly", async () => { + const result = await loadDataset({ + datasetPath: join(TEST_DIR, "test_dataset.json"), + }); + + const instance = result.instances[0]; + expect(instance.questionDate).toBeInstanceOf(Date); + expect(instance.sessions[0].timestamp).toBeInstanceOf(Date); + }); + + it("should compute correct statistics", async () => { + const result = await loadDataset({ + datasetPath: join(TEST_DIR, "test_dataset.json"), + }); + + expect(result.stats.totalSessions).toBe(3); // 2 + 1 sessions + expect(result.stats.totalTurns).toBe(6); // 2 + 2 + 2 turns + expect(result.stats.abstentionCount).toBe(1); + expect(result.stats.byAbility.IE).toBe(1); + expect(result.stats.byAbility.ABS).toBe(1); + }); + + it("should apply limit filter", async () => { + const result = await loadDataset({ + datasetPath: join(TEST_DIR, "test_dataset.json"), + limit: 1, + }); + + expect(result.instances).toHaveLength(1); + }); + + it("should validate a valid dataset", async () => { + const result = await validateDataset(join(TEST_DIR, "test_dataset.json")); + expect(result.valid).toBe(true); + expect(result.stats).toBeDefined(); + }); + + it("should fail validation for invalid file", async () => { + const result = await validateDataset(join(TEST_DIR, "nonexistent.json")); + expect(result.valid).toBe(false); + expect(result.error).toBeDefined(); + }); +}); + +// Cleanup after all tests +afterAll(async () => { + await rm(TEST_DIR, { recursive: true, force: true }); +}); diff --git a/packages/benchmark/tests/mapper.test.ts b/packages/benchmark/tests/mapper.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddbacd1f7fd6695be2122763d0c0d76fbeba22f8 --- /dev/null +++ b/packages/benchmark/tests/mapper.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_MAPPER_CONFIG, + formatDocumentsForContext, + groupBySession, + mapInstance, +} from "../src/longmemeval/mapper.js"; +import type { ParsedInstance } from "../src/longmemeval/types.js"; + +const createMockInstance = (overrides?: Partial): ParsedInstance => ({ + questionId: "test_001", + questionType: "single-session-user", + memoryAbility: "IE", + question: "What is the user's favorite color?", + answer: "blue", + questionDate: new Date("2024-03-15T10:00:00Z"), + sessions: [ + { + sessionId: "session_1", + timestamp: new Date("2024-03-01T09:00:00Z"), + turns: [ + { role: "user", content: "My favorite color is blue.", hasAnswer: true, sequenceIndex: 0 }, + { role: "assistant", content: "That's nice!", hasAnswer: false, sequenceIndex: 1 }, + ], + }, + { + sessionId: "session_2", + timestamp: new Date("2024-03-10T14:00:00Z"), + turns: [ + { role: "user", content: "Going to the store.", hasAnswer: false, sequenceIndex: 0 }, + { role: "assistant", content: "What for?", hasAnswer: false, sequenceIndex: 1 }, + ], + }, + ], + answerSessionIds: ["session_1"], + isAbstention: false, + ...overrides, +}); + +describe("LongMemEval Mapper", () => { + describe("mapInstance", () => { + it("should map instance to documents with turn granularity", () => { + const instance = createMockInstance(); + const result = mapInstance(instance, { ...DEFAULT_MAPPER_CONFIG, granularity: "turn" }); + + // With includeAssistant=true, should have 4 turns total + expect(result.documents).toHaveLength(4); + expect(result.instance).toBe(instance); + }); + + it("should map instance to documents with session granularity", () => { + const instance = createMockInstance(); + const result = mapInstance(instance, { granularity: "session", includeAssistant: true }); + + // Should have 2 sessions + expect(result.documents).toHaveLength(2); + }); + + it("should filter out assistant turns when includeAssistant is false", () => { + const instance = createMockInstance(); + const result = mapInstance(instance, { granularity: "turn", includeAssistant: false }); + + // Should only have user turns (2 total) + expect(result.documents).toHaveLength(2); + expect(result.documents.every((d) => d.metadata.role === "user")).toBe(true); + }); + + it("should correctly identify evidence documents", () => { + const instance = createMockInstance(); + const result = mapInstance(instance); + + expect(result.evidenceDocIds.length).toBeGreaterThan(0); + + // Find the evidence document + const evidenceDoc = result.documents.find((d) => d.metadata.hasAnswer); + expect(evidenceDoc).toBeDefined(); + expect(evidenceDoc?.content).toContain("blue"); + }); + + it("should set valid time correctly", () => { + const instance = createMockInstance(); + const result = mapInstance(instance); + + const doc = result.documents[0]; + expect(doc.validTime).toEqual(instance.sessions[0].timestamp); + }); + }); + + describe("formatDocumentsForContext", () => { + it("should format documents as JSON", () => { + const instance = createMockInstance(); + const { documents } = mapInstance(instance); + + const formatted = formatDocumentsForContext(documents.slice(0, 2)); + const parsed = JSON.parse(formatted); + + expect(Array.isArray(parsed)).toBe(true); + expect(parsed[0]).toHaveProperty("index"); + expect(parsed[0]).toHaveProperty("content"); + expect(parsed[0]).toHaveProperty("date"); + }); + + it("should respect maxLength option", () => { + const instance = createMockInstance(); + const { documents } = mapInstance(instance); + + const formatted = formatDocumentsForContext(documents, { maxLength: 50 }); + expect(formatted.length).toBeLessThanOrEqual(70); // 50 + truncation message + expect(formatted).toContain("truncated"); + }); + }); + + describe("groupBySession", () => { + it("should group documents by session ID", () => { + const instance = createMockInstance(); + const { documents } = mapInstance(instance); + + const groups = groupBySession(documents); + + expect(groups.size).toBe(2); + expect(groups.get("session_1")).toBeDefined(); + expect(groups.get("session_2")).toBeDefined(); + }); + }); +}); diff --git a/packages/benchmark/tests/reader.test.ts b/packages/benchmark/tests/reader.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f14ad3a11f2f53c6cc53cc1f9ac1206ccb8a4ad1 --- /dev/null +++ b/packages/benchmark/tests/reader.test.ts @@ -0,0 +1,309 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import type { EngramDocument } from "../src/longmemeval/mapper.js"; +import { + DEFAULT_READER_CONFIG, + MockLLMProvider, + Reader, + StubLLMProvider, +} from "../src/longmemeval/reader.js"; + +const createMockDocument = ( + content: string, + id: string, + date: Date = new Date("2024-03-15"), +): EngramDocument => ({ + id, + instanceId: "instance-1", + sessionId: "session-1", + content, + validTime: date, + metadata: { + questionId: "q1", + role: "user", + hasAnswer: false, + sessionIndex: 0, + }, +}); + +describe("Reader", () => { + describe("with StubLLMProvider", () => { + it("should generate an answer with default config", async () => { + const llm = new StubLLMProvider(); + const reader = new Reader(llm); + + const docs = [createMockDocument("My favorite color is blue.", "doc-1")]; + const result = await reader.read("What is my favorite color?", docs); + + expect(result.hypothesis).toBeDefined(); + expect(result.abstained).toBe(true); // Stub returns low confidence + }); + + it("should use canned responses when set", async () => { + const llm = new StubLLMProvider(); + llm.setResponse( + "favorite color", + `\`\`\`json +{ + "key_information": ["User stated favorite color is blue"], + "reasoning_steps": ["Found direct statement about color preference"], + "answer": "blue", + "confidence": 0.95, + "answerable": true +} +\`\`\``, + ); + + const reader = new Reader(llm); + const docs = [createMockDocument("My favorite color is blue.", "doc-1")]; + const result = await reader.read("What is my favorite color?", docs); + + expect(result.hypothesis).toBe("blue"); + expect(result.keyInformation).toContain("User stated favorite color is blue"); + expect(result.abstained).toBe(false); + }); + }); + + describe("with MockLLMProvider", () => { + let llm: MockLLMProvider; + let reader: Reader; + + beforeEach(() => { + llm = new MockLLMProvider(); + reader = new Reader(llm); + }); + + it("should parse JSON responses correctly", async () => { + llm.setFixedResponse({ + key_information: ["fact1", "fact2"], + reasoning_steps: ["step1", "step2"], + answer: "The answer is 42", + confidence: 0.9, + answerable: true, + }); + + const docs = [createMockDocument("Some context", "doc-1")]; + const result = await reader.read("What is the answer?", docs); + + expect(result.hypothesis).toBe("The answer is 42"); + expect(result.keyInformation).toEqual(["fact1", "fact2"]); + expect(result.reasoning).toBe("step1 → step2"); + expect(result.abstained).toBe(false); + }); + + it("should detect abstention when answerable is false", async () => { + llm.setFixedResponse({ + key_information: [], + reasoning_steps: ["No relevant information found"], + answer: "Cannot determine", + confidence: 0.1, + answerable: false, + }); + + const docs = [createMockDocument("Unrelated content", "doc-1")]; + const result = await reader.read("What is my phone number?", docs); + + expect(result.abstained).toBe(true); + expect(result.confidence).toBeLessThan(0.3); + }); + }); + + describe("confidence calibration", () => { + it("should return low confidence when no documents", async () => { + const llm = new MockLLMProvider(); + llm.setConfidenceOverride(0.8); + + const reader = new Reader(llm); + const result = await reader.read("What is X?", [], new Date()); + + expect(result.confidence).toBeLessThan(0.5); + }); + + it("should incorporate retrieval scores in confidence", async () => { + const llm = new MockLLMProvider(); + llm.setFixedResponse({ + answer: "test", + confidence: 0.8, + answerable: true, + }); + + const reader = new Reader(llm); + const docs = [ + createMockDocument("Relevant content", "doc-1"), + createMockDocument("More content", "doc-2"), + ]; + + // High retrieval score + const highScoreResult = await reader.read("Test?", docs, new Date(), [0.95, 0.8]); + + // Low retrieval score + const lowScoreResult = await reader.read("Test?", docs, new Date(), [0.3, 0.2]); + + expect(highScoreResult.confidence).toBeGreaterThan(lowScoreResult.confidence ?? 0); + }); + + it("should have confidence signals in result", async () => { + const llm = new MockLLMProvider(); + const reader = new Reader(llm); + const docs = [createMockDocument("Content", "doc-1")]; + + const result = await reader.read("Question?", docs, new Date(), [0.7]); + + expect(result.confidenceSignals).toBeDefined(); + expect(result.confidenceSignals?.hasRelevantDocs).toBe(true); + expect(result.confidenceSignals?.topDocRelevance).toBe(0.7); + expect(result.confidenceSignals?.supportingDocCount).toBe(1); + }); + }); + + describe("enhanced Chain-of-Note", () => { + it("should use enhanced prompt by default", async () => { + const llm = new MockLLMProvider(); + const reader = new Reader(llm); + + expect(DEFAULT_READER_CONFIG.enhancedChainOfNote).toBe(true); + + const docs = [createMockDocument("Test content", "doc-1")]; + const result = await reader.read("Test question?", docs); + + // Should have structured output + expect(result.keyInformation).toBeDefined(); + }); + + it("should fall back to basic Chain-of-Note when enhanced disabled", async () => { + const llm = new MockLLMProvider(); + const reader = new Reader(llm, { enhancedChainOfNote: false }); + + const docs = [createMockDocument("Test content", "doc-1")]; + const result = await reader.read("Test question?", docs); + + expect(result.hypothesis).toBeDefined(); + }); + + it("should format context as JSON when structuredFormat enabled", async () => { + const llm = new MockLLMProvider(); + const reader = new Reader(llm, { structuredFormat: true }); + + const docs = [ + createMockDocument("First message", "doc-1", new Date("2024-03-10")), + createMockDocument("Second message", "doc-2", new Date("2024-03-12")), + ]; + + // The reader should format as JSON internally + const result = await reader.read("Question?", docs); + expect(result).toBeDefined(); + }); + }); + + describe("abstention detection", () => { + it("should abstain when confidence below threshold", async () => { + const llm = new MockLLMProvider(); + llm.setConfidenceOverride(0.1); + + const reader = new Reader(llm, { abstentionThreshold: 0.3 }); + const docs = [createMockDocument("Unrelated", "doc-1")]; + + const result = await reader.read("Unknown question?", docs); + expect(result.abstained).toBe(true); + }); + + it("should not abstain when confidence above threshold", async () => { + const llm = new MockLLMProvider(); + llm.setFixedResponse({ + answer: "Specific answer", + confidence: 0.9, + answerable: true, + }); + + const reader = new Reader(llm, { abstentionThreshold: 0.3 }); + const docs = [createMockDocument("Relevant content", "doc-1")]; + + const result = await reader.read("Clear question?", docs, new Date(), [0.9]); + expect(result.abstained).toBe(false); + }); + + it("should detect abstention phrases in markdown responses", async () => { + const llm = new StubLLMProvider(); + llm.setResponse( + "phone number", + `### Key Information: +- No phone number mentioned in conversation + +### Reasoning: +The conversation history does not contain any phone numbers. + +### Answer: +I don't have that information.`, + ); + + const reader = new Reader(llm, { calibratedConfidence: false }); + const docs = [createMockDocument("My name is John", "doc-1")]; + + const result = await reader.read("What is my phone number?", docs); + expect(result.confidenceSignals?.abstentionDetected).toBe(true); + }); + }); + + describe("configuration options", () => { + it("should respect jsonOutput setting", async () => { + const llm = new MockLLMProvider(); + const readerJson = new Reader(llm, { jsonOutput: true }); + const readerMarkdown = new Reader(llm, { jsonOutput: false }); + + const docs = [createMockDocument("Test", "doc-1")]; + + const jsonResult = await readerJson.read("Question?", docs); + const mdResult = await readerMarkdown.read("Question?", docs); + + // Both should produce results + expect(jsonResult.hypothesis).toBeDefined(); + expect(mdResult.hypothesis).toBeDefined(); + }); + + it("should disable calibrated confidence when configured", async () => { + const llm = new MockLLMProvider(); + llm.setFixedResponse({ + answer: "test", + confidence: 0.5, + answerable: true, + }); + + const readerCalibrated = new Reader(llm, { calibratedConfidence: true }); + const readerUncalibrated = new Reader(llm, { calibratedConfidence: false }); + + const docs = [createMockDocument("Content", "doc-1")]; + + const calibratedResult = await readerCalibrated.read("Q?", docs, new Date(), [0.8]); + const uncalibratedResult = await readerUncalibrated.read("Q?", docs, new Date(), [0.8]); + + // Uncalibrated should use raw LLM confidence (0.5) + // Calibrated should compute weighted score + expect(uncalibratedResult.confidence).toBe(0.5); + expect(calibratedResult.confidence).not.toBe(0.5); + }); + }); +}); + +describe("Reader prompt generation", () => { + it("should include date context when provided", async () => { + const llm = new MockLLMProvider(); + const reader = new Reader(llm); + + const docs = [createMockDocument("Test", "doc-1")]; + const questionDate = new Date("2024-03-15"); + + const result = await reader.read("What happened yesterday?", docs, questionDate); + + // Should have processed with date context + expect(result).toBeDefined(); + }); + + it("should handle empty documents gracefully", async () => { + const llm = new MockLLMProvider(); + const reader = new Reader(llm); + + const result = await reader.read("Question with no context?", []); + + expect(result.hypothesis).toBeDefined(); + expect(result.confidenceSignals?.hasRelevantDocs).toBe(false); + }); +}); diff --git a/packages/benchmark/tests/retriever.test.ts b/packages/benchmark/tests/retriever.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e93d2866e034c36f72666ae2795d5b2fc99f823 --- /dev/null +++ b/packages/benchmark/tests/retriever.test.ts @@ -0,0 +1,196 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { mapInstance } from "../src/longmemeval/mapper.js"; +import { + computeRetrievalMetrics, + type EmbeddingProvider, + InMemoryVectorStore, + Retriever, +} from "../src/longmemeval/retriever.js"; +import type { ParsedInstance } from "../src/longmemeval/types.js"; + +/** + * Mock embedding provider that generates deterministic embeddings + * based on word overlap (for testing retrieval logic) + */ +class MockEmbeddingProvider implements EmbeddingProvider { + readonly dimension = 64; + + async embed(texts: string[]): Promise { + return texts.map((text) => this.textToVector(text)); + } + + private textToVector(text: string): number[] { + const words = text.toLowerCase().split(/\s+/); + const vector = new Array(this.dimension).fill(0); + + // Create a simple bag-of-words style embedding + for (const word of words) { + const hash = this.hashString(word); + const index = hash % this.dimension; + vector[index] += 1; + } + + // Normalize + const norm = Math.sqrt(vector.reduce((sum, v) => sum + v * v, 0)); + if (norm > 0) { + for (let i = 0; i < vector.length; i++) { + vector[i] /= norm; + } + } + + return vector; + } + + private hashString(str: string): number { + let hash = 0; + for (let i = 0; i < str.length; i++) { + hash = (hash << 5) - hash + str.charCodeAt(i); + hash = hash & hash; + } + return Math.abs(hash); + } +} + +const createMockInstance = (): ParsedInstance => ({ + questionId: "test_001", + questionType: "single-session-user", + memoryAbility: "IE", + question: "What is the user's favorite color?", + answer: "blue", + questionDate: new Date("2024-03-15T10:00:00Z"), + sessions: [ + { + sessionId: "session_1", + timestamp: new Date("2024-03-01T09:00:00Z"), + turns: [ + { role: "user", content: "My favorite color is blue.", hasAnswer: true, sequenceIndex: 0 }, + { + role: "assistant", + content: "Blue is a calming color.", + hasAnswer: false, + sequenceIndex: 1, + }, + ], + }, + { + sessionId: "session_2", + timestamp: new Date("2024-03-10T14:00:00Z"), + turns: [ + { + role: "user", + content: "I went to the grocery store.", + hasAnswer: false, + sequenceIndex: 0, + }, + { role: "assistant", content: "What did you buy?", hasAnswer: false, sequenceIndex: 1 }, + ], + }, + ], + answerSessionIds: ["session_1"], + isAbstention: false, +}); + +describe("LongMemEval Retriever", () => { + let embeddings: MockEmbeddingProvider; + let retriever: Retriever; + + beforeEach(() => { + embeddings = new MockEmbeddingProvider(); + retriever = new Retriever(embeddings, { topK: 5 }); + }); + + describe("InMemoryVectorStore", () => { + it("should index and search documents", async () => { + const store = new InMemoryVectorStore(embeddings); + const instance = createMockInstance(); + const { documents } = mapInstance(instance); + + await store.index(documents); + const result = await store.search("favorite color blue", 3); + + expect(result.documents.length).toBeLessThanOrEqual(3); + expect(result.scores.length).toBe(result.documents.length); + }); + }); + + describe("Retriever", () => { + it("should retrieve relevant documents", async () => { + const instance = createMockInstance(); + const mapped = mapInstance(instance); + + await retriever.indexInstance(mapped); + const result = await retriever.retrieve("What is my favorite color?"); + + expect(result.documents.length).toBeGreaterThan(0); + expect(result.retrievedIds.length).toBe(result.documents.length); + }); + + it("should rank documents by relevance", async () => { + const instance = createMockInstance(); + const mapped = mapInstance(instance); + + await retriever.indexInstance(mapped); + const result = await retriever.retrieve("favorite color blue"); + + // Scores should be in descending order + for (let i = 1; i < result.scores.length; i++) { + expect(result.scores[i]).toBeLessThanOrEqual(result.scores[i - 1]); + } + }); + + it("should clear index between instances", async () => { + const instance = createMockInstance(); + const mapped = mapInstance(instance); + + await retriever.indexInstance(mapped); + retriever.clear(); + + // After clear, search should return empty results + const result = await retriever.retrieve("favorite color"); + expect(result.documents.length).toBe(0); + }); + }); + + describe("computeRetrievalMetrics", () => { + it("should compute recall correctly", () => { + const result = { + documents: [], + scores: [], + retrievedIds: ["doc1", "doc2", "doc3"], + }; + const evidenceIds = ["doc1", "doc4"]; + + const metrics = computeRetrievalMetrics(result, evidenceIds); + + expect(metrics.recall).toBe(0.5); // 1 out of 2 evidence docs retrieved + expect(metrics.precision).toBeCloseTo(1 / 3); // 1 out of 3 retrieved is evidence + }); + + it("should compute recall@K correctly", () => { + const result = { + documents: [], + scores: [], + retrievedIds: ["doc1", "doc2", "doc3", "doc4", "doc5"], + }; + const evidenceIds = ["doc1", "doc3"]; + + const metrics = computeRetrievalMetrics(result, evidenceIds); + + expect(metrics.recallAtK[1]).toBe(0.5); // doc1 is evidence + expect(metrics.recallAtK[5]).toBe(1.0); // both doc1 and doc3 in top 5 + }); + + it("should handle empty evidence", () => { + const result = { + documents: [], + scores: [], + retrievedIds: ["doc1"], + }; + + const metrics = computeRetrievalMetrics(result, []); + + expect(metrics.recall).toBe(0); + expect(metrics.precision).toBe(0); + }); + }); +}); diff --git a/packages/benchmark/tests/temporal.test.ts b/packages/benchmark/tests/temporal.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..02d8d612c9c9de20ec3a013c19a442eefdea4c5d --- /dev/null +++ b/packages/benchmark/tests/temporal.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from "vitest"; +import { + analyzeTemporalQuery, + filterByTimeRange, + TemporalAnalyzer, + type TimeRange, +} from "../src/longmemeval/temporal.js"; + +describe("Temporal Analysis", () => { + const baseDate = new Date("2024-03-15T10:00:00Z"); + + describe("TemporalAnalyzer", () => { + const analyzer = new TemporalAnalyzer(); + + it("should detect temporal queries", async () => { + const result = await analyzer.analyze("What did I do yesterday?", baseDate); + expect(result.isTemporalQuery).toBe(true); + expect(result.temporalKeywords).toContain("yesterday"); + }); + + it("should not flag non-temporal queries", async () => { + const result = await analyzer.analyze("What is my favorite color?", baseDate); + expect(result.isTemporalQuery).toBe(false); + }); + + it("should extract time range for 'yesterday'", async () => { + const result = await analyzer.analyze("What happened yesterday?", baseDate); + expect(result.timeRange).toBeDefined(); + expect(result.timeRange?.source).toBe("yesterday"); + + const expectedDate = new Date("2024-03-14"); + expect(result.timeRange?.start.toISOString().split("T")[0]).toBe("2024-03-14"); + }); + + it("should extract time range for 'last week'", async () => { + const result = await analyzer.analyze("What did I do last week?", baseDate); + expect(result.timeRange).toBeDefined(); + expect(result.timeRange?.source).toBe("last week"); + }); + + it("should extract time range for 'last month'", async () => { + const result = await analyzer.analyze("What happened last month?", baseDate); + expect(result.timeRange).toBeDefined(); + expect(result.timeRange?.source).toBe("last month"); + }); + + it("should extract time range for specific month", async () => { + const result = await analyzer.analyze("What happened in January?", baseDate); + expect(result.timeRange).toBeDefined(); + expect(result.timeRange?.start.getMonth()).toBe(0); // January + }); + + it("should extract time range for 'last N days'", async () => { + const result = await analyzer.analyze("Show me the last 5 days", baseDate); + expect(result.timeRange).toBeDefined(); + expect(result.timeRange?.source).toBe("last 5 days"); + }); + + it("should detect temporal keywords", async () => { + const result = await analyzer.analyze("When did I visit the doctor last month?", baseDate); + expect(result.temporalKeywords).toContain("when"); + expect(result.temporalKeywords).toContain("last"); + expect(result.temporalKeywords).toContain("month"); + }); + + it("should expand query with time context", async () => { + const result = await analyzer.analyze("What happened yesterday?", baseDate); + expect(result.expandedQuery).toContain("Time context:"); + }); + }); + + describe("filterByTimeRange", () => { + const documents = [ + { id: "1", validTime: new Date("2024-03-10") }, + { id: "2", validTime: new Date("2024-03-12") }, + { id: "3", validTime: new Date("2024-03-14") }, + { id: "4", validTime: new Date("2024-03-16") }, + ]; + + it("should filter documents within range", () => { + const range: TimeRange = { + start: new Date("2024-03-11"), + end: new Date("2024-03-15"), + confidence: "high", + source: "test", + }; + + const filtered = filterByTimeRange(documents, range); + expect(filtered).toHaveLength(2); + expect(filtered.map((d) => d.id)).toEqual(["2", "3"]); + }); + + it("should return empty array when no matches", () => { + const range: TimeRange = { + start: new Date("2024-01-01"), + end: new Date("2024-01-31"), + confidence: "high", + source: "test", + }; + + const filtered = filterByTimeRange(documents, range); + expect(filtered).toHaveLength(0); + }); + + it("should include boundary dates", () => { + const range: TimeRange = { + start: new Date("2024-03-10T00:00:00Z"), + end: new Date("2024-03-10T23:59:59Z"), + confidence: "high", + source: "test", + }; + + const filtered = filterByTimeRange(documents, range); + expect(filtered).toHaveLength(1); + expect(filtered[0].id).toBe("1"); + }); + }); + + describe("analyzeTemporalQuery helper", () => { + it("should analyze query", async () => { + const result = await analyzeTemporalQuery("What did I do last week?", baseDate); + expect(result.isTemporalQuery).toBe(true); + expect(result.timeRange).toBeDefined(); + }); + }); +}); diff --git a/packages/benchmark/tsconfig.json b/packages/benchmark/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d5542982d1e8909aafdade933f3d65bb78f040b3 --- /dev/null +++ b/packages/benchmark/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@engram/tsconfig/base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/common/README.md b/packages/common/README.md new file mode 100644 index 0000000000000000000000000000000000000000..777f8fe1b264c10950f7837f71d20f8252916069 --- /dev/null +++ b/packages/common/README.md @@ -0,0 +1,96 @@ +# @engram/common + +Shared utilities, errors, and constants for the Engram system. + +## Overview + +Foundation package that eliminates code duplication and provides consistent error handling across all Engram packages and applications. + +## Installation + +```bash +npm install @engram/common +``` + +## Exports + +### Utilities + +```typescript +import { + envStr, + envBool, + envNum, + formatBytes, + formatDuration, + sha256Hash, + withRetry, +} from "@engram/common"; + +// Environment helpers +const apiKey = envStr("API_KEY", "default"); +const debug = envBool("DEBUG", false); +const port = envNum("PORT", 3000); + +// Formatting +formatBytes(1024); // "1 KB" +formatDuration(3600000); // "1h" + +// Hashing +const hash = sha256Hash("content"); + +// Retry logic +await withRetry(() => fetchData(), { maxRetries: 3 }); +``` + +### Errors + +```typescript +import { + EngramError, + GraphOperationError, + SearchError, + StorageError, + ValidationError, +} from "@engram/common"; + +throw new ValidationError("Invalid input", { field: "email" }); +``` + +### Constants + +```typescript +import { TIMEOUTS, LIMITS, INTERVALS } from "@engram/common"; + +// Timeouts for various operations +TIMEOUTS.KAFKA_CONNECT; // 30000ms +TIMEOUTS.GRAPH_QUERY; // 10000ms + +// System limits +LIMITS.MAX_PAYLOAD_SIZE; // 50MB +LIMITS.MAX_BATCH_SIZE; // 100 +``` + +### Testing Utilities + +```typescript +import { createMockLogger, createMockClient } from "@engram/common/testing"; + +const logger = createMockLogger(); +const client = createMockClient(); +``` + +## Error Hierarchy + +``` +EngramError (base) +├── GraphOperationError +├── SearchError +├── StorageError +└── ValidationError +``` + +All errors include: +- Error code +- Optional context object +- Stack trace preservation diff --git a/packages/common/package.json b/packages/common/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6450e4f687ae1b5bbe5e09d5a32d5e75bcaacf44 --- /dev/null +++ b/packages/common/package.json @@ -0,0 +1,28 @@ +{ + "name": "@engram/common", + "version": "0.0.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./utils": "./src/utils/index.ts", + "./errors": "./src/errors/index.ts", + "./constants": "./src/constants/index.ts", + "./testing": "./src/testing/index.ts" + }, + "dependencies": { + "@engram/storage": "*", + "@engram/graph": "*" + }, + "devDependencies": { + "typescript": "^5.9.3", + "@types/node": "^24.10.1", + "@engram/tsconfig": "*", + "vitest": "^3.2.3" + }, + "scripts": { + "build": "echo 'Build success'", + "typecheck": "tsc --noEmit" + } +} diff --git a/packages/common/src/constants/index.ts b/packages/common/src/constants/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..1dae10fe30e98865f706492ddeb46707cad5bc81 --- /dev/null +++ b/packages/common/src/constants/index.ts @@ -0,0 +1,28 @@ +/** + * Constants for the Engram system. + * + * @module @engram/common/constants + */ + +export { + DebounceIntervals, + PollIntervals, + PruneIntervals, + RetentionPeriods, + WebSocketIntervals, +} from "./intervals"; + +export { + BatchLimits, + ContentLimits, + QueryLimits, + RateLimits, + SessionLimits, +} from "./limits"; +export { + CacheTimeouts, + GraphTimeouts, + HttpTimeouts, + SearchTimeouts, + ToolTimeouts, +} from "./timeouts"; diff --git a/packages/common/src/constants/intervals.ts b/packages/common/src/constants/intervals.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f43ee106477e3cc5fc889d96122983c6267e045 --- /dev/null +++ b/packages/common/src/constants/intervals.ts @@ -0,0 +1,103 @@ +/** + * Interval constants for the Engram system. + * + * These constants define timing intervals for periodic jobs and cleanup. + * All values are in milliseconds. + * + * @module @engram/common/constants/intervals + */ + +/** + * Pruning and cleanup intervals. + */ +export const PruneIntervals = { + /** Graph pruning job interval (24 hours) */ + GRAPH_PRUNE_MS: 24 * 60 * 60 * 1000, // 86_400_000 + + /** Stale turn cleanup interval (5 minutes) */ + STALE_TURN_CLEANUP_MS: 5 * 60 * 1000, // 300_000 + + /** Cache cleanup interval (1 hour) */ + CACHE_CLEANUP_MS: 60 * 60 * 1000, // 3_600_000 + + /** Session inactivity threshold (30 minutes) */ + SESSION_INACTIVE_MS: 30 * 60 * 1000, // 1_800_000 + + /** Stale turn threshold (30 minutes) */ + STALE_TURN_THRESHOLD_MS: 30 * 60 * 1000, // 1_800_000 +} as const; + +/** + * Polling and sync intervals. + */ +export const PollIntervals = { + /** Health check polling interval (30 seconds) */ + HEALTH_CHECK_MS: 30 * 1000, // 30_000 + + /** Metrics collection interval (10 seconds) */ + METRICS_COLLECTION_MS: 10 * 1000, // 10_000 + + /** Connection retry base interval (1 second) */ + CONNECTION_RETRY_BASE_MS: 1000, + + /** Maximum connection retry interval (30 seconds) */ + CONNECTION_RETRY_MAX_MS: 30 * 1000, // 30_000 + + /** Kafka consumer poll interval (100ms) */ + KAFKA_POLL_MS: 100, +} as const; + +/** + * Debounce and throttle intervals. + */ +export const DebounceIntervals = { + /** Search input debounce (300ms) */ + SEARCH_INPUT_MS: 300, + + /** Auto-save debounce (1 second) */ + AUTO_SAVE_MS: 1000, + + /** WebSocket reconnect debounce (1 second) */ + WS_RECONNECT_MS: 1000, + + /** Event batching window (100ms) */ + EVENT_BATCH_MS: 100, +} as const; + +/** + * Retention periods. + */ +export const RetentionPeriods = { + /** Default data retention (30 days) */ + DEFAULT_DAYS: 30, + + /** Session data retention (90 days) */ + SESSION_DAYS: 90, + + /** Metrics retention (7 days) */ + METRICS_DAYS: 7, + + /** Log retention (14 days) */ + LOGS_DAYS: 14, + + /** Convert days to milliseconds helper */ + toMs: (days: number): number => days * 24 * 60 * 60 * 1000, +} as const; + +/** + * WebSocket intervals. + */ +export const WebSocketIntervals = { + /** Ping interval to keep connection alive (30 seconds) */ + PING_MS: 30 * 1000, // 30_000 + + /** Pong timeout before considering connection dead (10 seconds) */ + PONG_TIMEOUT_MS: 10 * 1000, // 10_000 + + /** Reconnection attempt interval (1-30 seconds with backoff) */ + RECONNECT_BASE_MS: 1000, + RECONNECT_MAX_MS: 30 * 1000, // 30_000 + + /** Maximum reconnection attempts before giving up */ + MAX_RECONNECT_ATTEMPTS: 10, +} as const; diff --git a/packages/common/src/constants/limits.ts b/packages/common/src/constants/limits.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbbc8c5797bc8a0c3ddc8678c2a85aa851471b4f --- /dev/null +++ b/packages/common/src/constants/limits.ts @@ -0,0 +1,119 @@ +/** + * Limit constants for the Engram system. + * + * These constants define maximum values for various operations. + * + * @module @engram/common/constants/limits + */ + +/** + * Content size limits. + */ +export const ContentLimits = { + /** Maximum content length for a single event (100KB) */ + MAX_EVENT_CONTENT_BYTES: 100_000, + + /** Maximum length for thought/turn content (50KB) */ + MAX_THOUGHT_CONTENT_BYTES: 50_000, + + /** Maximum context window size for LLM (200K tokens approx) */ + MAX_CONTEXT_TOKENS: 200_000, + + /** Maximum file content for indexing (1MB) */ + MAX_FILE_INDEX_BYTES: 1_000_000, + + /** Maximum blob size (10MB) */ + MAX_BLOB_BYTES: 10_000_000, + + /** Truncation limit for display (500 chars) */ + DISPLAY_TRUNCATE_CHARS: 500, +} as const; + +/** + * Query and result limits. + */ +export const QueryLimits = { + /** Default number of results per page */ + DEFAULT_PAGE_SIZE: 10, + + /** Maximum number of results per page */ + MAX_PAGE_SIZE: 100, + + /** Default number of search results */ + DEFAULT_SEARCH_RESULTS: 10, + + /** Maximum number of search results */ + MAX_SEARCH_RESULTS: 100, + + /** Default history items to retrieve */ + DEFAULT_HISTORY_ITEMS: 50, + + /** Maximum history items to retrieve */ + MAX_HISTORY_ITEMS: 500, + + /** Maximum depth for graph traversals */ + MAX_TRAVERSAL_DEPTH: 10, + + /** Maximum candidates for reranking */ + MAX_RERANK_CANDIDATES: 100, +} as const; + +/** + * Session and turn limits. + */ +export const SessionLimits = { + /** Maximum turns per session for display */ + MAX_TURNS_DISPLAY: 100, + + /** Maximum active sessions per user */ + MAX_ACTIVE_SESSIONS: 10, + + /** Maximum events per turn */ + MAX_EVENTS_PER_TURN: 1000, + + /** Maximum file touches per turn */ + MAX_FILE_TOUCHES_PER_TURN: 500, +} as const; + +/** + * Rate limits. + */ +export const RateLimits = { + /** Maximum requests per minute for search API */ + SEARCH_RPM: 60, + + /** Maximum requests per minute for embedding API */ + EMBEDDING_RPM: 100, + + /** Maximum requests per hour for LLM reranking */ + LLM_RERANK_RPH: 1000, + + /** Maximum events per second for ingestion */ + INGESTION_EPS: 100, + + /** Maximum WebSocket connections per user */ + WS_CONNECTIONS_PER_USER: 5, +} as const; + +/** + * Batch processing limits. + */ +export const BatchLimits = { + /** Default batch size for processing */ + DEFAULT_BATCH_SIZE: 100, + + /** Maximum batch size for processing */ + MAX_BATCH_SIZE: 1000, + + /** Batch size for embedding generation */ + EMBEDDING_BATCH_SIZE: 32, + + /** Batch size for fast reranking */ + RERANK_FAST_BATCH_SIZE: 16, + + /** Batch size for accurate reranking */ + RERANK_ACCURATE_BATCH_SIZE: 8, + + /** Batch size for Kafka message processing */ + KAFKA_BATCH_SIZE: 100, +} as const; diff --git a/packages/common/src/constants/timeouts.ts b/packages/common/src/constants/timeouts.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6e103ac8b126d53a5648bc86f80cf1bab57e3ec --- /dev/null +++ b/packages/common/src/constants/timeouts.ts @@ -0,0 +1,101 @@ +/** + * Timeout constants for the Engram system. + * + * All timeout values are in milliseconds unless otherwise noted. + * + * @module @engram/common/constants/timeouts + */ + +/** + * Graph database query timeouts. + */ +export const GraphTimeouts = { + /** Default timeout for graph queries (10 seconds) */ + QUERY_MS: 10_000, + + /** Timeout for complex traversal queries (30 seconds) */ + TRAVERSAL_MS: 30_000, + + /** Timeout for graph connection attempts (5 seconds) */ + CONNECTION_MS: 5_000, + + /** Timeout for transaction commits (15 seconds) */ + TRANSACTION_MS: 15_000, +} as const; + +/** + * Tool and MCP execution timeouts. + */ +export const ToolTimeouts = { + /** Default timeout for tool execution (60 seconds) */ + EXECUTION_MS: 60_000, + + /** Timeout for MCP server connection (10 seconds) */ + MCP_CONNECTION_MS: 10_000, + + /** Timeout for MCP tool invocation (120 seconds) */ + MCP_INVOCATION_MS: 120_000, + + /** Timeout for shell command execution (300 seconds / 5 minutes) */ + SHELL_EXECUTION_MS: 300_000, +} as const; + +/** + * Search and embedding timeouts. + */ +export const SearchTimeouts = { + /** Default timeout for search queries (5 seconds) */ + QUERY_MS: 5_000, + + /** Timeout for embedding generation (30 seconds) */ + EMBEDDING_MS: 30_000, + + /** Timeout for reranking (500ms for fast tier) */ + RERANK_FAST_MS: 500, + + /** Timeout for reranking (2 seconds for accurate tier) */ + RERANK_ACCURATE_MS: 2_000, + + /** Timeout for LLM reranking (10 seconds) */ + RERANK_LLM_MS: 10_000, +} as const; + +/** + * HTTP and API timeouts. + */ +export const HttpTimeouts = { + /** Default HTTP request timeout (30 seconds) */ + REQUEST_MS: 30_000, + + /** Timeout for health checks (5 seconds) */ + HEALTH_CHECK_MS: 5_000, + + /** Timeout for webhook deliveries (10 seconds) */ + WEBHOOK_MS: 10_000, + + /** WebSocket ping interval (30 seconds) */ + WS_PING_MS: 30_000, + + /** WebSocket connection timeout (10 seconds) */ + WS_CONNECTION_MS: 10_000, +} as const; + +/** + * Cache timeouts (TTL values). + */ +export const CacheTimeouts = { + /** Default cache TTL (5 minutes) */ + DEFAULT_TTL_MS: 300_000, + + /** Short cache TTL (1 minute) */ + SHORT_TTL_MS: 60_000, + + /** Long cache TTL (1 hour) */ + LONG_TTL_MS: 3_600_000, + + /** Embedding cache TTL (24 hours) */ + EMBEDDING_TTL_MS: 86_400_000, + + /** Query result cache TTL (5 minutes) */ + QUERY_RESULT_TTL_MS: 300_000, +} as const; diff --git a/packages/common/src/errors/base.ts b/packages/common/src/errors/base.ts new file mode 100644 index 0000000000000000000000000000000000000000..6077557ecd449fd3011ac51c8c92e4e039d46f2e --- /dev/null +++ b/packages/common/src/errors/base.ts @@ -0,0 +1,85 @@ +/** + * Base error class for the Engram system. + * + * All domain-specific errors should extend this class. + * + * @module @engram/common/errors/base + */ + +/** + * Base error class for all Engram errors. + * + * Provides structured error handling with: + * - Error codes for programmatic handling + * - Cause chaining for root cause analysis + * - Consistent serialization for logging + * + * @example + * ```ts + * throw new EngramError("Operation failed", "OP_FAILED", originalError); + * ``` + */ +export class EngramError extends Error { + /** + * Error code for programmatic error handling. + * Use SCREAMING_SNAKE_CASE (e.g., "GRAPH_QUERY_FAILED"). + */ + public readonly code: string; + + /** + * Original error that caused this error. + * Enables error chaining for debugging. + */ + public readonly cause?: Error; + + /** + * Timestamp when the error was created. + */ + public readonly timestamp: number; + + constructor(message: string, code: string, cause?: Error) { + super(message); + this.name = "EngramError"; + this.code = code; + this.cause = cause; + this.timestamp = Date.now(); + + // Maintains proper stack trace for where error was thrown + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + + /** + * Convert error to a plain object for logging/serialization. + */ + toJSON(): Record { + return { + name: this.name, + message: this.message, + code: this.code, + timestamp: this.timestamp, + stack: this.stack, + cause: this.cause + ? { + name: this.cause.name, + message: this.cause.message, + stack: this.cause.stack, + } + : undefined, + }; + } + + /** + * Create a formatted string representation for logging. + */ + toLogString(): string { + const parts = [`[${this.code}] ${this.message}`]; + + if (this.cause) { + parts.push(` Caused by: ${this.cause.message}`); + } + + return parts.join("\n"); + } +} diff --git a/packages/common/src/errors/domain.ts b/packages/common/src/errors/domain.ts new file mode 100644 index 0000000000000000000000000000000000000000..deeb21b1afc5f23205ff852316a66184138acbba --- /dev/null +++ b/packages/common/src/errors/domain.ts @@ -0,0 +1,343 @@ +/** + * Domain-specific error classes for the Engram system. + * + * These errors represent specific failure scenarios across the system. + * + * @module @engram/common/errors/domain + */ + +import { EngramError } from "./base"; + +/** + * Error codes for domain errors. + */ +export const ErrorCodes = { + // Graph operations + GRAPH_QUERY_FAILED: "GRAPH_QUERY_FAILED", + GRAPH_CONNECTION_FAILED: "GRAPH_CONNECTION_FAILED", + GRAPH_TRANSACTION_FAILED: "GRAPH_TRANSACTION_FAILED", + + // Parsing + PARSE_JSON_FAILED: "PARSE_JSON_FAILED", + PARSE_CYPHER_FAILED: "PARSE_CYPHER_FAILED", + PARSE_EVENT_FAILED: "PARSE_EVENT_FAILED", + + // Validation + VALIDATION_FAILED: "VALIDATION_FAILED", + VALIDATION_SCHEMA_FAILED: "VALIDATION_SCHEMA_FAILED", + VALIDATION_CONSTRAINT_FAILED: "VALIDATION_CONSTRAINT_FAILED", + + // Context assembly + CONTEXT_ASSEMBLY_FAILED: "CONTEXT_ASSEMBLY_FAILED", + CONTEXT_TIMEOUT: "CONTEXT_TIMEOUT", + CONTEXT_LIMIT_EXCEEDED: "CONTEXT_LIMIT_EXCEEDED", + + // Rehydration + REHYDRATION_FAILED: "REHYDRATION_FAILED", + REHYDRATION_NOT_FOUND: "REHYDRATION_NOT_FOUND", + REHYDRATION_CORRUPTED: "REHYDRATION_CORRUPTED", + + // Storage + STORAGE_READ_FAILED: "STORAGE_READ_FAILED", + STORAGE_WRITE_FAILED: "STORAGE_WRITE_FAILED", + STORAGE_NOT_FOUND: "STORAGE_NOT_FOUND", + STORAGE_INVALID_PATH: "STORAGE_INVALID_PATH", + + // Search + SEARCH_QUERY_FAILED: "SEARCH_QUERY_FAILED", + SEARCH_INDEX_FAILED: "SEARCH_INDEX_FAILED", + SEARCH_EMBEDDING_FAILED: "SEARCH_EMBEDDING_FAILED", +} as const; + +export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]; + +/** + * Error for FalkorDB graph operations. + * + * Thrown when graph queries, connections, or transactions fail. + * + * @example + * ```ts + * throw new GraphOperationError( + * "Failed to execute Cypher query", + * "MATCH (n) RETURN n LIMIT 10", + * originalError + * ); + * ``` + */ +export class GraphOperationError extends EngramError { + /** + * The Cypher query that failed (if applicable). + */ + public readonly query?: string; + + /** + * Query parameters (if applicable). + */ + public readonly params?: Record; + + constructor(message: string, query?: string, cause?: Error, params?: Record) { + super(message, ErrorCodes.GRAPH_QUERY_FAILED, cause); + this.name = "GraphOperationError"; + this.query = query; + this.params = params; + } + + override toJSON(): Record { + return { + ...super.toJSON(), + query: this.query, + params: this.params, + }; + } +} + +/** + * Error for parsing failures. + * + * Thrown when JSON parsing, event parsing, or other deserialization fails. + * + * @example + * ```ts + * throw new ParseError("Invalid JSON in event payload", rawPayload, originalError); + * ``` + */ +export class ParseError extends EngramError { + /** + * The raw input that failed to parse. + */ + public readonly input?: string; + + /** + * Expected format or type. + */ + public readonly expected?: string; + + constructor(message: string, input?: string, cause?: Error, expected?: string) { + super(message, ErrorCodes.PARSE_JSON_FAILED, cause); + this.name = "ParseError"; + this.input = input ? input.slice(0, 500) : undefined; // Truncate for logging + this.expected = expected; + } + + override toJSON(): Record { + return { + ...super.toJSON(), + input: this.input, + expected: this.expected, + }; + } +} + +/** + * Error for validation failures. + * + * Thrown when input validation, schema validation, or constraint checks fail. + * + * @example + * ```ts + * throw new ValidationError("Session ID is required", "sessionId"); + * ``` + */ +export class ValidationError extends EngramError { + /** + * The field or property that failed validation. + */ + public readonly field?: string; + + /** + * The invalid value that was provided. + */ + public readonly value?: unknown; + + /** + * Constraint that was violated. + */ + public readonly constraint?: string; + + constructor( + message: string, + field?: string, + cause?: Error, + options?: { value?: unknown; constraint?: string }, + ) { + super(message, ErrorCodes.VALIDATION_FAILED, cause); + this.name = "ValidationError"; + this.field = field; + this.value = options?.value; + this.constraint = options?.constraint; + } + + override toJSON(): Record { + return { + ...super.toJSON(), + field: this.field, + value: this.value, + constraint: this.constraint, + }; + } +} + +/** + * Error for context assembly failures. + * + * Thrown when building context for agent interactions fails. + * + * @example + * ```ts + * throw new ContextAssemblyError( + * "Failed to assemble context within timeout", + * sessionId, + * timeoutError + * ); + * ``` + */ +export class ContextAssemblyError extends EngramError { + /** + * Session ID for which context assembly failed. + */ + public readonly sessionId?: string; + + /** + * Partial context that was assembled before failure. + */ + public readonly partialContext?: unknown; + + constructor(message: string, sessionId?: string, cause?: Error, partialContext?: unknown) { + super(message, ErrorCodes.CONTEXT_ASSEMBLY_FAILED, cause); + this.name = "ContextAssemblyError"; + this.sessionId = sessionId; + this.partialContext = partialContext; + } + + override toJSON(): Record { + return { + ...super.toJSON(), + sessionId: this.sessionId, + hasPartialContext: this.partialContext !== undefined, + }; + } +} + +/** + * Error for state rehydration failures. + * + * Thrown when reconstructing state from persisted data fails. + * + * @example + * ```ts + * throw new RehydrationError("Session state corrupted", sessionId, corruptionError); + * ``` + */ +export class RehydrationError extends EngramError { + /** + * Entity ID for which rehydration failed. + */ + public readonly entityId?: string; + + /** + * Type of entity being rehydrated. + */ + public readonly entityType?: string; + + constructor(message: string, entityId?: string, cause?: Error, entityType?: string) { + super(message, ErrorCodes.REHYDRATION_FAILED, cause); + this.name = "RehydrationError"; + this.entityId = entityId; + this.entityType = entityType; + } + + override toJSON(): Record { + return { + ...super.toJSON(), + entityId: this.entityId, + entityType: this.entityType, + }; + } +} + +/** + * Error for storage operations. + * + * Thrown when blob storage, file system, or database operations fail. + * + * @example + * ```ts + * throw new StorageError("Failed to read blob", uri, readError); + * ``` + */ +export class StorageError extends EngramError { + /** + * URI or path of the storage resource. + */ + public readonly uri?: string; + + /** + * Type of storage operation that failed. + */ + public readonly operation?: "read" | "write" | "delete" | "list"; + + constructor( + message: string, + code: ErrorCode, + uri?: string, + cause?: Error, + operation?: "read" | "write" | "delete" | "list", + ) { + super(message, code, cause); + this.name = "StorageError"; + this.uri = uri; + this.operation = operation; + } + + override toJSON(): Record { + return { + ...super.toJSON(), + uri: this.uri, + operation: this.operation, + }; + } +} + +/** + * Error for search operations. + * + * Thrown when search queries, indexing, or embedding generation fails. + * + * @example + * ```ts + * throw new SearchError("Embedding generation failed", query, embeddingError); + * ``` + */ +export class SearchError extends EngramError { + /** + * The search query that failed. + */ + public readonly query?: string; + + /** + * Search operation that failed. + */ + public readonly operation?: "query" | "index" | "embed" | "rerank"; + + constructor( + message: string, + code: ErrorCode, + query?: string, + cause?: Error, + operation?: "query" | "index" | "embed" | "rerank", + ) { + super(message, code, cause); + this.name = "SearchError"; + this.query = query; + this.operation = operation; + } + + override toJSON(): Record { + return { + ...super.toJSON(), + query: this.query, + operation: this.operation, + }; + } +} diff --git a/packages/common/src/errors/index.ts b/packages/common/src/errors/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2362a9db1e16488221b31acd176cfdd31e023b40 --- /dev/null +++ b/packages/common/src/errors/index.ts @@ -0,0 +1,18 @@ +/** + * Error types for the Engram system. + * + * @module @engram/common/errors + */ + +export { EngramError } from "./base"; +export type { ErrorCode } from "./domain"; +export { + ContextAssemblyError, + ErrorCodes, + GraphOperationError, + ParseError, + RehydrationError, + SearchError, + StorageError, + ValidationError, +} from "./domain"; diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9038887db8cffe7b66c7c5b681c22c44c6fdf9d --- /dev/null +++ b/packages/common/src/index.ts @@ -0,0 +1,107 @@ +/** + * @engram/common - Shared utilities, errors, and constants for the Engram system. + * + * This package provides the foundation for all other packages and applications + * in the Engram monorepo. It consolidates common patterns and eliminates + * code duplication across the codebase. + * + * @example + * ```ts + * // Import utilities + * import { envBool, sha256Hash, withRetry } from "@engram/common"; + * + * // Import errors + * import { GraphOperationError, ValidationError } from "@engram/common"; + * + * // Import constants + * import { GraphTimeouts, ContentLimits } from "@engram/common"; + * + * // Or import from subpaths + * import { envStr } from "@engram/common/utils"; + * import { EngramError } from "@engram/common/errors"; + * import { PruneIntervals } from "@engram/common/constants"; + * ``` + * + * @module @engram/common + */ + +// ============================================================================= +// Utils +// ============================================================================= + +export type { RetryOptions } from "./utils"; +export { + envArray, + // Environment helpers + envBool, + envFloat, + envNum, + envRequired, + envStr, + formatBytes, + formatDuration, + // Formatting utilities + formatRelativeTime, + hashObject, + RetryableErrors, + // Hash utilities + sha256Hash, + sha256Short, + truncateId, + truncateText, + // Retry utilities + withRetry, +} from "./utils"; + +// ============================================================================= +// Errors +// ============================================================================= + +export type { ErrorCode } from "./errors"; +export { + ContextAssemblyError, + // Base error + EngramError, + // Error codes + ErrorCodes, + // Domain errors + GraphOperationError, + ParseError, + RehydrationError, + SearchError, + StorageError, + ValidationError, +} from "./errors"; + +// ============================================================================= +// Constants +// ============================================================================= + +export { + BatchLimits, + CacheTimeouts, + // Limits + ContentLimits, + DebounceIntervals, + // Timeouts + GraphTimeouts, + HttpTimeouts, + PollIntervals, + // Intervals + PruneIntervals, + QueryLimits, + RateLimits, + RetentionPeriods, + SearchTimeouts, + SessionLimits, + ToolTimeouts, + WebSocketIntervals, +} from "./constants"; + +// ============================================================================= +// Testing +// ============================================================================= +// NOTE: Testing utilities are NOT exported from the main entry point to avoid +// pulling vitest into production code. Import testing utilities from: +// import { createTestGraphClient, ... } from "@engram/common/testing"; +// ============================================================================= diff --git a/packages/common/src/testing/index.test.ts b/packages/common/src/testing/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..48232179dcc5c373f3e1c70a4cc82400efba19b9 --- /dev/null +++ b/packages/common/src/testing/index.test.ts @@ -0,0 +1,567 @@ +/** + * Tests for @engram/common/testing utilities. + * These tests validate the mock factories and fixture helpers work correctly. + */ + +import { describe, expect, it, vi } from "vitest"; +import { + createDeferred, + createTestBitemporalProps, + createTestBlobStore, + createTestFileTouch, + // Mock factories + createTestGraphClient, + createTestHash, + // ID and hash utilities + createTestId, + createTestKafkaClient, + createTestKafkaMessage, + createTestObservation, + createTestReasoning, + createTestRedisPublisher, + // Fixture factories + createTestSession, + createTestToolCall, + createTestTurn, + expectToReject, + spyOnConsole, + // Test utilities + wait, +} from "./index"; + +// ============================================================================= +// ID and Hash Utilities +// ============================================================================= + +describe("createTestId", () => { + it("should generate a 26-character ULID-like ID", () => { + // Act + const id = createTestId(); + + // Assert + expect(id).toHaveLength(26); + expect(id).toMatch(/^[0-9A-HJKMNP-TV-Z]+$/); + }); + + it("should use custom prefix", () => { + // Act + const id = createTestId("01CUST"); + + // Assert + expect(id).toHaveLength(26); + expect(id).toMatch(/^01CUST/); + }); + + it("should generate unique IDs", () => { + // Act + const ids = Array.from({ length: 100 }, () => createTestId()); + const uniqueIds = new Set(ids); + + // Assert + expect(uniqueIds.size).toBe(100); + }); +}); + +describe("createTestHash", () => { + it("should generate a 64-character hex string", () => { + // Act + const hash = createTestHash(); + + // Assert + expect(hash).toHaveLength(64); + expect(hash).toMatch(/^[0-9a-f]+$/); + }); +}); + +describe("createTestBitemporalProps", () => { + it("should generate valid bitemporal properties", () => { + // Arrange + const before = Date.now(); + + // Act + const props = createTestBitemporalProps(); + + // Assert + expect(props.vt_start).toBeGreaterThanOrEqual(before); + expect(props.tt_start).toBeGreaterThanOrEqual(before); + expect(props.vt_end).toBe(9999999999999); + expect(props.tt_end).toBe(9999999999999); + }); + + it("should allow overriding properties", () => { + // Arrange + const customStart = 1000000000000; + + // Act + const props = createTestBitemporalProps({ + vt_start: customStart, + tt_start: customStart, + }); + + // Assert + expect(props.vt_start).toBe(customStart); + expect(props.tt_start).toBe(customStart); + }); +}); + +// ============================================================================= +// Mock Factory Tests +// ============================================================================= + +describe("createTestGraphClient", () => { + it("should create a mock with all required methods", () => { + // Act + const client = createTestGraphClient(); + + // Assert + expect(client.connect).toBeDefined(); + expect(client.disconnect).toBeDefined(); + expect(client.query).toBeDefined(); + expect(client.isConnected).toBeDefined(); + }); + + it("should have working mock implementations", async () => { + // Arrange + const client = createTestGraphClient(); + + // Act + await client.connect(); + const results = await client.query("MATCH (n) RETURN n"); + const connected = client.isConnected(); + await client.disconnect(); + + // Assert + expect(results).toEqual([]); + expect(connected).toBe(true); + expect(client.connect).toHaveBeenCalled(); + expect(client.query).toHaveBeenCalledWith("MATCH (n) RETURN n"); + expect(client.disconnect).toHaveBeenCalled(); + }); + + it("should allow overriding methods", async () => { + // Arrange + const mockData = [{ id: "123", name: "test" }]; + const client = createTestGraphClient({ + query: vi.fn().mockResolvedValue(mockData), + }); + + // Act + const results = await client.query("MATCH (n) RETURN n"); + + // Assert + expect(results).toEqual(mockData); + }); +}); + +describe("createTestKafkaClient", () => { + it("should create a mock with all required methods", () => { + // Act + const client = createTestKafkaClient(); + + // Assert + expect(client.getProducer).toBeDefined(); + expect(client.getConsumer).toBeDefined(); + expect(client.disconnect).toBeDefined(); + }); + + it("should return mock producer and consumer", async () => { + // Arrange + const client = createTestKafkaClient(); + + // Act + const producer = await client.getProducer(); + const consumer = await client.getConsumer({ groupId: "test-group" }); + + // Assert + expect(producer.connect).toBeDefined(); + expect(producer.send).toBeDefined(); + expect(producer.disconnect).toBeDefined(); + expect(consumer.connect).toBeDefined(); + expect(consumer.subscribe).toBeDefined(); + expect(consumer.run).toBeDefined(); + expect(consumer.disconnect).toBeDefined(); + }); +}); + +describe("createTestRedisPublisher", () => { + it("should create a mock with all required methods", () => { + // Act + const publisher = createTestRedisPublisher(); + + // Assert + expect(publisher.publishSessionUpdate).toBeDefined(); + expect(publisher.disconnect).toBeDefined(); + }); + + it("should track method calls", async () => { + // Arrange + const publisher = createTestRedisPublisher(); + const event = { type: "turn_added", data: {} }; + + // Act + await publisher.publishSessionUpdate("session-123", event); + + // Assert + expect(publisher.publishSessionUpdate).toHaveBeenCalledWith("session-123", event); + }); +}); + +describe("createTestBlobStore", () => { + it("should create a mock with all required methods", () => { + // Act + const store = createTestBlobStore(); + + // Assert + expect(store.save).toBeDefined(); + expect(store.load).toBeDefined(); + }); + + it("should have working mock implementations", async () => { + // Arrange + const store = createTestBlobStore(); + + // Act + const uri = await store.save("test content"); + const content = await store.load(uri); + + // Assert + expect(uri).toMatch(/^file:\/\//); + expect(content).toBe(""); + }); +}); + +describe("createTestKafkaMessage", () => { + it("should create a valid Kafka message", () => { + // Act + const message = createTestKafkaMessage(); + + // Assert + expect(message.key).toBeInstanceOf(Buffer); + expect(message.value).toBeInstanceOf(Buffer); + expect(message.offset).toBe("0"); + expect(message.timestamp).toBeDefined(); + }); + + it("should allow overriding properties", () => { + // Arrange + const customValue = Buffer.from(JSON.stringify({ custom: "data" })); + + // Act + const message = createTestKafkaMessage({ + value: customValue, + offset: "100", + }); + + // Assert + expect(message.value).toBe(customValue); + expect(message.offset).toBe("100"); + }); +}); + +// ============================================================================= +// Domain Fixture Tests +// ============================================================================= + +describe("createTestSession", () => { + it("should create a valid session fixture", () => { + // Act + const session = createTestSession(); + + // Assert + expect(session.id).toHaveLength(26); + expect(session.labels).toEqual(["Session"]); + expect(session.user_id).toBe("test-user"); + expect(session.started_at).toBeDefined(); + expect(session.vt_start).toBeDefined(); + expect(session.tt_start).toBeDefined(); + }); + + it("should allow overriding properties", () => { + // Act + const session = createTestSession({ + user_id: "custom-user", + working_dir: "/home/user/project", + agent_type: "claude-code", + }); + + // Assert + expect(session.user_id).toBe("custom-user"); + expect(session.working_dir).toBe("/home/user/project"); + expect(session.agent_type).toBe("claude-code"); + }); +}); + +describe("createTestTurn", () => { + it("should create a valid turn fixture", () => { + // Act + const turn = createTestTurn(); + + // Assert + expect(turn.id).toHaveLength(26); + expect(turn.labels).toEqual(["Turn"]); + expect(turn.user_content).toBe("Test user prompt"); + expect(turn.user_content_hash).toHaveLength(64); + expect(turn.sequence_index).toBe(0); + expect(turn.files_touched).toEqual([]); + expect(turn.tool_calls_count).toBe(0); + }); + + it("should allow overriding properties", () => { + // Act + const turn = createTestTurn({ + user_content: "How do I create a file?", + sequence_index: 5, + tool_calls_count: 3, + }); + + // Assert + expect(turn.user_content).toBe("How do I create a file?"); + expect(turn.sequence_index).toBe(5); + expect(turn.tool_calls_count).toBe(3); + }); +}); + +describe("createTestToolCall", () => { + it("should create a valid tool call fixture", () => { + // Act + const toolCall = createTestToolCall(); + + // Assert + expect(toolCall.id).toHaveLength(26); + expect(toolCall.labels).toEqual(["ToolCall"]); + expect(toolCall.call_id).toMatch(/^toolu_/); + expect(toolCall.tool_name).toBe("TestTool"); + expect(toolCall.tool_type).toBe("unknown"); + expect(toolCall.status).toBe("success"); + }); + + it("should allow overriding properties", () => { + // Act + const toolCall = createTestToolCall({ + tool_name: "Read", + tool_type: "file_read", + arguments_json: JSON.stringify({ file_path: "/src/index.ts" }), + }); + + // Assert + expect(toolCall.tool_name).toBe("Read"); + expect(toolCall.tool_type).toBe("file_read"); + expect(JSON.parse(toolCall.arguments_json)).toEqual({ file_path: "/src/index.ts" }); + }); +}); + +describe("createTestReasoning", () => { + it("should create a valid reasoning fixture", () => { + // Act + const reasoning = createTestReasoning(); + + // Assert + expect(reasoning.id).toHaveLength(26); + expect(reasoning.labels).toEqual(["Reasoning"]); + expect(reasoning.content_hash).toHaveLength(64); + expect(reasoning.preview).toBe("Test reasoning content"); + expect(reasoning.reasoning_type).toBe("unknown"); + }); +}); + +describe("createTestFileTouch", () => { + it("should create a valid file touch fixture", () => { + // Act + const fileTouch = createTestFileTouch(); + + // Assert + expect(fileTouch.id).toHaveLength(26); + expect(fileTouch.labels).toEqual(["FileTouch"]); + expect(fileTouch.file_path).toBe("test/file.ts"); + expect(fileTouch.action).toBe("read"); + }); +}); + +describe("createTestObservation", () => { + it("should create a valid observation fixture", () => { + // Act + const observation = createTestObservation(); + + // Assert + expect(observation.id).toHaveLength(26); + expect(observation.labels).toEqual(["Observation"]); + expect(observation.tool_call_id).toMatch(/^toolu_/); + expect(observation.content).toBe("Test observation content"); + expect(observation.is_error).toBe(false); + }); +}); + +// ============================================================================= +// Test Utility Tests +// ============================================================================= + +describe("wait", () => { + it("should wait for specified duration", async () => { + // Arrange + const start = Date.now(); + + // Act + await wait(50); + + // Assert + const elapsed = Date.now() - start; + expect(elapsed).toBeGreaterThanOrEqual(45); // Allow small variance + }); +}); + +describe("createDeferred", () => { + it("should create a controllable promise", async () => { + // Arrange + const { promise, resolve } = createDeferred(); + let resolved = false; + + // Act + const resultPromise = promise.then((v) => { + resolved = true; + return v; + }); + + // Assert - not resolved yet + await wait(10); + expect(resolved).toBe(false); + + // Resolve and check + resolve("done"); + const result = await resultPromise; + expect(result).toBe("done"); + expect(resolved).toBe(true); + }); + + it("should support rejection", async () => { + // Arrange + const { promise, reject } = createDeferred(); + const error = new Error("test error"); + + // Act + reject(error); + + // Assert + await expect(promise).rejects.toThrow("test error"); + }); +}); + +describe("expectToReject", () => { + it("should pass when promise rejects with expected error type", async () => { + // Arrange + const promise = Promise.reject(new TypeError("invalid type")); + + // Act & Assert + const error = await expectToReject(promise, TypeError); + expect(error).toBeInstanceOf(TypeError); + }); + + it("should pass when error message matches string", async () => { + // Arrange + const promise = Promise.reject(new Error("invalid input value")); + + // Act & Assert + const error = await expectToReject(promise, Error, "invalid input"); + expect(error.message).toContain("invalid input"); + }); + + it("should pass when error message matches regex", async () => { + // Arrange + const promise = Promise.reject(new Error("Error code: 404")); + + // Act & Assert + const error = await expectToReject(promise, Error, /code: \d+/); + expect(error.message).toMatch(/code: \d+/); + }); + + it("should fail when promise resolves", async () => { + // Arrange + const promise = Promise.resolve("success"); + + // Act + let thrownError: Error | undefined; + try { + await expectToReject(promise, Error); + } catch (error) { + thrownError = error as Error; + } + + // Assert + expect(thrownError).toBeDefined(); + expect(thrownError?.message).toContain("Expected promise to reject"); + }); + + it("should fail when error type does not match", async () => { + // Arrange + const promise = Promise.reject(new TypeError("wrong type")); + + // Act + let thrownError: Error | undefined; + try { + await expectToReject(promise, RangeError); + } catch (error) { + thrownError = error as Error; + } + + // Assert + expect(thrownError).toBeDefined(); + expect(thrownError?.message).toContain("Expected RangeError but got TypeError"); + }); +}); + +describe("spyOnConsole", () => { + it("should capture console.log output", () => { + // Arrange + const { logs, restore } = spyOnConsole(); + + // Act + console.log("test message"); + console.log("another", "message"); + + // Assert + expect(logs).toContain("test message"); + expect(logs).toContain("another message"); + + // Cleanup + restore(); + }); + + it("should capture console.error output", () => { + // Arrange + const { errors, restore } = spyOnConsole(); + + // Act + console.error("error message"); + + // Assert + expect(errors).toContain("error message"); + + // Cleanup + restore(); + }); + + it("should capture console.warn output", () => { + // Arrange + const { warns, restore } = spyOnConsole(); + + // Act + console.warn("warning message"); + + // Assert + expect(warns).toContain("warning message"); + + // Cleanup + restore(); + }); + + it("should restore original console methods", () => { + // Arrange + const originalLog = console.log; + const { restore } = spyOnConsole(); + + // Act + restore(); + + // Assert + expect(console.log).toBe(originalLog); + }); +}); diff --git a/packages/common/src/testing/index.ts b/packages/common/src/testing/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a3a5738e80a7b46071cdfb65ef0d39b60133d14 --- /dev/null +++ b/packages/common/src/testing/index.ts @@ -0,0 +1,530 @@ +/** + * @engram/common/testing - Shared test utilities and mock factories for the Engram system. + * + * This module provides reusable test infrastructure for integration and unit testing + * across the monorepo. It includes mock factories for storage interfaces and + * fixture helpers for domain types. + * + * @example + * ```ts + * import { + * createTestGraphClient, + * createTestKafkaClient, + * createTestSession, + * createTestTurn, + * } from "@engram/common/testing"; + * + * describe("MyService", () => { + * it("should handle session creation", async () => { + * // Arrange + * const graphClient = createTestGraphClient(); + * const session = createTestSession({ user_id: "user-123" }); + * + * // Act + * await myService.createSession(session); + * + * // Assert + * expect(graphClient.query).toHaveBeenCalled(); + * }); + * }); + * ``` + * + * @module @engram/common/testing + */ + +import type { + FileTouchNode, + ObservationNode, + ReasoningNode, + SessionNode, + ToolCallNode, + TurnNode, +} from "@engram/graph"; +import type { + BlobStore, + Consumer, + ConsumerConfig, + GraphClient, + KafkaMessage, + MessageClient, + Producer, + RedisPublisher, +} from "@engram/storage"; +import { vi } from "vitest"; + +// ============================================================================= +// ID Generation Utilities +// ============================================================================= + +/** + * Generate a test ULID-like ID for use in fixtures. + * Format: 01XXXX... (26 character ULID format) + */ +export function createTestId(prefix = "01TEST"): string { + const chars = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + let result = prefix; + while (result.length < 26) { + result += chars[Math.floor(Math.random() * chars.length)]; + } + return result.slice(0, 26); +} + +/** + * Generate a test content hash (SHA256-like). + */ +export function createTestHash(): string { + return Array.from({ length: 64 }, () => Math.floor(Math.random() * 16).toString(16)).join(""); +} + +// ============================================================================= +// Bitemporal Time Utilities +// ============================================================================= + +const INFINITY_END = 9999999999999; + +/** + * Create bitemporal timestamps for test fixtures. + * Returns valid time and transaction time bounds. + */ +export function createTestBitemporalProps(overrides?: { + vt_start?: number; + vt_end?: number; + tt_start?: number; + tt_end?: number; +}): { vt_start: number; vt_end: number; tt_start: number; tt_end: number } { + const now = Date.now(); + return { + vt_start: overrides?.vt_start ?? now, + vt_end: overrides?.vt_end ?? INFINITY_END, + tt_start: overrides?.tt_start ?? now, + tt_end: overrides?.tt_end ?? INFINITY_END, + }; +} + +// ============================================================================= +// Mock Producer/Consumer for Kafka +// ============================================================================= + +/** + * Create a mock Kafka producer with vi.fn() stubs. + */ +export function createTestProducer(overrides?: Partial): Producer { + return { + connect: vi.fn().mockResolvedValue(undefined), + disconnect: vi.fn().mockResolvedValue(undefined), + send: vi.fn().mockResolvedValue(undefined), + ...overrides, + }; +} + +/** + * Create a mock Kafka consumer with vi.fn() stubs. + */ +export function createTestConsumer(overrides?: Partial): Consumer { + return { + connect: vi.fn().mockResolvedValue(undefined), + disconnect: vi.fn().mockResolvedValue(undefined), + subscribe: vi.fn().mockResolvedValue(undefined), + run: vi.fn(), + ...overrides, + }; +} + +// ============================================================================= +// Storage Interface Mock Factories +// ============================================================================= + +/** + * Create a mock GraphClient with vi.fn() stubs. + * All methods are mocked with sensible defaults that can be overridden. + * + * @example + * ```ts + * const graphClient = createTestGraphClient({ + * query: vi.fn().mockResolvedValue([{ id: "123", name: "test" }]), + * }); + * ``` + */ +export function createTestGraphClient(overrides?: Partial): GraphClient { + return { + connect: vi.fn().mockResolvedValue(undefined), + disconnect: vi.fn().mockResolvedValue(undefined), + query: vi.fn().mockResolvedValue([]), + isConnected: vi.fn().mockReturnValue(true), + ...overrides, + }; +} + +/** + * Create a mock MessageClient (Kafka) with vi.fn() stubs. + * Returns pre-configured mock producer and consumer instances. + * + * @example + * ```ts + * const kafkaClient = createTestKafkaClient(); + * const producer = await kafkaClient.getProducer(); + * await producer.send({ topic: "events", messages: [...] }); + * expect(producer.send).toHaveBeenCalledWith({ topic: "events", messages: [...] }); + * ``` + */ +export function createTestKafkaClient(overrides?: Partial): MessageClient { + const mockProducer = createTestProducer(); + const mockConsumer = createTestConsumer(); + + return { + getProducer: vi.fn().mockResolvedValue(mockProducer), + getConsumer: vi.fn((_config: ConsumerConfig) => Promise.resolve(mockConsumer)), + disconnect: vi.fn().mockResolvedValue(undefined), + ...overrides, + }; +} + +/** + * Create a mock RedisPublisher with vi.fn() stubs. + * + * @example + * ```ts + * const redisPublisher = createTestRedisPublisher(); + * await redisPublisher.publishSessionUpdate("session-123", { type: "turn_added" }); + * expect(redisPublisher.publishSessionUpdate).toHaveBeenCalledWith("session-123", { type: "turn_added" }); + * ``` + */ +export function createTestRedisPublisher(overrides?: Partial): RedisPublisher { + return { + publishSessionUpdate: vi.fn().mockResolvedValue(undefined), + disconnect: vi.fn().mockResolvedValue(undefined), + ...overrides, + }; +} + +/** + * Create a mock BlobStore with vi.fn() stubs. + * + * @example + * ```ts + * const blobStore = createTestBlobStore({ + * load: vi.fn().mockResolvedValue("file contents"), + * }); + * ``` + */ +export function createTestBlobStore(overrides?: Partial): BlobStore { + return { + save: vi.fn().mockResolvedValue("file://test/blob/abc123"), + load: vi.fn().mockResolvedValue(""), + ...overrides, + }; +} + +// ============================================================================= +// Kafka Message Helpers +// ============================================================================= + +/** + * Create a test Kafka message payload. + */ +export function createTestKafkaMessage(overrides?: Partial): KafkaMessage { + return { + key: Buffer.from("test-key"), + value: Buffer.from(JSON.stringify({ type: "test", data: {} })), + offset: "0", + timestamp: String(Date.now()), + ...overrides, + }; +} + +// ============================================================================= +// Domain Model Fixture Factories +// ============================================================================= + +/** + * Create a test Session fixture. + * All required fields are populated with sensible defaults. + * + * @example + * ```ts + * const session = createTestSession({ + * user_id: "user-123", + * working_dir: "/home/user/project", + * }); + * ``` + */ +export function createTestSession(overrides?: Partial): SessionNode { + const bitemporal = createTestBitemporalProps(); + return { + id: createTestId("01SESS"), + labels: ["Session"] as const, + user_id: "test-user", + started_at: Date.now(), + agent_type: "unknown", + ...bitemporal, + ...overrides, + } as SessionNode; +} + +/** + * Create a test Turn fixture. + * Represents a single conversation turn (user prompt + assistant response). + * + * @example + * ```ts + * const turn = createTestTurn({ + * user_content: "How do I create a new file?", + * sequence_index: 0, + * }); + * ``` + */ +export function createTestTurn(overrides?: Partial): TurnNode { + const bitemporal = createTestBitemporalProps(); + const userContent = overrides?.user_content ?? "Test user prompt"; + return { + id: createTestId("01TURN"), + labels: ["Turn"] as const, + user_content: userContent, + user_content_hash: createTestHash(), + assistant_preview: "Test assistant response preview", + sequence_index: 0, + files_touched: [], + tool_calls_count: 0, + ...bitemporal, + ...overrides, + } as TurnNode; +} + +/** + * Create a test ToolCall fixture. + * Represents a tool invocation within a turn. + * + * @example + * ```ts + * const toolCall = createTestToolCall({ + * tool_name: "Read", + * tool_type: "file_read", + * arguments_json: JSON.stringify({ file_path: "/src/index.ts" }), + * }); + * ``` + */ +export function createTestToolCall(overrides?: Partial): ToolCallNode { + const bitemporal = createTestBitemporalProps(); + return { + id: createTestId("01TOOL"), + labels: ["ToolCall"] as const, + call_id: `toolu_${createTestId("01CALL")}`, + tool_name: "TestTool", + tool_type: "unknown", + arguments_json: "{}", + status: "success", + sequence_index: 0, + ...bitemporal, + ...overrides, + } as ToolCallNode; +} + +/** + * Create a test Reasoning fixture. + * Represents a thinking/reasoning block within a turn. + * + * @example + * ```ts + * const reasoning = createTestReasoning({ + * preview: "I should read the file first to understand its structure...", + * reasoning_type: "planning", + * }); + * ``` + */ +export function createTestReasoning(overrides?: Partial): ReasoningNode { + const bitemporal = createTestBitemporalProps(); + return { + id: createTestId("01REAS"), + labels: ["Reasoning"] as const, + content_hash: createTestHash(), + preview: "Test reasoning content", + reasoning_type: "unknown", + sequence_index: 0, + ...bitemporal, + ...overrides, + } as ReasoningNode; +} + +/** + * Create a test FileTouch fixture. + * Represents a file operation within a turn. + * + * @example + * ```ts + * const fileTouch = createTestFileTouch({ + * file_path: "src/auth/login.ts", + * action: "edit", + * lines_added: 5, + * lines_removed: 2, + * }); + * ``` + */ +export function createTestFileTouch(overrides?: Partial): FileTouchNode { + const bitemporal = createTestBitemporalProps(); + return { + id: createTestId("01FILE"), + labels: ["FileTouch"] as const, + file_path: "test/file.ts", + action: "read", + ...bitemporal, + ...overrides, + } as FileTouchNode; +} + +/** + * Create a test Observation fixture. + * Represents tool execution results. + * + * @example + * ```ts + * const observation = createTestObservation({ + * tool_call_id: "toolu_01ABC...", + * content: "File contents here...", + * is_error: false, + * }); + * ``` + */ +export function createTestObservation(overrides?: Partial): ObservationNode { + const bitemporal = createTestBitemporalProps(); + return { + id: createTestId("01OBSR"), + labels: ["Observation"] as const, + tool_call_id: `toolu_${createTestId("01CALL")}`, + content: "Test observation content", + is_error: false, + ...bitemporal, + ...overrides, + } as ObservationNode; +} + +// ============================================================================= +// Test Utilities +// ============================================================================= + +/** + * Wait for a specified number of milliseconds. + * Useful for testing async operations with timing. + */ +export function wait(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Create a deferred promise for testing async control flow. + * + * @example + * ```ts + * const { promise, resolve, reject } = createDeferred(); + * // Later... + * resolve("done"); + * await promise; // "done" + * ``` + */ +export function createDeferred(): { + promise: Promise; + resolve: (value: T) => void; + reject: (error: unknown) => void; +} { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +// Sentinel class to distinguish "promise resolved" errors from actual rejections +class PromiseResolvedError extends Error { + constructor(expectedType: string) { + super(`Expected promise to reject with ${expectedType}, but it resolved`); + this.name = "PromiseResolvedError"; + } +} + +/** + * Assert that a promise rejects with a specific error type. + * + * @example + * ```ts + * await expectToReject( + * myService.doSomething(), + * ValidationError, + * "Invalid input" + * ); + * ``` + */ +export async function expectToReject( + promise: Promise, + errorType: new (...args: unknown[]) => E, + messageMatch?: string | RegExp, +): Promise { + try { + await promise; + throw new PromiseResolvedError(errorType.name); + } catch (error) { + // Re-throw our sentinel error + if (error instanceof PromiseResolvedError) { + throw error; + } + if (!(error instanceof errorType)) { + throw new Error( + `Expected ${errorType.name} but got ${(error as Error).constructor.name}: ${(error as Error).message}`, + ); + } + if (messageMatch) { + const matches = + typeof messageMatch === "string" + ? error.message.includes(messageMatch) + : messageMatch.test(error.message); + if (!matches) { + throw new Error( + `Error message "${error.message}" does not match expected pattern "${messageMatch}"`, + ); + } + } + return error; + } +} + +/** + * Spy on console methods and capture output. + * Returns cleanup function to restore original methods. + * + * @example + * ```ts + * const { logs, errors, restore } = spyOnConsole(); + * myService.doSomething(); + * expect(logs).toContain("Operation completed"); + * restore(); + * ``` + */ +export function spyOnConsole(): { + logs: string[]; + errors: string[]; + warns: string[]; + restore: () => void; +} { + const logs: string[] = []; + const errors: string[] = []; + const warns: string[] = []; + + const originalLog = console.log; + const originalError = console.error; + const originalWarn = console.warn; + + console.log = (...args: unknown[]) => logs.push(args.map(String).join(" ")); + console.error = (...args: unknown[]) => errors.push(args.map(String).join(" ")); + console.warn = (...args: unknown[]) => warns.push(args.map(String).join(" ")); + + return { + logs, + errors, + warns, + restore: () => { + console.log = originalLog; + console.error = originalError; + console.warn = originalWarn; + }, + }; +} diff --git a/packages/common/src/utils/env.ts b/packages/common/src/utils/env.ts new file mode 100644 index 0000000000000000000000000000000000000000..da84379923f8360775f8a342386bcf0b3581262b --- /dev/null +++ b/packages/common/src/utils/env.ts @@ -0,0 +1,137 @@ +/** + * Environment variable utilities. + * + * Provides type-safe helpers for reading environment variables with defaults. + * Consolidates patterns from across the codebase into a single source of truth. + * + * @module @engram/common/utils/env + */ + +/** + * Parse a boolean from an environment variable. + * + * Recognizes "true", "1" as true (case-insensitive). + * Returns defaultValue if the environment variable is not set. + * + * @param key - Environment variable name + * @param defaultValue - Default value if not set + * @returns Parsed boolean value + * + * @example + * ```ts + * const debug = envBool("DEBUG", false); + * const enabled = envBool("FEATURE_ENABLED", true); + * ``` + */ +export function envBool(key: string, defaultValue: boolean): boolean { + const val = process.env[key]; + if (val === undefined) return defaultValue; + return val.toLowerCase() === "true" || val === "1"; +} + +/** + * Parse a number from an environment variable. + * + * Returns defaultValue if the environment variable is not set or not a valid number. + * + * @param key - Environment variable name + * @param defaultValue - Default value if not set or invalid + * @returns Parsed number value + * + * @example + * ```ts + * const port = envNum("PORT", 3000); + * const timeout = envNum("TIMEOUT_MS", 5000); + * ``` + */ +export function envNum(key: string, defaultValue: number): number { + const val = process.env[key]; + if (val === undefined) return defaultValue; + const parsed = Number.parseInt(val, 10); + return Number.isNaN(parsed) ? defaultValue : parsed; +} + +/** + * Parse a float from an environment variable. + * + * Returns defaultValue if the environment variable is not set or not a valid number. + * + * @param key - Environment variable name + * @param defaultValue - Default value if not set or invalid + * @returns Parsed float value + * + * @example + * ```ts + * const threshold = envFloat("SCORE_THRESHOLD", 0.75); + * ``` + */ +export function envFloat(key: string, defaultValue: number): number { + const val = process.env[key]; + if (val === undefined) return defaultValue; + const parsed = Number.parseFloat(val); + return Number.isNaN(parsed) ? defaultValue : parsed; +} + +/** + * Get a string from an environment variable. + * + * Returns defaultValue if the environment variable is not set. + * + * @param key - Environment variable name + * @param defaultValue - Default value if not set + * @returns String value + * + * @example + * ```ts + * const host = envStr("REDIS_HOST", "localhost"); + * const model = envStr("RERANK_MODEL", "ms-marco-MiniLM-L-6-v2"); + * ``` + */ +export function envStr(key: string, defaultValue: string): string { + return process.env[key] ?? defaultValue; +} + +/** + * Get a required environment variable. + * + * Throws an error if the environment variable is not set. + * + * @param key - Environment variable name + * @returns String value + * @throws Error if the environment variable is not set + * + * @example + * ```ts + * const apiKey = envRequired("API_KEY"); // Throws if not set + * ``` + */ +export function envRequired(key: string): string { + const val = process.env[key]; + if (val === undefined || val === "") { + throw new Error(`Required environment variable ${key} is not set`); + } + return val; +} + +/** + * Get an environment variable as a string array. + * + * Splits the value by the specified delimiter. + * Returns defaultValue if the environment variable is not set. + * + * @param key - Environment variable name + * @param defaultValue - Default value if not set + * @param delimiter - Delimiter to split on (default: ",") + * @returns Array of strings + * + * @example + * ```ts + * const brokers = envArray("KAFKA_BROKERS", ["localhost:9092"]); + * const hosts = envArray("REDIS_HOSTS", ["127.0.0.1"], ";"); + * ``` + */ +export function envArray(key: string, defaultValue: string[], delimiter: string = ","): string[] { + const val = process.env[key]; + if (val === undefined || val === "") return defaultValue; + return val.split(delimiter).map((item) => item.trim()); +} diff --git a/packages/common/src/utils/format.ts b/packages/common/src/utils/format.ts new file mode 100644 index 0000000000000000000000000000000000000000..186523ca90fc01f9393c56fd3f2e82da20ca1d5d --- /dev/null +++ b/packages/common/src/utils/format.ts @@ -0,0 +1,129 @@ +/** + * Formatting utilities. + * + * Provides consistent formatting functions for display and logging. + * + * @module @engram/common/utils/format + */ + +/** + * Format a timestamp as a relative time string. + * + * Used for displaying timestamps in a human-friendly format. + * + * @param timestamp - Unix timestamp in milliseconds + * @returns Relative time string (e.g., "now", "5m", "2h", "3d") + * + * @example + * ```ts + * formatRelativeTime(Date.now() - 30000); // => "now" (less than 1 minute) + * formatRelativeTime(Date.now() - 300000); // => "5m" + * formatRelativeTime(Date.now() - 7200000); // => "2h" + * formatRelativeTime(Date.now() - 259200000); // => "3d" + * ``` + */ +export function formatRelativeTime(timestamp: number): string { + const now = Date.now(); + const diff = now - timestamp; + + const minutes = Math.floor(diff / 60000); + const hours = Math.floor(diff / 3600000); + const days = Math.floor(diff / 86400000); + + if (minutes < 1) return "now"; + if (minutes < 60) return `${minutes}m`; + if (hours < 24) return `${hours}h`; + if (days < 7) return `${days}d`; + + return new Date(timestamp).toLocaleDateString("en-US", { + month: "short", + day: "numeric", + }); +} + +/** + * Truncate an ID for display. + * + * Returns the first `length` characters of an ID, useful for UUIDs and hashes. + * + * @param id - ID to truncate + * @param length - Maximum length (default: 8) + * @returns Truncated ID + * + * @example + * ```ts + * truncateId("550e8400-e29b-41d4-a716-446655440000"); // => "550e8400" + * truncateId("abc"); // => "abc" + * ``` + */ +export function truncateId(id: string, length: number = 8): string { + if (id.length <= length) return id; + return id.slice(0, length); +} + +/** + * Truncate text with ellipsis. + * + * @param text - Text to truncate + * @param maxLength - Maximum length including ellipsis + * @param ellipsis - Ellipsis string (default: "...") + * @returns Truncated text + * + * @example + * ```ts + * truncateText("Hello, World!", 10); // => "Hello, ..." + * truncateText("Hi", 10); // => "Hi" + * ``` + */ +export function truncateText(text: string, maxLength: number, ellipsis: string = "..."): string { + if (text.length <= maxLength) return text; + return text.slice(0, maxLength - ellipsis.length) + ellipsis; +} + +/** + * Format bytes as a human-readable string. + * + * @param bytes - Number of bytes + * @param decimals - Decimal places (default: 2) + * @returns Formatted string (e.g., "1.5 KB", "2.3 MB") + * + * @example + * ```ts + * formatBytes(1024); // => "1 KB" + * formatBytes(1536); // => "1.5 KB" + * formatBytes(1048576); // => "1 MB" + * ``` + */ +export function formatBytes(bytes: number, decimals: number = 2): string { + if (bytes === 0) return "0 Bytes"; + + const k = 1024; + const sizes = ["Bytes", "KB", "MB", "GB", "TB"]; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + + return `${Number.parseFloat((bytes / k ** i).toFixed(decimals))} ${sizes[i]}`; +} + +/** + * Format milliseconds as a human-readable duration. + * + * @param ms - Duration in milliseconds + * @returns Formatted duration (e.g., "1.5s", "250ms", "2m 30s") + * + * @example + * ```ts + * formatDuration(150); // => "150ms" + * formatDuration(1500); // => "1.5s" + * formatDuration(90000); // => "1m 30s" + * ``` + */ +export function formatDuration(ms: number): string { + if (ms < 1000) return `${ms}ms`; + if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`; + + const minutes = Math.floor(ms / 60000); + const seconds = Math.floor((ms % 60000) / 1000); + + if (seconds === 0) return `${minutes}m`; + return `${minutes}m ${seconds}s`; +} diff --git a/packages/common/src/utils/hash.ts b/packages/common/src/utils/hash.ts new file mode 100644 index 0000000000000000000000000000000000000000..44914056457596c25e5de76c519c1c494d03e10b --- /dev/null +++ b/packages/common/src/utils/hash.ts @@ -0,0 +1,66 @@ +/** + * Hashing utilities. + * + * Provides consistent hashing functions used across the codebase. + * + * @module @engram/common/utils/hash + */ + +import { createHash } from "node:crypto"; + +/** + * Generate a SHA-256 hash of the given content. + * + * Used for content-addressable storage, cache keys, and deduplication. + * + * @param content - Content to hash (string or Buffer) + * @returns Hexadecimal hash string (64 characters) + * + * @example + * ```ts + * const hash = sha256Hash("Hello, World!"); + * // => "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f" + * ``` + */ +export function sha256Hash(content: string | Buffer): string { + return createHash("sha256").update(content).digest("hex"); +} + +/** + * Generate a short hash suitable for display or IDs. + * + * Returns the first `length` characters of a SHA-256 hash. + * + * @param content - Content to hash + * @param length - Number of characters (default: 8) + * @returns Truncated hexadecimal hash string + * + * @example + * ```ts + * const shortHash = sha256Short("Hello, World!"); + * // => "dffd6021" + * ``` + */ +export function sha256Short(content: string | Buffer, length: number = 8): string { + return sha256Hash(content).slice(0, length); +} + +/** + * Generate a deterministic hash from a JSON-serializable object. + * + * Keys are sorted to ensure consistent hashing regardless of property order. + * + * @param obj - Object to hash + * @returns Hexadecimal hash string + * + * @example + * ```ts + * const hash1 = hashObject({ b: 2, a: 1 }); + * const hash2 = hashObject({ a: 1, b: 2 }); + * // hash1 === hash2 + * ``` + */ +export function hashObject(obj: unknown): string { + const normalized = JSON.stringify(obj, Object.keys(obj as object).sort()); + return sha256Hash(normalized); +} diff --git a/packages/common/src/utils/index.ts b/packages/common/src/utils/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7e36359df477e50fbf412a3f44b830e0411bd5d --- /dev/null +++ b/packages/common/src/utils/index.ts @@ -0,0 +1,17 @@ +/** + * Utility functions for the Engram system. + * + * @module @engram/common/utils + */ + +export { envArray, envBool, envFloat, envNum, envRequired, envStr } from "./env"; +export { + formatBytes, + formatDuration, + formatRelativeTime, + truncateId, + truncateText, +} from "./format"; +export { hashObject, sha256Hash, sha256Short } from "./hash"; +export type { RetryOptions } from "./retry"; +export { RetryableErrors, withRetry } from "./retry"; diff --git a/packages/common/src/utils/retry.ts b/packages/common/src/utils/retry.ts new file mode 100644 index 0000000000000000000000000000000000000000..4bcaddae4e4bb530c19d39127c9a45fb9129715a --- /dev/null +++ b/packages/common/src/utils/retry.ts @@ -0,0 +1,193 @@ +/** + * Retry utilities. + * + * Provides retry logic with exponential backoff for transient failures. + * + * @module @engram/common/utils/retry + */ + +/** + * Options for the retry function. + */ +export interface RetryOptions { + /** Maximum number of retry attempts (default: 3) */ + maxRetries?: number; + /** Initial delay in milliseconds (default: 1000) */ + initialDelayMs?: number; + /** Maximum delay in milliseconds (default: 30000) */ + maxDelayMs?: number; + /** Backoff multiplier (default: 2) */ + backoffMultiplier?: number; + /** Jitter factor 0-1 to add randomness (default: 0.1) */ + jitter?: number; + /** Function to determine if error is retryable (default: always retry) */ + isRetryable?: (error: unknown) => boolean; + /** Callback invoked on each retry attempt */ + onRetry?: (error: unknown, attempt: number, delayMs: number) => void; +} + +/** + * Sleep for the specified duration. + */ +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Calculate delay with exponential backoff and jitter. + */ +function calculateDelay( + attempt: number, + initialDelayMs: number, + maxDelayMs: number, + backoffMultiplier: number, + jitter: number, +): number { + // Exponential backoff + const exponentialDelay = initialDelayMs * backoffMultiplier ** attempt; + + // Cap at max delay + const cappedDelay = Math.min(exponentialDelay, maxDelayMs); + + // Add jitter + const jitterAmount = cappedDelay * jitter * Math.random(); + + return Math.floor(cappedDelay + jitterAmount); +} + +/** + * Execute a function with retry logic and exponential backoff. + * + * @param fn - Async function to execute + * @param options - Retry configuration + * @returns Result of the function + * @throws Last error if all retries fail + * + * @example + * ```ts + * // Basic usage + * const result = await withRetry(() => fetchData(url)); + * + * // With options + * const result = await withRetry( + * () => apiCall(), + * { + * maxRetries: 5, + * initialDelayMs: 500, + * isRetryable: (e) => e instanceof NetworkError, + * onRetry: (e, attempt) => console.log(`Retry ${attempt}`) + * } + * ); + * ``` + */ +export async function withRetry(fn: () => Promise, options: RetryOptions = {}): Promise { + const { + maxRetries = 3, + initialDelayMs = 1000, + maxDelayMs = 30000, + backoffMultiplier = 2, + jitter = 0.1, + isRetryable = () => true, + onRetry, + } = options; + + let lastError: unknown; + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + try { + return await fn(); + } catch (error) { + lastError = error; + + // Check if we've exhausted retries + if (attempt >= maxRetries) { + throw error; + } + + // Check if error is retryable + if (!isRetryable(error)) { + throw error; + } + + // Calculate delay + const delayMs = calculateDelay( + attempt, + initialDelayMs, + maxDelayMs, + backoffMultiplier, + jitter, + ); + + // Invoke callback if provided + if (onRetry) { + onRetry(error, attempt + 1, delayMs); + } + + // Wait before retrying + await sleep(delayMs); + } + } + + // This should never be reached, but TypeScript needs it + throw lastError; +} + +/** + * Common retryable error patterns. + * + * Use with the `isRetryable` option. + */ +export const RetryableErrors = { + /** + * Check if error is a network error. + */ + isNetworkError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + + const networkErrorPatterns = [ + "fetch failed", + "ECONNREFUSED", + "ENOTFOUND", + "ETIMEDOUT", + "ECONNRESET", + "socket hang up", + "network error", + ]; + + return networkErrorPatterns.some((pattern) => + error.message.toLowerCase().includes(pattern.toLowerCase()), + ); + }, + + /** + * Check if error is a rate limit error (HTTP 429). + */ + isRateLimitError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + return error.message.includes("429") || error.message.toLowerCase().includes("rate limit"); + }, + + /** + * Check if error is a server error (HTTP 5xx). + */ + isServerError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + + const serverErrorPatterns = ["500", "502", "503", "504", "server error"]; + + return serverErrorPatterns.some((pattern) => + error.message.toLowerCase().includes(pattern.toLowerCase()), + ); + }, + + /** + * Check if error is any transient error (network, rate limit, or server). + */ + isTransientError(error: unknown): boolean { + return ( + RetryableErrors.isNetworkError(error) || + RetryableErrors.isRateLimitError(error) || + RetryableErrors.isServerError(error) + ); + }, +}; diff --git a/packages/common/tsconfig.json b/packages/common/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..641a81dc7930b9224a4c9e017be08450bf43e9f0 --- /dev/null +++ b/packages/common/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@engram/tsconfig/base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "baseUrl": "." + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/graph/README.md b/packages/graph/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9ece49af65513b322602c4eb3dd5ba9df47fb776 --- /dev/null +++ b/packages/graph/README.md @@ -0,0 +1,91 @@ +# @engram/graph + +Graph database abstraction with bitemporal node and edge models. + +## Overview + +Abstracts FalkorDB operations and ensures all nodes/edges support bitemporal versioning (valid time and transaction time). Provides a fluent query builder and graph maintenance utilities. + +## Installation + +```bash +npm install @engram/graph +``` + +## Exports + +### GraphWriter + +```typescript +import { GraphWriter } from "@engram/graph"; + +const writer = new GraphWriter(client); + +// Write nodes with bitemporal fields +await writer.createNode("Session", { + id: "session-123", + started_at: new Date().toISOString(), + vt_start: new Date().toISOString(), + tt_start: new Date().toISOString(), +}); + +// Create edges +await writer.createEdge("HAS_TURN", sessionId, turnId); +``` + +### Node Models + +```typescript +import { BaseNode, SessionNode, TurnNode, ReasoningNode } from "@engram/graph"; + +// All nodes include bitemporal fields +interface BaseNode { + id: string; + vt_start: string; // Valid time start + vt_end?: string; // Valid time end + tt_start: string; // Transaction time start + tt_end?: string; // Transaction time end +} +``` + +### QueryBuilder + +```typescript +import { QueryBuilder } from "@engram/graph"; + +const query = new QueryBuilder() + .match("(s:Session)") + .where("s.id = $id") + .return("s") + .build(); +``` + +### Utilities + +```typescript +import { Merger, Pruner } from "@engram/graph"; + +// Merge duplicate nodes +const merger = new Merger(client); +await merger.mergeNodes("Session", "id"); + +// Prune old nodes +const pruner = new Pruner(client); +await pruner.pruneOlderThan(30); // days +``` + +## Bitemporal Model + +Every node and edge tracks two time dimensions: + +| Field | Description | +|:------|:------------| +| `vt_start` | When the fact became true in the real world | +| `vt_end` | When the fact stopped being true | +| `tt_start` | When we recorded this fact | +| `tt_end` | When we corrected/superseded this record | + +This enables: +- **Point-in-time queries**: What did we know at time T? +- **As-of queries**: What was true at time T? +- **Audit trails**: Complete history of changes diff --git a/packages/graph/package.json b/packages/graph/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c590cac4fbde59504ec2eb3540db296fbe48c868 --- /dev/null +++ b/packages/graph/package.json @@ -0,0 +1,21 @@ +{ + "name": "@engram/graph", + "version": "0.0.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "devDependencies": { + "typescript": "^5.9.3", + "@types/node": "^24.10.1", + "@engram/tsconfig": "*" + }, + "dependencies": { + "zod": "^4.1.13", + "ulid": "^3.0.2", + "@engram/storage": "*" + }, + "scripts": { + "build": "echo 'Build success'", + "typecheck": "tsc --noEmit" + } +} diff --git a/packages/graph/src/graph.test.ts b/packages/graph/src/graph.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..633b8ce3a9e2f2db97838dc9c5f5ad0cdafc21bb --- /dev/null +++ b/packages/graph/src/graph.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from "vitest"; +import { GraphWriter } from "./graph"; + +const mockFalkorClient = { + connect: vi.fn(async () => {}), + query: vi.fn(async () => []), + disconnect: vi.fn(async () => {}), +}; + +describe("GraphWriter", () => { + it("should write a node with bitemporal properties", async () => { + const writer = new GraphWriter(mockFalkorClient as any); + const data = { id: "node-1", content: "test" }; + + await writer.writeNode("TestLabel", data as any); + + expect(mockFalkorClient.query).toHaveBeenCalled(); + const call = mockFalkorClient.query.mock.calls[mockFalkorClient.query.mock.calls.length - 1]; + expect(call[0]).toContain("CREATE (n:TestLabel"); + expect(call[1]).toHaveProperty("tt_start"); + expect(call[1]).toHaveProperty("vt_start"); + }); + + it("should write an edge between nodes", async () => { + const writer = new GraphWriter(mockFalkorClient as any); + + await writer.writeEdge("node-1", "node-2", "LINKS_TO"); + + const call = mockFalkorClient.query.mock.calls[mockFalkorClient.query.mock.calls.length - 1]; + expect(call[0]).toContain("MATCH (a {id: $fromId}), (b {id: $toId})"); + expect(call[0]).toContain("CREATE (a)-[:LINKS_TO"); + expect(call[1]).toMatchObject({ fromId: "node-1", toId: "node-2" }); + }); + + it("should update node by writing new version and linking", async () => { + const writer = new GraphWriter(mockFalkorClient as any); + const newData = { id: "node-1-v2", content: "updated" }; + + // Mock writeNode and writeEdge calls internal to updateNode? + // Or just check the query calls. + // writeNode calls query, writeEdge calls query. + + await writer.updateNode("node-1-v1", "TestLabel", newData as any); + + // Should be 2 calls + const calls = mockFalkorClient.query.mock.calls.slice(-2); + expect(calls[0][0]).toContain("CREATE (n:TestLabel"); // writeNode + expect(calls[1][0]).toContain("CREATE (a)-[:REPLACES"); // writeEdge + }); + + it("should delete node by closing transaction time", async () => { + const writer = new GraphWriter(mockFalkorClient as any); + + await writer.deleteNode("node-1"); + + const call = mockFalkorClient.query.mock.calls[mockFalkorClient.query.mock.calls.length - 1]; + expect(call[0]).toContain("SET n.tt_end = $t"); + expect(call[1]).toHaveProperty("id", "node-1"); + }); +}); diff --git a/packages/graph/src/graph.ts b/packages/graph/src/graph.ts new file mode 100644 index 0000000000000000000000000000000000000000..7248b0b7e1264873f3f1091b36a6cd3b5f6c4b94 --- /dev/null +++ b/packages/graph/src/graph.ts @@ -0,0 +1,100 @@ +import type { FalkorClient, QueryParams } from "@engram/storage"; +import type { BaseNode } from "./models/base"; +import { createBitemporal, MAX_DATE, now } from "./utils/time"; + +/** + * Regex pattern for valid Cypher labels and relationship types. + * Labels/types must: + * - Start with a letter (a-z, A-Z) + * - Contain only letters, digits, and underscores + * - Be at most 100 characters long + */ +const VALID_CYPHER_IDENTIFIER = /^[a-zA-Z][a-zA-Z0-9_]{0,99}$/; + +/** + * Validate a label or relationship type to prevent Cypher injection. + * @param identifier The label or relationship type to validate + * @param type Description for error message (e.g., "label", "relationship type") + * @throws Error if the identifier is invalid + */ +function validateCypherIdentifier(identifier: string, type: string): void { + if (!VALID_CYPHER_IDENTIFIER.test(identifier)) { + throw new Error( + `Invalid ${type}: "${identifier}". Must start with a letter and contain only letters, digits, and underscores (max 100 chars).`, + ); + } +} + +export class GraphWriter { + constructor(private client: FalkorClient) {} + + async writeNode( + label: string, + data: Omit, + validFrom: number = now(), + ): Promise { + // Validate label to prevent Cypher injection + validateCypherIdentifier(label, "label"); + + const temporal = createBitemporal(validFrom); + const nodeData = { ...data, ...temporal }; + + const propKeys = Object.keys(nodeData); + const propsString = propKeys.map((k) => `${k}: $${k}`).join(", "); + + const query = `CREATE (n:${label} { ${propsString} })`; + + await this.client.query(query, nodeData as QueryParams); + } + + async writeEdge( + fromId: string, + toId: string, + relationType: string, + props: Record = {}, + validFrom: number = now(), + ): Promise { + // Validate relationship type to prevent Cypher injection + validateCypherIdentifier(relationType, "relationship type"); + + const temporal = createBitemporal(validFrom); + const edgeData = { ...props, ...temporal }; + + const propKeys = Object.keys(edgeData); + const propsString = propKeys.map((k) => `${k}: $${k}`).join(", "); + + const query = ` + MATCH (a {id: $fromId}), (b {id: $toId}) + CREATE (a)-[:${relationType} { ${propsString} }]->(b) + `; + + await this.client.query(query, { fromId, toId, ...edgeData }); + } + + // Transaction Time: Update (Append-Only / Replace) + async updateNode( + oldNodeId: string, + label: string, + newNodeData: Omit, + validFrom: number = now(), + ): Promise { + // 1. Write the new node version + await this.writeNode(label, newNodeData, validFrom); + + // 2. Link New -> Old via REPLACES + // We expect newNodeData to contain the new 'id' + await this.writeEdge(newNodeData.id, oldNodeId, "REPLACES", {}, validFrom); + } + + // Transaction Time: Delete (Logical Delete) + async deleteNode(id: string): Promise { + const t = now(); + // Close the transaction time interval for the current version + const query = ` + MATCH (n {id: $id}) + WHERE n.tt_end = ${MAX_DATE} + SET n.tt_end = $t + `; + await this.client.query(query, { id, t }); + } +} diff --git a/packages/graph/src/index.ts b/packages/graph/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..ababaefcd33c3f7514425013f667fbf33d1dd299 --- /dev/null +++ b/packages/graph/src/index.ts @@ -0,0 +1,9 @@ +export * from "./graph"; +export * from "./merger"; +export * from "./models/base"; +export * from "./models/edges"; +export * from "./models/nodes"; +export * from "./pruner"; +export * from "./queries/builder"; +export * from "./repositories"; +export * from "./utils/time"; diff --git a/packages/graph/src/merger.test.ts b/packages/graph/src/merger.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4040ca230cdf442d84be6a6425ce4eb81660e945 --- /dev/null +++ b/packages/graph/src/merger.test.ts @@ -0,0 +1,33 @@ +import type { FalkorClient } from "@engram/storage"; +import { describe, expect, it, vi } from "vitest"; +import { GraphMerger } from "./merger"; + +describe("GraphMerger", () => { + it("should move edges and delete source", async () => { + const mockQuery = vi.fn((query: string, _params: any) => { + if (query.includes("MATCH (s {id: $sourceId})-[r]-(n)")) { + // Return one outgoing edge + return Promise.resolve([["LINKS_TO", true, "neighbor-123", { weight: 1 }]]); + } + return Promise.resolve([]); + }); + + const mockFalkor = { + query: mockQuery, + } as unknown as FalkorClient; + + const merger = new GraphMerger(mockFalkor); + await merger.mergeNodes("target-1", "source-1"); + + // Expect 3 queries: 1 read edges, 1 create new edge, 1 delete source + expect(mockQuery).toHaveBeenCalledTimes(3); + + // Check creation of new edge + const createCall = mockQuery.mock.calls[1]; + expect(createCall[0]).toContain("MERGE (t)-[r:LINKS_TO]->(n)"); + + // Check deletion + const deleteCall = mockQuery.mock.calls[2]; + expect(deleteCall[0]).toContain("DETACH DELETE s"); + }); +}); diff --git a/packages/graph/src/merger.ts b/packages/graph/src/merger.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed4eff323f6043d60c4a277c1dfa9c7e52119091 --- /dev/null +++ b/packages/graph/src/merger.ts @@ -0,0 +1,73 @@ +import type { FalkorClient, QueryParams } from "@engram/storage"; + +/** + * Regex pattern for valid Cypher relationship types. + * Types must: + * - Start with a letter (a-z, A-Z) + * - Contain only letters, digits, and underscores + * - Be at most 100 characters long + */ +const VALID_RELATIONSHIP_TYPE = /^[a-zA-Z][a-zA-Z0-9_]{0,99}$/; + +/** + * Validate a relationship type to prevent Cypher injection. + * @param type The relationship type to validate + * @throws Error if the type is invalid + */ +function validateRelationshipType(type: string): void { + if (!VALID_RELATIONSHIP_TYPE.test(type)) { + throw new Error( + `Invalid relationship type: "${type}". Must start with a letter and contain only letters, digits, and underscores (max 100 chars).`, + ); + } +} + +export class GraphMerger { + constructor(private client: FalkorClient) {} + + async mergeNodes(targetId: string, sourceId: string) { + // 1. Get all edges connected to source + const edgesQuery = ` + MATCH (s {id: $sourceId})-[r]-(n) + RETURN type(r) as type, startNode(r) = s as isOutgoing, n.id as neighborId, properties(r) as props + `; + + const edgesResult = await this.client.query(edgesQuery, { sourceId }); + + if (!Array.isArray(edgesResult)) return; + + for (const row of edgesResult) { + const type = row[0] as string; + const isOutgoing = row[1] as boolean; + const neighborId = row[2] as string; + const props = (row[3] || {}) as QueryParams; + + // Validate relationship type to prevent Cypher injection + validateRelationshipType(type); + + // Re-create edge to target + let createQuery = ""; + if (isOutgoing) { + createQuery = ` + MATCH (t {id: $targetId}), (n {id: $neighborId}) + MERGE (t)-[r:${type}]->(n) + SET r = $props + `; + } else { + createQuery = ` + MATCH (t {id: $targetId}), (n {id: $neighborId}) + MERGE (n)-[r:${type}]->(t) + SET r = $props + `; + } + + await this.client.query(createQuery, { targetId, neighborId, props }); + } + + // 2. Delete source node (and its old edges) + const deleteQuery = `MATCH (s {id: $sourceId}) DETACH DELETE s`; + await this.client.query(deleteQuery, { sourceId }); + + console.log(`Merged node ${sourceId} into ${targetId}`); + } +} diff --git a/packages/graph/src/models/base.ts b/packages/graph/src/models/base.ts new file mode 100644 index 0000000000000000000000000000000000000000..58a7d849506fd4a34bee75dbe8b999bb12270d1c --- /dev/null +++ b/packages/graph/src/models/base.ts @@ -0,0 +1,110 @@ +import { z } from "zod"; + +// ============================================================================= +// Bitemporal Types - Source of Truth +// ============================================================================= + +/** + * Bitemporal properties for graph nodes. + * Supports both valid time (when data is true in reality) and + * transaction time (when data was recorded in the system). + * + * - vt_start/vt_end: Valid time interval (epoch ms) + * - tt_start/tt_end: Transaction time interval (epoch ms) + */ +export const BitemporalSchema = z.object({ + vt_start: z.number(), + vt_end: z.number(), + tt_start: z.number(), + tt_end: z.number(), +}); + +export type Bitemporal = z.infer; + +/** + * @deprecated Use Bitemporal instead + */ +export type BitemporalProperties = Bitemporal; + +// ============================================================================= +// Base Node Schema +// ============================================================================= + +/** + * Base schema for all graph nodes. + * All nodes have a unique ULID and labels, plus bitemporal properties. + */ +export const BaseNodeSchema = z + .object({ + id: z.string().ulid(), // Unique Node ID + labels: z.array(z.string()), // e.g., ['Turn', 'Session'] + }) + .merge(BitemporalSchema); + +export type BaseNode = z.infer; + +// ============================================================================= +// FalkorDB Node Wrapper Types +// ============================================================================= + +/** + * Wrapper type for FalkorDB node with typed properties. + * This represents the raw structure returned by FalkorDB queries. + * + * Note: This is a convenience re-export. For direct FalkorDB operations, + * import FalkorNode from @engram/storage instead. + */ +export interface FalkorNodeWrapper = Record> { + id: number; // FalkorDB internal node ID + labels: string[]; + properties: T; +} + +/** + * Wrapper type for FalkorDB edge with typed properties. + */ +export interface FalkorEdgeWrapper = Record> { + id: number; + relationshipType?: string; + relation?: string; + type?: string; + sourceId?: number; + srcNodeId?: number; + destinationId?: number; + destNodeId?: number; + properties: T; +} + +// ============================================================================= +// Re-exports for Backward Compatibility +// ============================================================================= + +// These are re-exported from storage for backward compatibility. +// New code should import FalkorNode/FalkorEdge directly from @engram/storage. +// Re-export domain property types from storage for backward compatibility. +// These are deprecated - use Zod-inferred types from ./nodes.ts instead. +// Re-export composed FalkorNode types with aliases to avoid naming conflicts. +// Prefer using Zod-inferred types from ./nodes.ts for domain logic. +export type { + FalkorEdge, + FalkorNode, + FalkorResult, + FalkorRow, + FileTouchNode as FalkorFileTouchNode, + // Deprecated property types - use Zod schemas in nodes.ts + FileTouchProperties, + ObservationNode as FalkorObservationNode, + ObservationProperties, + QueryParam, + QueryParams, + ReasoningNode as FalkorReasoningNode, + ReasoningProperties, + SessionNode as FalkorSessionNode, + SessionProperties, + ThoughtNode as FalkorThoughtNode, + ThoughtProperties, + ToolCallNode as FalkorToolCallNode, + ToolCallProperties, + TurnNode as FalkorTurnNode, + TurnProperties, +} from "@engram/storage/falkor"; diff --git a/packages/graph/src/models/edges.ts b/packages/graph/src/models/edges.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fc708e35c5c25c40526da0890dd582d3bb28a2a --- /dev/null +++ b/packages/graph/src/models/edges.ts @@ -0,0 +1,146 @@ +import { z } from "zod"; +import { BitemporalSchema } from "./base"; + +// All edges are bitemporal +export const BaseEdgeSchema = BitemporalSchema.extend({ + type: z.string(), // e.g., 'NEXT', 'HAS_TURN' +}); + +// ============================================================================= +// Session → Turn hierarchy +// ============================================================================= + +// Session -[HAS_TURN]-> Turn +export const HasTurnEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("HAS_TURN"), +}); + +// Turn -[NEXT]-> Turn (sequential ordering within session) +export const NextEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("NEXT"), +}); + +// ============================================================================= +// Turn → children hierarchy +// ============================================================================= + +// Turn -[CONTAINS]-> Reasoning (thinking blocks within a turn) +export const ContainsEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("CONTAINS"), +}); + +// Turn -[INVOKES]-> ToolCall +export const InvokesEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("INVOKES"), +}); + +// ToolCall -[TOUCHES]-> FileTouch (captures file operations from tool calls) +// NOTE: Previously Turn -[TOUCHES]-> FileTouch, now routed through ToolCall for lineage +export const TouchesEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("TOUCHES"), +}); + +// ============================================================================= +// Tool relationships +// ============================================================================= + +// ToolCall -[YIELDS]-> Observation +export const YieldsEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("YIELDS"), +}); + +// ============================================================================= +// Code artifact relationships +// ============================================================================= + +// DiffHunk -[MODIFIES]-> CodeArtifact +export const ModifiesEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("MODIFIES"), +}); + +// Snapshot -[SNAPSHOT_OF]-> VFS state +export const SnapshotOfEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("SNAPSHOT_OF"), +}); + +// ============================================================================= +// Versioning & deduplication +// ============================================================================= + +// Node -[REPLACES]-> Node (new version replaces old) +export const ReplacesEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("REPLACES"), +}); + +// Node -[SAME_AS]-> Node (deduplication link) +export const SameAsEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("SAME_AS"), +}); + +// ============================================================================= +// Reasoning → ToolCall causal link +// ============================================================================= + +// Reasoning -[TRIGGERS]-> ToolCall (causal link from reasoning to tool invocation) +// This captures WHY a tool was called - the preceding thinking block that led to it +export const TriggersEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("TRIGGERS"), +}); + +// ============================================================================= +// DEPRECATED: Legacy edges (kept for migration) +// ============================================================================= + +// DEPRECATED: Use CONTAINS/INVOKES instead +export const MotivatedByEdgeSchema = BaseEdgeSchema.extend({ + type: z.literal("MOTIVATED_BY"), +}); + +// ============================================================================= +// Edge type constants for use in queries +// ============================================================================= +export const EdgeTypes = { + // Session hierarchy + HAS_TURN: "HAS_TURN", + NEXT: "NEXT", + + // Turn hierarchy + CONTAINS: "CONTAINS", + INVOKES: "INVOKES", + + // Reasoning → ToolCall → FileTouch lineage + TRIGGERS: "TRIGGERS", // Reasoning -> ToolCall + TOUCHES: "TOUCHES", // ToolCall -> FileTouch + + // Tool relationships + YIELDS: "YIELDS", + + // Code relationships + MODIFIES: "MODIFIES", + SNAPSHOT_OF: "SNAPSHOT_OF", + + // Versioning + REPLACES: "REPLACES", + SAME_AS: "SAME_AS", + + // Deprecated + MOTIVATED_BY: "MOTIVATED_BY", +} as const; + +// Union of all edge types +export const EdgeSchema = z.union([ + HasTurnEdgeSchema, + NextEdgeSchema, + ContainsEdgeSchema, + InvokesEdgeSchema, + TouchesEdgeSchema, + YieldsEdgeSchema, + ModifiesEdgeSchema, + SnapshotOfEdgeSchema, + ReplacesEdgeSchema, + SameAsEdgeSchema, + TriggersEdgeSchema, + MotivatedByEdgeSchema, +]); + +export type Edge = z.infer; diff --git a/packages/graph/src/models/nodes.ts b/packages/graph/src/models/nodes.ts new file mode 100644 index 0000000000000000000000000000000000000000..a75645e23b611e5565ab6d8a63a19eb6d8e89772 --- /dev/null +++ b/packages/graph/src/models/nodes.ts @@ -0,0 +1,303 @@ +import { z } from "zod"; +import { BaseNodeSchema } from "./base"; + +// ============================================================================= +// ToolCallType Enum - Categorizes all tool call types +// ============================================================================= +export const ToolCallType = { + // File operations + FILE_READ: "file_read", + FILE_WRITE: "file_write", + FILE_EDIT: "file_edit", + FILE_MULTI_EDIT: "file_multi_edit", + FILE_GLOB: "file_glob", + FILE_GREP: "file_grep", + FILE_LIST: "file_list", + + // Execution + BASH_EXEC: "bash_exec", + NOTEBOOK_READ: "notebook_read", + NOTEBOOK_EDIT: "notebook_edit", + + // Web + WEB_FETCH: "web_fetch", + WEB_SEARCH: "web_search", + + // Agent + AGENT_SPAWN: "agent_spawn", + TODO_READ: "todo_read", + TODO_WRITE: "todo_write", + + // MCP (Model Context Protocol) + MCP: "mcp", + + // Fallback + UNKNOWN: "unknown", +} as const; + +export type ToolCallTypeValue = (typeof ToolCallType)[keyof typeof ToolCallType]; + +export const ToolCallTypeEnum = z.enum([ + "file_read", + "file_write", + "file_edit", + "file_multi_edit", + "file_glob", + "file_grep", + "file_list", + "bash_exec", + "notebook_read", + "notebook_edit", + "web_fetch", + "web_search", + "agent_spawn", + "todo_read", + "todo_write", + "mcp", + "unknown", +]); + +export const SessionNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("Session")]), + title: z.string().optional(), + user_id: z.string(), + started_at: z.number(), // Epoch + + // Project context for per-repo memory filtering + working_dir: z.string().optional(), // e.g., /home/user/projects/engram + git_remote: z.string().optional(), // e.g., github.com/org/engram + agent_type: z + .enum(["claude-code", "codex", "gemini-cli", "opencode", "aider", "cursor", "unknown"]) + .default("unknown"), + + // Session summary for semantic search + summary: z.string().optional(), // LLM-generated session summary + embedding: z.array(z.number()).optional(), // Vector for retrieval +}); +export type SessionNode = z.infer; + +// ============================================================================= +// DEPRECATED: ThoughtNode - use TurnNode + ReasoningNode instead +// Kept for backward compatibility during migration +// ============================================================================= +export const ThoughtNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("Thought")]), + content_hash: z.string(), // SHA256 of content for dedupe + role: z.enum(["user", "assistant", "system"]), + is_thinking: z.boolean().default(false), // True if block + + // Note: Actual large text content is stored in BlobStore, + // but short thoughts might be stored directly. + // We include a 'summary' or 'preview' here. + preview: z.string().max(1000).optional(), + blob_ref: z.string().optional(), // URI to GCS if content > 1KB +}); +export type ThoughtNode = z.infer; + +// ============================================================================= +// TurnNode: A single conversation turn (user prompt + assistant response) +// This is the atomic unit for agent memory retrieval +// ============================================================================= +export const TurnNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("Turn")]), + + // User prompt + user_content: z.string(), // The user's prompt/message + user_content_hash: z.string(), // SHA256 for deduplication + + // Assistant response + assistant_preview: z.string().max(2000), // First 2000 chars of response + assistant_blob_ref: z.string().optional(), // Full response if > 2KB + + // Semantic retrieval + embedding: z.array(z.number()).optional(), // Vector embedding for similarity search + + // Metadata + sequence_index: z.number().int(), // Order within session (0, 1, 2, ...) + files_touched: z.array(z.string()).default([]), // Denormalized file paths for quick filtering + tool_calls_count: z.number().int().default(0), // Number of tool calls in this turn + + // Token usage (aggregated for the turn) + input_tokens: z.number().int().optional(), + output_tokens: z.number().int().optional(), + cache_read_tokens: z.number().int().optional(), + cache_write_tokens: z.number().int().optional(), + reasoning_tokens: z.number().int().optional(), + + // Cost and timing + cost_usd: z.number().optional(), // Total cost for this turn in USD + duration_ms: z.number().int().optional(), // Total duration in milliseconds + + // Git context (for OpenCode and others that track git state) + git_commit: z.string().optional(), // Git commit hash at end of turn +}); +export type TurnNode = z.infer; + +// ============================================================================= +// ReasoningNode: A thinking/reasoning block within a turn +// Captures the agent's internal reasoning process +// ============================================================================= +export const ReasoningNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("Reasoning")]), + + content_hash: z.string(), // SHA256 for deduplication + preview: z.string().max(1000), // First 1000 chars + blob_ref: z.string().optional(), // Full content if > 1KB + + // Classification of reasoning type + reasoning_type: z + .enum(["chain_of_thought", "reflection", "planning", "analysis", "unknown"]) + .default("unknown"), + + // Position within the turn + sequence_index: z.number().int(), // Order within turn (0, 1, 2, ...) + + // Optional semantic embedding for deep reasoning search + embedding: z.array(z.number()).optional(), +}); +export type ReasoningNode = z.infer; + +// ============================================================================= +// FileTouchNode: A file operation within a turn +// Enables "what happened to this file?" queries +// Now linked through ToolCall for full lineage: Reasoning -> ToolCall -> FileTouch +// ============================================================================= +export const FileTouchNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("FileTouch")]), + + file_path: z.string(), // Indexed path, e.g., "src/auth/login.ts" + action: z.enum(["read", "edit", "create", "delete", "list", "search"]), + + // Link to parent ToolCall for lineage tracing + tool_call_id: z.string().optional(), // UUID of the ToolCall that created this + + // Position tracking within turn + sequence_index: z.number().int().optional(), // Order within turn's tool calls + + // Optional diff summary for edits + diff_preview: z.string().max(500).optional(), // Brief description of changes + lines_added: z.number().int().optional(), + lines_removed: z.number().int().optional(), + + // Search results (for grep/glob operations) + match_count: z.number().int().optional(), + matched_files: z.array(z.string()).optional(), // For glob results +}); +export type FileTouchNode = z.infer; + +// ============================================================================= +// ToolCallNode: Captures every tool invocation +// Creates causal lineage: Reasoning -[TRIGGERS]-> ToolCall -[TOUCHES]-> FileTouch +// ============================================================================= +export const ToolCallNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("ToolCall")]), + + // Identity + call_id: z.string(), // Provider ID (e.g. "toolu_01ABC...") + + // Tool info + tool_name: z.string(), // Original tool name (e.g., "Read", "Bash", "mcp__chrome__click") + tool_type: ToolCallTypeEnum.default("unknown"), // Categorized type + + // Arguments + arguments_json: z.string(), // Full JSON arguments + arguments_preview: z.string().max(500).optional(), // Truncated for display + + // Execution state + status: z.enum(["pending", "success", "error", "cancelled"]), + error_message: z.string().optional(), + + // Sequence tracking + sequence_index: z.number().int(), // Position within Turn's content blocks + reasoning_sequence: z.number().int().optional(), // Index of triggering Reasoning block +}); +export type ToolCallNode = z.infer; + +export const CodeArtifactNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("CodeArtifact")]), + filename: z.string(), + language: z.string(), // ts, py, etc. + content_hash: z.string(), + blob_ref: z.string(), // Content is almost always > 1KB +}); +export type CodeArtifactNode = z.infer; + +export const DiffHunkNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("DiffHunk")]), + file_path: z.string(), + original_line_start: z.number().int(), + original_line_end: z.number().int(), + patch_content: z.string(), // The unified diff or search/replace block +}); +export type DiffHunkNode = z.infer; + +// ============================================================================= +// ObservationNode: Tool execution results +// Links back to ToolCall via tool_call_id +// ============================================================================= +export const ObservationNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("Observation")]), + + // Identity + tool_call_id: z.string(), // Reference to parent ToolCall + + // Result content + content: z.string(), // Full result content + content_preview: z.string().max(1000).optional(), // Truncated for display + content_hash: z.string().optional(), // SHA256 for deduplication + + // Status + is_error: z.boolean().default(false), + error_type: z.string().optional(), // e.g., "FileNotFound", "PermissionDenied" + + // Metadata + execution_time_ms: z.number().int().optional(), +}); +export type ObservationNode = z.infer; + +export const SnapshotNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("Snapshot")]), + vfs_state_blob_ref: z.string().url(), + state_hash: z.string(), + snapshot_at: z.number(), // Epoch +}); +export type SnapshotNode = z.infer; + +// ============================================================================= +// MemoryNode: Explicit user-defined memories for long-term storage +// Created via engram_remember tool or auto-extracted from sessions +// ============================================================================= +export const MemoryTypeEnum = z.enum([ + "decision", // Architectural or design decisions + "context", // Background context about the project + "insight", // Learned patterns or observations + "preference", // User preferences (coding style, tools, etc.) + "fact", // Factual information to remember + "turn", // Auto-generated from conversation turns +]); +export type MemoryType = z.infer; + +export const MemoryNodeSchema = BaseNodeSchema.extend({ + labels: z.tuple([z.literal("Memory")]), + + // Content + content: z.string(), // The memory content + content_hash: z.string(), // SHA256 for deduplication + + // Classification + type: MemoryTypeEnum.default("context"), + tags: z.array(z.string()).default([]), // User-defined tags + + // Source tracking + source_session_id: z.string().optional(), // Session where memory was created + source_turn_id: z.string().optional(), // Turn where memory was created + source: z.enum(["user", "auto", "import"]).default("user"), // How it was created + + // Project context (for scoping) + project: z.string().optional(), // Project/repo identifier + working_dir: z.string().optional(), // Working directory when created + + // Semantic retrieval + embedding: z.array(z.number()).optional(), // Vector for similarity search +}); +export type MemoryNode = z.infer; diff --git a/packages/graph/src/pruner.test.ts b/packages/graph/src/pruner.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..08139babe53bf2a09e6a7ce57e00a3e5000967cf --- /dev/null +++ b/packages/graph/src/pruner.test.ts @@ -0,0 +1,129 @@ +import { beforeEach, describe, expect, it, type MockedFunction, vi } from "vitest"; +import { GraphPruner } from "./pruner"; + +describe("GraphPruner", () => { + let mockFalkorQuery: MockedFunction; + let mockFalkorClient: { query: Mock }; + + beforeEach(() => { + mockFalkorQuery = vi.fn(async () => []); + mockFalkorClient = { query: mockFalkorQuery }; + }); + + it("should prune history in batches without archive", async () => { + // First call: fetch node IDs returns 2 nodes + // Second call: delete returns 2 + // Third call: fetch returns empty (no more) + mockFalkorQuery + .mockResolvedValueOnce([{ nodeId: 1 }, { nodeId: 2 }]) + .mockResolvedValueOnce([[2]]) + .mockResolvedValueOnce([]); + + const pruner = new GraphPruner(mockFalkorClient as any); + + const result = await pruner.pruneHistory({ retentionMs: 1000 }); + + expect(result.deleted).toBe(2); + expect(result.archived).toBe(0); + expect(result.batches).toBe(1); + expect(result.archiveUri).toBeUndefined(); + }); + + it("should process multiple batches", async () => { + // First batch: 2 nodes (full batch size) + // Second batch: 1 node (partial, signals end) + mockFalkorQuery + .mockResolvedValueOnce([{ nodeId: 1 }, { nodeId: 2 }]) // fetch batch 1 + .mockResolvedValueOnce([[2]]) // delete batch 1 + .mockResolvedValueOnce([{ nodeId: 3 }]) // fetch batch 2 (partial) + .mockResolvedValueOnce([[1]]); // delete batch 2 + + const pruner = new GraphPruner(mockFalkorClient as any); + + const result = await pruner.pruneHistory({ retentionMs: 1000, batchSize: 2 }); + + expect(result.deleted).toBe(3); + expect(result.batches).toBe(2); + }); + + it("should respect maxBatches limit", async () => { + // Setup infinite supply of nodes + mockFalkorQuery + .mockResolvedValueOnce([{ nodeId: 1 }, { nodeId: 2 }]) + .mockResolvedValueOnce([[2]]) + .mockResolvedValueOnce([{ nodeId: 3 }, { nodeId: 4 }]) + .mockResolvedValueOnce([[2]]); + + const pruner = new GraphPruner(mockFalkorClient as any); + + const result = await pruner.pruneHistory({ + retentionMs: 1000, + batchSize: 2, + maxBatches: 1, + }); + + expect(result.batches).toBe(1); + expect(result.deleted).toBe(2); + }); + + it("should archive nodes before pruning when archiveStore is provided", async () => { + const mockBlobStore = { + save: vi.fn(async () => "file:///data/blobs/abc123"), + read: vi.fn(async () => ""), + }; + + // Archive query returns nodes, then fetch/delete batches + mockFalkorQuery + .mockResolvedValueOnce([ + { labels: ["Thought"], props: { id: "t1", content: "old thought" }, nodeId: 1 }, + { labels: ["Thought"], props: { id: "t2", content: "another old thought" }, nodeId: 2 }, + ]) + .mockResolvedValueOnce([{ nodeId: 1 }, { nodeId: 2 }]) // fetch batch + .mockResolvedValueOnce([[2]]) // delete batch + .mockResolvedValueOnce([]); // no more + + const pruner = new GraphPruner(mockFalkorClient as any, mockBlobStore as any); + + const result = await pruner.pruneHistory({ retentionMs: 1000 }); + + expect(result.archived).toBe(2); + expect(result.deleted).toBe(2); + expect(result.batches).toBe(1); + expect(result.archiveUri).toBe("file:///data/blobs/abc123"); + + // Verify blob store was called with JSONL content + expect(mockBlobStore.save).toHaveBeenCalledTimes(1); + const savedContent = mockBlobStore.save.mock.calls[0][0] as string; + const lines = savedContent.split("\n"); + expect(lines.length).toBe(2); + + // Verify JSONL format + const firstRecord = JSON.parse(lines[0]); + expect(firstRecord.labels).toEqual(["Thought"]); + expect(firstRecord.id).toBe("t1"); + expect(firstRecord._node_id).toBe(1); + expect(firstRecord._archived_at).toBeDefined(); + }); + + it("should skip archive when no nodes to prune", async () => { + const mockBlobStore = { + save: vi.fn(async () => "file:///data/blobs/abc123"), + read: vi.fn(async () => ""), + }; + + // Archive query returns empty, fetch returns empty + mockFalkorQuery.mockResolvedValueOnce([]).mockResolvedValueOnce([]); + + const pruner = new GraphPruner(mockFalkorClient as any, mockBlobStore as any); + + const result = await pruner.pruneHistory({ retentionMs: 1000 }); + + expect(result.archived).toBe(0); + expect(result.deleted).toBe(0); + expect(result.batches).toBe(0); + expect(result.archiveUri).toBeUndefined(); + + // Blob store should not be called if no nodes to archive + expect(mockBlobStore.save).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/graph/src/pruner.ts b/packages/graph/src/pruner.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0dae3c71c8500123efe3cd36cde69cf37beaa1e --- /dev/null +++ b/packages/graph/src/pruner.ts @@ -0,0 +1,164 @@ +import type { BlobStore, FalkorClient, GraphClient } from "@engram/storage"; +import { now } from "./utils/time"; + +interface PruneResult { + archived: number; + deleted: number; + archiveUri?: string; + batches: number; +} + +interface PruneOptions { + /** Milliseconds to keep history (default: 30 days) */ + retentionMs?: number; + /** Number of nodes to delete per batch (default: 1000) */ + batchSize?: number; + /** Maximum batches to process (default: no limit) */ + maxBatches?: number; +} + +const DEFAULT_BATCH_SIZE = 1000; +const DEFAULT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; // 30 days + +export class GraphPruner { + private client: GraphClient; + private archiveStore?: BlobStore; + + constructor(client: GraphClient, archiveStore?: BlobStore); + /** @deprecated Use GraphClient interface instead */ + constructor(client: FalkorClient, archiveStore?: BlobStore); + constructor(client: GraphClient | FalkorClient, archiveStore?: BlobStore) { + this.client = client as GraphClient; + this.archiveStore = archiveStore; + } + + /** + * Prune old transaction history. + * Optionally archives nodes to blob storage before deletion. + * Removes nodes where transaction time ended before the threshold. + * Uses batched deletion to avoid Redis timeouts on large graphs. + * + * @param options - Pruning options + * @returns PruneResult with counts, archive URI, and batch info + */ + async pruneHistory(options: PruneOptions = {}): Promise { + const { + retentionMs = DEFAULT_RETENTION_MS, + batchSize = DEFAULT_BATCH_SIZE, + maxBatches, + } = options; + + const threshold = now() - retentionMs; + + // 1. Archive nodes before deletion (if archive store is configured) + let archiveUri: string | undefined; + let archivedCount = 0; + + if (this.archiveStore) { + const archiveResult = await this.archiveNodes(threshold); + archivedCount = archiveResult.count; + archiveUri = archiveResult.uri; + } + + // 2. Delete old nodes in batches to avoid Redis timeouts + let totalDeleted = 0; + let batchesProcessed = 0; + let hasMore = true; + + while (hasMore) { + // Check if we've hit max batches limit + if (maxBatches !== undefined && batchesProcessed >= maxBatches) { + break; + } + + // Fetch a batch of node IDs to delete + const fetchQuery = ` + MATCH (n) + WHERE n.tt_end < ${threshold} + RETURN id(n) as nodeId + LIMIT ${batchSize} + `; + + const nodeRows = await this.client.query<{ nodeId: number }>(fetchQuery); + + if (!nodeRows || nodeRows.length === 0) { + hasMore = false; + break; + } + + // Delete this batch by node IDs + const nodeIds = nodeRows.map((row) => row.nodeId); + const deleteQuery = ` + MATCH (n) + WHERE id(n) IN [${nodeIds.join(",")}] + DELETE n + RETURN count(n) as deleted_count + `; + + const result = await this.client.query(deleteQuery); + const firstRow = result?.[0]; + const batchDeleted = (firstRow?.deleted_count as number) ?? (firstRow?.[0] as number) ?? 0; + + totalDeleted += batchDeleted; + batchesProcessed++; + + // If we got fewer than batch size, we're done + if (nodeRows.length < batchSize) { + hasMore = false; + } + } + + return { + archived: archivedCount, + deleted: totalDeleted, + archiveUri, + batches: batchesProcessed, + }; + } + + /** + * Archive nodes to JSONL format before deletion. + * Exports all nodes that will be pruned to blob storage. + */ + private async archiveNodes(threshold: number): Promise<{ count: number; uri?: string }> { + // Query all nodes that will be deleted + const fetchQuery = ` + MATCH (n) + WHERE n.tt_end < ${threshold} + RETURN labels(n) as labels, properties(n) as props, id(n) as nodeId + `; + + const rows = await this.client.query<{ + labels: string[]; + props: Record; + nodeId: number; + }>(fetchQuery); + + if (!rows || rows.length === 0) { + return { count: 0 }; + } + + // Convert to JSONL format + const lines: string[] = []; + for (const row of rows) { + const archiveRecord = { + _archived_at: now(), + _threshold: threshold, + _node_id: row.nodeId, + labels: row.labels, + ...row.props, + }; + lines.push(JSON.stringify(archiveRecord)); + } + + const jsonlContent = lines.join("\n"); + + // Save to blob storage + const uri = await this.archiveStore?.save(jsonlContent); + + return { + count: rows.length, + uri, + }; + } +} diff --git a/packages/graph/src/queries/builder.test.ts b/packages/graph/src/queries/builder.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b4a6877c53f13f49f514ed50673e0f7eaf73de8 --- /dev/null +++ b/packages/graph/src/queries/builder.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { MAX_DATE } from "../utils/time"; +import { QueryBuilder } from "./builder"; + +describe("QueryBuilder", () => { + it("should build simple match query", () => { + const qb = new QueryBuilder(); + const { cypher, params } = qb.match("(n)").return("n").build(); + + expect(cypher).toBe("MATCH (n) RETURN n"); + expect(params).toEqual({}); + }); + + it("should build query with where clause", () => { + const qb = new QueryBuilder(); + const { cypher } = qb.match("(n)").where("n.id = 1").return("n").build(); + + expect(cypher).toBe("MATCH (n) WHERE n.id = 1 RETURN n"); + }); + + it("should add bitemporal constraints (current)", () => { + const qb = new QueryBuilder(); + const { cypher, params } = qb.match("(n)").at(["n"], { tt: "current" }).return("n").build(); + + expect(cypher).toContain(`MATCH (n) WHERE n.tt_end = ${MAX_DATE} RETURN n`); + }); + + it("should add bitemporal constraints (valid time and transaction time)", () => { + const qb = new QueryBuilder(); + const { cypher, params } = qb + .match("(n)") + .at(["n"], { vt: 1000, tt: 2000 }) + .return("n") + .build(); + + expect(cypher).toContain("(n.vt_start <= $vt AND n.vt_end > $vt)"); + expect(cypher).toContain("(n.tt_start <= $tt AND n.tt_end > $tt)"); + expect(params).toEqual({ vt: 1000, tt: 2000 }); + }); +}); diff --git a/packages/graph/src/queries/builder.ts b/packages/graph/src/queries/builder.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7595eb9b20f73709b39a32767fe9525bc13e15b --- /dev/null +++ b/packages/graph/src/queries/builder.ts @@ -0,0 +1,58 @@ +export class QueryBuilder { + private matchParts: string[] = []; + private whereParts: string[] = []; + private returnParts: string[] = []; + private params: Record = {}; + + match(clause: string): this { + this.matchParts.push(clause); + return this; + } + + where(clause: string): this { + this.whereParts.push(clause); + return this; + } + + return(clause: string): this { + this.returnParts.push(clause); + return this; + } + + // Inject bitemporal constraints + // Simplification: aliases list required to know what to constrain + at(aliases: string[], time: { vt?: number; tt?: number | "current" }): this { + const { vt, tt } = time; + + aliases.forEach((alias) => { + // Valid Time Constraint + if (vt !== undefined) { + this.whereParts.push(`(${alias}.vt_start <= $vt AND ${alias}.vt_end > $vt)`); + this.params.vt = vt; + } + + // Transaction Time Constraint + if (tt === "current") { + // Current knowledge + this.whereParts.push(`${alias}.tt_end = 253402300799000`); // MAX_DATE + } else if (typeof tt === "number") { + // Known at time T + this.whereParts.push(`(${alias}.tt_start <= $tt AND ${alias}.tt_end > $tt)`); + this.params.tt = tt; + } + }); + + return this; + } + + build(): { cypher: string; params: Record } { + let cypher = `MATCH ${this.matchParts.join(", ")}`; + if (this.whereParts.length > 0) { + cypher += ` WHERE ${this.whereParts.join(" AND ")}`; + } + if (this.returnParts.length > 0) { + cypher += ` RETURN ${this.returnParts.join(", ")}`; + } + return { cypher, params: this.params }; + } +} diff --git a/packages/graph/src/repositories/falkor-base.ts b/packages/graph/src/repositories/falkor-base.ts new file mode 100644 index 0000000000000000000000000000000000000000..1199dd7b7dc65762ed0f9ea9e17e346038c12b3c --- /dev/null +++ b/packages/graph/src/repositories/falkor-base.ts @@ -0,0 +1,123 @@ +import type { GraphClient } from "@engram/storage"; +import { ulid } from "ulid"; +import { createBitemporal, MAX_DATE, now } from "../utils/time"; + +/** + * Base class for FalkorDB repository implementations. + * Provides common utilities for: + * - ID generation + * - Bitemporal property management + * - Query parameter building + * - Node property mapping + */ +export abstract class FalkorBaseRepository { + constructor(protected readonly graphClient: GraphClient) {} + + /** + * Generate a new ULID for entity IDs. + */ + protected generateId(): string { + return ulid(); + } + + /** + * Create bitemporal properties for a new node. + * @param validFrom - Optional valid time start (defaults to now) + */ + protected createBitemporal(validFrom?: number) { + return createBitemporal(validFrom ?? now()); + } + + /** + * Build a Cypher property string from an object. + * Example: { id: 'abc', name: 'test' } => "id: $id, name: $name" + */ + protected buildPropertyString(obj: Record): string { + return Object.keys(obj) + .map((k) => `${k}: $${k}`) + .join(", "); + } + + /** + * Build a Cypher SET clause for updates. + * Example: { name: 'new', age: 30 } => "n.name = $name, n.age = $age" + */ + protected buildSetClause(updates: Record, alias: string = "n"): string { + return Object.keys(updates) + .map((k) => `${alias}.${k} = $${k}`) + .join(", "); + } + + /** + * Convert snake_case properties to camelCase for domain objects. + */ + protected snakeToCamel>(obj: T): Record { + const result: Record = {}; + for (const [key, value] of Object.entries(obj)) { + const camelKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); + result[camelKey] = value; + } + return result; + } + + /** + * Convert camelCase properties to snake_case for FalkorDB. + */ + protected camelToSnake>(obj: T): Record { + const result: Record = {}; + for (const [key, value] of Object.entries(obj)) { + if (value !== undefined) { + const snakeKey = key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`); + result[snakeKey] = value; + } + } + return result; + } + + /** + * Execute a typed Cypher query. + */ + protected async query(cypher: string, params: Record = {}): Promise { + return this.graphClient.query(cypher, params); + } + + /** + * Check if a node exists with the given condition. + */ + protected async exists( + label: string, + condition: string, + params: Record, + ): Promise { + const result = await this.query<{ cnt: number }>( + `MATCH (n:${label} {${condition}}) WHERE n.tt_end = ${MAX_DATE} RETURN count(n) as cnt`, + params, + ); + return (result[0]?.cnt ?? 0) > 0; + } + + /** + * Soft delete a node by closing its transaction time. + */ + protected async softDelete(label: string, id: string): Promise { + const t = now(); + await this.query( + `MATCH (n:${label} {id: $id}) WHERE n.tt_end = ${MAX_DATE} SET n.tt_end = $t`, + { id, t }, + ); + } + + /** + * Get the MAX_DATE constant for queries. + */ + protected get maxDate(): number { + return MAX_DATE; + } + + /** + * Get the current timestamp. + */ + protected get now(): number { + return now(); + } +} diff --git a/packages/graph/src/repositories/falkor-reasoning.repository.ts b/packages/graph/src/repositories/falkor-reasoning.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..239849d8bfa8e0be7fbfb27fb9ba1e2c1c292c99 --- /dev/null +++ b/packages/graph/src/repositories/falkor-reasoning.repository.ts @@ -0,0 +1,178 @@ +import type { FalkorNode } from "@engram/storage"; +import { EdgeTypes } from "../models/edges"; +import { FalkorBaseRepository } from "./falkor-base"; +import type { ReasoningRepository } from "./reasoning.repository"; +import type { CreateReasoningInput, Reasoning } from "./types"; + +/** + * Raw FalkorDB Reasoning node properties. + */ +type ReasoningNodeProps = { + id: string; + content_hash: string; + preview: string; + blob_ref?: string; + reasoning_type: string; + sequence_index: number; + embedding?: number[]; + vt_start: number; + vt_end: number; + tt_start: number; + tt_end: number; + [key: string]: unknown; +}; + +/** + * FalkorDB implementation of ReasoningRepository. + */ +export class FalkorReasoningRepository extends FalkorBaseRepository implements ReasoningRepository { + async findById(id: string): Promise { + const results = await this.query<{ r: FalkorNode; turnId: string }>( + `MATCH (t:Turn)-[:${EdgeTypes.CONTAINS}]->(r:Reasoning {id: $id}) + WHERE r.tt_end = ${this.maxDate} + RETURN r, t.id as turnId`, + { id }, + ); + if (!results[0]?.r) return null; + return this.mapToReasoning(results[0].r, results[0].turnId); + } + + async findByTurn(turnId: string): Promise { + const results = await this.query<{ r: FalkorNode }>( + `MATCH (t:Turn {id: $turnId})-[:${EdgeTypes.CONTAINS}]->(r:Reasoning) + WHERE r.tt_end = ${this.maxDate} + RETURN r + ORDER BY r.sequence_index ASC`, + { turnId }, + ); + return results.map((row) => this.mapToReasoning(row.r, turnId)); + } + + async findBySession(sessionId: string): Promise { + const results = await this.query<{ + r: FalkorNode; + turnId: string; + turnSeq: number; + }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn)-[:${EdgeTypes.CONTAINS}]->(r:Reasoning) + WHERE t.tt_end = ${this.maxDate} AND r.tt_end = ${this.maxDate} + RETURN r, t.id as turnId, t.sequence_index as turnSeq + ORDER BY turnSeq ASC, r.sequence_index ASC`, + { sessionId }, + ); + return results.map((row) => this.mapToReasoning(row.r, row.turnId)); + } + + async findByType(sessionId: string, reasoningType: string): Promise { + const results = await this.query<{ + r: FalkorNode; + turnId: string; + turnSeq: number; + }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn)-[:${EdgeTypes.CONTAINS}]->(r:Reasoning {reasoning_type: $reasoningType}) + WHERE t.tt_end = ${this.maxDate} AND r.tt_end = ${this.maxDate} + RETURN r, t.id as turnId, t.sequence_index as turnSeq + ORDER BY turnSeq ASC, r.sequence_index ASC`, + { sessionId, reasoningType }, + ); + return results.map((row) => this.mapToReasoning(row.r, row.turnId)); + } + + async create(input: CreateReasoningInput): Promise { + const id = this.generateId(); + const temporal = this.createBitemporal(); + + const nodeProps: Record = { + id, + content_hash: input.contentHash, + preview: input.preview, + reasoning_type: input.reasoningType ?? "unknown", + sequence_index: input.sequenceIndex, + vt_start: temporal.vt_start, + vt_end: temporal.vt_end, + tt_start: temporal.tt_start, + tt_end: temporal.tt_end, + }; + + if (input.blobRef) nodeProps.blob_ref = input.blobRef; + if (input.embedding) nodeProps.embedding = input.embedding; + + const propsString = this.buildPropertyString(nodeProps); + + // Create node and link to turn + await this.query( + `MATCH (t:Turn {id: $turnId}) + WHERE t.tt_end = ${this.maxDate} + CREATE (r:Reasoning {${propsString}}) + CREATE (t)-[:${EdgeTypes.CONTAINS} {vt_start: $vt_start, vt_end: $vt_end, tt_start: $tt_start, tt_end: $tt_end}]->(r)`, + { turnId: input.turnId, ...nodeProps }, + ); + + return { + id, + turnId: input.turnId, + contentHash: input.contentHash, + preview: input.preview, + blobRef: input.blobRef, + reasoningType: input.reasoningType ?? "unknown", + sequenceIndex: input.sequenceIndex, + embedding: input.embedding, + vtStart: temporal.vt_start, + vtEnd: temporal.vt_end, + ttStart: temporal.tt_start, + ttEnd: temporal.tt_end, + }; + } + + async createBatch(inputs: CreateReasoningInput[]): Promise { + const results: Reasoning[] = []; + + // Group inputs by turnId for more efficient batching + const byTurn = new Map(); + for (const input of inputs) { + const existing = byTurn.get(input.turnId) ?? []; + existing.push(input); + byTurn.set(input.turnId, existing); + } + + for (const [turnId, turnInputs] of byTurn) { + for (const input of turnInputs) { + const reasoning = await this.create({ ...input, turnId }); + results.push(reasoning); + } + } + + return results; + } + + async count(turnId: string): Promise { + const results = await this.query<{ cnt: number }>( + `MATCH (t:Turn {id: $turnId})-[:${EdgeTypes.CONTAINS}]->(r:Reasoning) + WHERE r.tt_end = ${this.maxDate} + RETURN count(r) as cnt`, + { turnId }, + ); + return results[0]?.cnt ?? 0; + } + + /** + * Map FalkorDB node to domain Reasoning object. + */ + private mapToReasoning(node: FalkorNode, turnId: string): Reasoning { + const props = node.properties; + return { + id: props.id, + turnId, + contentHash: props.content_hash, + preview: props.preview, + blobRef: props.blob_ref, + reasoningType: props.reasoning_type, + sequenceIndex: props.sequence_index, + embedding: props.embedding, + vtStart: props.vt_start, + vtEnd: props.vt_end, + ttStart: props.tt_start, + ttEnd: props.tt_end, + }; + } +} diff --git a/packages/graph/src/repositories/falkor-session.repository.ts b/packages/graph/src/repositories/falkor-session.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..bdc054edb6fc568bd9faceda7d2b3385e139aa6d --- /dev/null +++ b/packages/graph/src/repositories/falkor-session.repository.ts @@ -0,0 +1,240 @@ +import type { FalkorNode } from "@engram/storage"; +import { FalkorBaseRepository } from "./falkor-base"; +import type { SessionRepository } from "./session.repository"; +import type { CreateSessionInput, Session, UpdateSessionInput } from "./types"; + +/** + * Raw FalkorDB Session node properties. + */ +type SessionNodeProps = { + id: string; + external_id?: string; + title?: string; + user_id: string; + provider?: string; + started_at: number; + working_dir?: string; + git_remote?: string; + agent_type: string; + summary?: string; + embedding?: number[]; + metadata?: string; // JSON string + vt_start: number; + vt_end: number; + tt_start: number; + tt_end: number; + [key: string]: unknown; +}; + +/** + * FalkorDB implementation of SessionRepository. + */ +export class FalkorSessionRepository extends FalkorBaseRepository implements SessionRepository { + async findById(id: string): Promise { + const results = await this.query<{ s: FalkorNode }>( + `MATCH (s:Session {id: $id}) WHERE s.tt_end = ${this.maxDate} RETURN s`, + { id }, + ); + if (!results[0]?.s) return null; + return this.mapToSession(results[0].s); + } + + async findByExternalId(externalId: string): Promise { + const results = await this.query<{ s: FalkorNode }>( + `MATCH (s:Session {external_id: $externalId}) WHERE s.tt_end = ${this.maxDate} RETURN s`, + { externalId }, + ); + if (!results[0]?.s) return null; + return this.mapToSession(results[0].s); + } + + async findActive(): Promise { + const results = await this.query<{ s: FalkorNode }>( + `MATCH (s:Session) WHERE s.tt_end = ${this.maxDate} RETURN s ORDER BY s.started_at DESC`, + ); + return results.map((r) => this.mapToSession(r.s)); + } + + async findByProvider(provider: string): Promise { + const results = await this.query<{ s: FalkorNode }>( + `MATCH (s:Session {agent_type: $provider}) WHERE s.tt_end = ${this.maxDate} RETURN s ORDER BY s.started_at DESC`, + { provider }, + ); + return results.map((r) => this.mapToSession(r.s)); + } + + async findByUser(userId: string): Promise { + const results = await this.query<{ s: FalkorNode }>( + `MATCH (s:Session {user_id: $userId}) WHERE s.tt_end = ${this.maxDate} RETURN s ORDER BY s.started_at DESC`, + { userId }, + ); + return results.map((r) => this.mapToSession(r.s)); + } + + async findByWorkingDir(workingDir: string): Promise { + const results = await this.query<{ s: FalkorNode }>( + `MATCH (s:Session {working_dir: $workingDir}) WHERE s.tt_end = ${this.maxDate} RETURN s ORDER BY s.started_at DESC`, + { workingDir }, + ); + return results.map((r) => this.mapToSession(r.s)); + } + + async create(input: CreateSessionInput): Promise { + const id = this.generateId(); + const temporal = this.createBitemporal(); + const startedAt = this.now; + + const nodeProps: Record = { + id, + user_id: input.userId, + started_at: startedAt, + agent_type: input.agentType ?? "unknown", + vt_start: temporal.vt_start, + vt_end: temporal.vt_end, + tt_start: temporal.tt_start, + tt_end: temporal.tt_end, + }; + + if (input.externalId) nodeProps.external_id = input.externalId; + if (input.title) nodeProps.title = input.title; + if (input.provider) nodeProps.provider = input.provider; + if (input.workingDir) nodeProps.working_dir = input.workingDir; + if (input.gitRemote) nodeProps.git_remote = input.gitRemote; + if (input.metadata) nodeProps.metadata = JSON.stringify(input.metadata); + + const propsString = this.buildPropertyString(nodeProps); + const results = await this.query<{ s: FalkorNode }>( + `CREATE (s:Session {${propsString}}) RETURN s`, + nodeProps, + ); + + return this.mapToSession(results[0].s); + } + + async update(id: string, updates: UpdateSessionInput): Promise { + const existing = await this.findById(id); + if (!existing) { + throw new Error(`Session not found: ${id}`); + } + + // Close old version with optimistic locking + // Only close if tt_end is still maxDate (concurrent update detection) + const t = this.now; + const closeResult = await this.query<{ count: number }>( + `MATCH (s:Session {id: $id}) WHERE s.tt_end = ${this.maxDate} + SET s.tt_end = $t + RETURN count(s) as count`, + { id, t }, + ); + + // Check if the close operation affected exactly one node + // If zero rows affected, another transaction closed it first + if (!closeResult[0] || closeResult[0].count === 0) { + throw new Error(`Concurrent modification detected for session ${id}. Please retry.`); + } + + // Prepare update properties + const updateProps: Record = {}; + if (updates.title !== undefined) updateProps.title = updates.title; + if (updates.summary !== undefined) updateProps.summary = updates.summary; + if (updates.embedding !== undefined) updateProps.embedding = updates.embedding; + if (updates.metadata !== undefined) updateProps.metadata = JSON.stringify(updates.metadata); + + // Create new version with merged properties + const newTemporal = this.createBitemporal(); + const newId = this.generateId(); + + const nodeProps: Record = { + id: newId, + external_id: existing.externalId, + user_id: existing.userId, + started_at: existing.startedAt.getTime(), + agent_type: existing.agentType, + working_dir: existing.workingDir, + git_remote: existing.gitRemote, + provider: existing.provider, + title: updates.title ?? existing.title, + summary: updates.summary ?? existing.summary, + embedding: updates.embedding ?? existing.embedding, + metadata: updates.metadata + ? JSON.stringify(updates.metadata) + : existing.metadata + ? JSON.stringify(existing.metadata) + : undefined, + vt_start: newTemporal.vt_start, + vt_end: newTemporal.vt_end, + tt_start: newTemporal.tt_start, + tt_end: newTemporal.tt_end, + }; + + // Remove undefined values + for (const key of Object.keys(nodeProps)) { + if (nodeProps[key] === undefined) { + delete nodeProps[key]; + } + } + + const propsString = this.buildPropertyString(nodeProps); + const results = await this.query<{ s: FalkorNode }>( + `CREATE (s:Session {${propsString}}) RETURN s`, + nodeProps, + ); + + // Link new version to old + await this.query( + `MATCH (new:Session {id: $newId}), (old:Session {id: $oldId}) + CREATE (new)-[:REPLACES {tt_start: $ttStart, tt_end: ${this.maxDate}, vt_start: $vtStart, vt_end: ${this.maxDate}}]->(old)`, + { newId, oldId: id, ttStart: newTemporal.tt_start, vtStart: newTemporal.vt_start }, + ); + + return this.mapToSession(results[0].s); + } + + async delete(id: string): Promise { + const exists = await this.findById(id); + if (!exists) { + throw new Error(`Session not found: ${id}`); + } + await this.softDelete("Session", id); + } + + /** + * Safely parse JSON with fallback. + * Logs a warning if parsing fails. + */ + private safeParseJson(jsonString: string | undefined, fallback: T, context: string): T { + if (!jsonString) return fallback; + try { + return JSON.parse(jsonString) as T; + } catch { + // Log warning but don't fail - return fallback value + console.warn(`[FalkorSessionRepository] Failed to parse ${context} JSON, using fallback`); + return fallback; + } + } + + /** + * Map FalkorDB node to domain Session object. + */ + private mapToSession(node: FalkorNode): Session { + const props = node.properties; + return { + id: props.id, + externalId: props.external_id, + title: props.title, + userId: props.user_id, + provider: props.provider, + startedAt: new Date(props.started_at), + workingDir: props.working_dir, + gitRemote: props.git_remote, + agentType: props.agent_type, + summary: props.summary, + embedding: props.embedding, + metadata: this.safeParseJson(props.metadata, undefined, "metadata"), + vtStart: props.vt_start, + vtEnd: props.vt_end, + ttStart: props.tt_start, + ttEnd: props.tt_end, + }; + } +} diff --git a/packages/graph/src/repositories/falkor-tool-call.repository.ts b/packages/graph/src/repositories/falkor-tool-call.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..05bd9090ba7153ab8505d2250c12007ad522a213 --- /dev/null +++ b/packages/graph/src/repositories/falkor-tool-call.repository.ts @@ -0,0 +1,287 @@ +import type { FalkorNode } from "@engram/storage"; +import { EdgeTypes } from "../models/edges"; +import { FalkorBaseRepository } from "./falkor-base"; +import type { ToolCallRepository } from "./tool-call.repository"; +import type { CreateToolCallInput, ToolCall, ToolResult } from "./types"; + +/** + * Raw FalkorDB ToolCall node properties. + */ +type ToolCallNodeProps = { + id: string; + call_id: string; + tool_name: string; + tool_type: string; + arguments_json: string; + arguments_preview?: string; + status: string; + error_message?: string; + sequence_index: number; + reasoning_sequence?: number; + vt_start: number; + vt_end: number; + tt_start: number; + tt_end: number; + [key: string]: unknown; +}; + +/** + * FalkorDB implementation of ToolCallRepository. + */ +export class FalkorToolCallRepository extends FalkorBaseRepository implements ToolCallRepository { + async findById(id: string): Promise { + const results = await this.query<{ tc: FalkorNode; turnId: string }>( + `MATCH (t:Turn)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall {id: $id}) + WHERE tc.tt_end = ${this.maxDate} + RETURN tc, t.id as turnId`, + { id }, + ); + if (!results[0]?.tc) return null; + return this.mapToToolCall(results[0].tc, results[0].turnId); + } + + async findByCallId(callId: string): Promise { + const results = await this.query<{ tc: FalkorNode; turnId: string }>( + `MATCH (t:Turn)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall {call_id: $callId}) + WHERE tc.tt_end = ${this.maxDate} + RETURN tc, t.id as turnId`, + { callId }, + ); + if (!results[0]?.tc) return null; + return this.mapToToolCall(results[0].tc, results[0].turnId); + } + + async findByTurn(turnId: string): Promise { + const results = await this.query<{ tc: FalkorNode }>( + `MATCH (t:Turn {id: $turnId})-[:${EdgeTypes.INVOKES}]->(tc:ToolCall) + WHERE tc.tt_end = ${this.maxDate} + RETURN tc + ORDER BY tc.sequence_index ASC`, + { turnId }, + ); + return results.map((row) => this.mapToToolCall(row.tc, turnId)); + } + + async findBySession(sessionId: string): Promise { + const results = await this.query<{ + tc: FalkorNode; + turnId: string; + turnSeq: number; + }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall) + WHERE t.tt_end = ${this.maxDate} AND tc.tt_end = ${this.maxDate} + RETURN tc, t.id as turnId, t.sequence_index as turnSeq + ORDER BY turnSeq ASC, tc.sequence_index ASC`, + { sessionId }, + ); + return results.map((row) => this.mapToToolCall(row.tc, row.turnId)); + } + + async findByToolType(sessionId: string, toolType: string): Promise { + const results = await this.query<{ + tc: FalkorNode; + turnId: string; + turnSeq: number; + }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall {tool_type: $toolType}) + WHERE t.tt_end = ${this.maxDate} AND tc.tt_end = ${this.maxDate} + RETURN tc, t.id as turnId, t.sequence_index as turnSeq + ORDER BY turnSeq ASC, tc.sequence_index ASC`, + { sessionId, toolType }, + ); + return results.map((row) => this.mapToToolCall(row.tc, row.turnId)); + } + + async findByStatus(sessionId: string, status: string): Promise { + const results = await this.query<{ + tc: FalkorNode; + turnId: string; + turnSeq: number; + }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall {status: $status}) + WHERE t.tt_end = ${this.maxDate} AND tc.tt_end = ${this.maxDate} + RETURN tc, t.id as turnId, t.sequence_index as turnSeq + ORDER BY turnSeq ASC, tc.sequence_index ASC`, + { sessionId, status }, + ); + return results.map((row) => this.mapToToolCall(row.tc, row.turnId)); + } + + async findPending(sessionId?: string): Promise { + if (sessionId) { + return this.findByStatus(sessionId, "pending"); + } + + const results = await this.query<{ tc: FalkorNode; turnId: string }>( + `MATCH (t:Turn)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall {status: 'pending'}) + WHERE tc.tt_end = ${this.maxDate} + RETURN tc, t.id as turnId + ORDER BY tc.vt_start ASC`, + ); + return results.map((row) => this.mapToToolCall(row.tc, row.turnId)); + } + + async create(input: CreateToolCallInput): Promise { + const id = this.generateId(); + const temporal = this.createBitemporal(); + + const nodeProps: Record = { + id, + call_id: input.callId, + tool_name: input.toolName, + tool_type: input.toolType ?? "unknown", + arguments_json: input.argumentsJson, + status: input.status ?? "pending", + sequence_index: input.sequenceIndex, + vt_start: temporal.vt_start, + vt_end: temporal.vt_end, + tt_start: temporal.tt_start, + tt_end: temporal.tt_end, + }; + + if (input.argumentsPreview) nodeProps.arguments_preview = input.argumentsPreview; + if (input.errorMessage) nodeProps.error_message = input.errorMessage; + if (input.reasoningSequence !== undefined) + nodeProps.reasoning_sequence = input.reasoningSequence; + + const propsString = this.buildPropertyString(nodeProps); + + // Create node and link to turn + await this.query( + `MATCH (t:Turn {id: $turnId}) + WHERE t.tt_end = ${this.maxDate} + CREATE (tc:ToolCall {${propsString}}) + CREATE (t)-[:${EdgeTypes.INVOKES} {vt_start: $vt_start, vt_end: $vt_end, tt_start: $tt_start, tt_end: $tt_end}]->(tc)`, + { turnId: input.turnId, ...nodeProps }, + ); + + // If there's a reasoning sequence, link to the triggering Reasoning node + if (input.reasoningSequence !== undefined) { + await this.query( + `MATCH (t:Turn {id: $turnId})-[:${EdgeTypes.CONTAINS}]->(r:Reasoning {sequence_index: $reasoningSeq}) + MATCH (t)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall {id: $tcId}) + WHERE r.tt_end = ${this.maxDate} AND tc.tt_end = ${this.maxDate} + CREATE (r)-[:${EdgeTypes.TRIGGERS} {vt_start: $vtStart, vt_end: ${this.maxDate}, tt_start: $ttStart, tt_end: ${this.maxDate}}]->(tc)`, + { + turnId: input.turnId, + reasoningSeq: input.reasoningSequence, + tcId: id, + vtStart: temporal.vt_start, + ttStart: temporal.tt_start, + }, + ); + } + + return { + id, + turnId: input.turnId, + callId: input.callId, + toolName: input.toolName, + toolType: input.toolType ?? "unknown", + argumentsJson: input.argumentsJson, + argumentsPreview: input.argumentsPreview, + status: input.status ?? "pending", + errorMessage: input.errorMessage, + sequenceIndex: input.sequenceIndex, + reasoningSequence: input.reasoningSequence, + vtStart: temporal.vt_start, + vtEnd: temporal.vt_end, + ttStart: temporal.tt_start, + ttEnd: temporal.tt_end, + }; + } + + async createBatch(inputs: CreateToolCallInput[]): Promise { + const results: ToolCall[] = []; + + // Group inputs by turnId for more efficient batching + const byTurn = new Map(); + for (const input of inputs) { + const existing = byTurn.get(input.turnId) ?? []; + existing.push(input); + byTurn.set(input.turnId, existing); + } + + for (const [turnId, turnInputs] of byTurn) { + for (const input of turnInputs) { + const toolCall = await this.create({ ...input, turnId }); + results.push(toolCall); + } + } + + return results; + } + + async updateResult(id: string, result: ToolResult): Promise { + const existing = await this.findById(id); + if (!existing) { + throw new Error(`ToolCall not found: ${id}`); + } + + const updateProps: Record = { + status: result.status, + }; + if (result.errorMessage) updateProps.error_message = result.errorMessage; + + const setClause = this.buildSetClause(updateProps, "tc"); + await this.query( + `MATCH (tc:ToolCall {id: $id}) WHERE tc.tt_end = ${this.maxDate} SET ${setClause}`, + { id, ...updateProps }, + ); + + return { + ...existing, + status: result.status, + errorMessage: result.errorMessage ?? existing.errorMessage, + }; + } + + async count(turnId: string): Promise { + const results = await this.query<{ cnt: number }>( + `MATCH (t:Turn {id: $turnId})-[:${EdgeTypes.INVOKES}]->(tc:ToolCall) + WHERE tc.tt_end = ${this.maxDate} + RETURN count(tc) as cnt`, + { turnId }, + ); + return results[0]?.cnt ?? 0; + } + + async countByStatus(sessionId: string): Promise> { + const results = await this.query<{ status: string; cnt: number }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn)-[:${EdgeTypes.INVOKES}]->(tc:ToolCall) + WHERE t.tt_end = ${this.maxDate} AND tc.tt_end = ${this.maxDate} + RETURN tc.status as status, count(tc) as cnt`, + { sessionId }, + ); + + const counts: Record = {}; + for (const row of results) { + counts[row.status] = row.cnt; + } + return counts; + } + + /** + * Map FalkorDB node to domain ToolCall object. + */ + private mapToToolCall(node: FalkorNode, turnId: string): ToolCall { + const props = node.properties; + return { + id: props.id, + turnId, + callId: props.call_id, + toolName: props.tool_name, + toolType: props.tool_type, + argumentsJson: props.arguments_json, + argumentsPreview: props.arguments_preview, + status: props.status, + errorMessage: props.error_message, + sequenceIndex: props.sequence_index, + reasoningSequence: props.reasoning_sequence, + vtStart: props.vt_start, + vtEnd: props.vt_end, + ttStart: props.tt_start, + ttEnd: props.tt_end, + }; + } +} diff --git a/packages/graph/src/repositories/falkor-turn.repository.ts b/packages/graph/src/repositories/falkor-turn.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..60bb4219217043f2e706bcc0281a731f8b8b5010 --- /dev/null +++ b/packages/graph/src/repositories/falkor-turn.repository.ts @@ -0,0 +1,280 @@ +import type { FalkorNode } from "@engram/storage"; +import { EdgeTypes } from "../models/edges"; +import { FalkorBaseRepository } from "./falkor-base"; +import type { TurnRepository } from "./turn.repository"; +import type { CreateTurnInput, Turn, UpdateTurnInput } from "./types"; + +/** + * Raw FalkorDB Turn node properties. + */ +type TurnNodeProps = { + id: string; + user_content: string; + user_content_hash: string; + assistant_preview: string; + assistant_blob_ref?: string; + embedding?: number[]; + sequence_index: number; + files_touched: string[]; + tool_calls_count: number; + input_tokens?: number; + output_tokens?: number; + cache_read_tokens?: number; + cache_write_tokens?: number; + reasoning_tokens?: number; + cost_usd?: number; + duration_ms?: number; + git_commit?: string; + vt_start: number; + vt_end: number; + tt_start: number; + tt_end: number; + [key: string]: unknown; +}; + +/** + * FalkorDB implementation of TurnRepository. + */ +export class FalkorTurnRepository extends FalkorBaseRepository implements TurnRepository { + async findById(id: string): Promise { + const results = await this.query<{ t: FalkorNode; sessionId: string }>( + `MATCH (s:Session)-[:${EdgeTypes.HAS_TURN}]->(t:Turn {id: $id}) + WHERE t.tt_end = ${this.maxDate} + RETURN t, s.id as sessionId`, + { id }, + ); + if (!results[0]?.t) return null; + return this.mapToTurn(results[0].t, results[0].sessionId); + } + + async findBySession(sessionId: string): Promise { + const results = await this.query<{ t: FalkorNode }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn) + WHERE t.tt_end = ${this.maxDate} + RETURN t + ORDER BY t.sequence_index ASC`, + { sessionId }, + ); + return results.map((r) => this.mapToTurn(r.t, sessionId)); + } + + async findByTimeRange(sessionId: string, start: Date, end: Date): Promise { + const results = await this.query<{ t: FalkorNode }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn) + WHERE t.tt_end = ${this.maxDate} + AND t.vt_start >= $startTime + AND t.vt_start < $endTime + RETURN t + ORDER BY t.sequence_index ASC`, + { sessionId, startTime: start.getTime(), endTime: end.getTime() }, + ); + return results.map((r) => this.mapToTurn(r.t, sessionId)); + } + + async findLatest(sessionId: string, limit: number = 10): Promise { + const results = await this.query<{ t: FalkorNode }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn) + WHERE t.tt_end = ${this.maxDate} + RETURN t + ORDER BY t.sequence_index DESC + LIMIT $limit`, + { sessionId, limit }, + ); + // Reverse to get chronological order + return results.reverse().map((r) => this.mapToTurn(r.t, sessionId)); + } + + async findByFilePath(sessionId: string, filePath: string): Promise { + // FalkorDB list contains check + const results = await this.query<{ t: FalkorNode }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn) + WHERE t.tt_end = ${this.maxDate} + AND $filePath IN t.files_touched + RETURN t + ORDER BY t.sequence_index ASC`, + { sessionId, filePath }, + ); + return results.map((r) => this.mapToTurn(r.t, sessionId)); + } + + async create(input: CreateTurnInput): Promise { + const id = this.generateId(); + const temporal = this.createBitemporal(); + + const nodeProps: Record = { + id, + user_content: input.userContent, + user_content_hash: input.userContentHash, + assistant_preview: input.assistantPreview, + sequence_index: input.sequenceIndex, + files_touched: input.filesTouched ?? [], + tool_calls_count: input.toolCallsCount ?? 0, + vt_start: temporal.vt_start, + vt_end: temporal.vt_end, + tt_start: temporal.tt_start, + tt_end: temporal.tt_end, + }; + + // Optional fields + if (input.assistantBlobRef) nodeProps.assistant_blob_ref = input.assistantBlobRef; + if (input.embedding) nodeProps.embedding = input.embedding; + if (input.inputTokens !== undefined) nodeProps.input_tokens = input.inputTokens; + if (input.outputTokens !== undefined) nodeProps.output_tokens = input.outputTokens; + if (input.cacheReadTokens !== undefined) nodeProps.cache_read_tokens = input.cacheReadTokens; + if (input.cacheWriteTokens !== undefined) nodeProps.cache_write_tokens = input.cacheWriteTokens; + if (input.reasoningTokens !== undefined) nodeProps.reasoning_tokens = input.reasoningTokens; + if (input.costUsd !== undefined) nodeProps.cost_usd = input.costUsd; + if (input.durationMs !== undefined) nodeProps.duration_ms = input.durationMs; + if (input.gitCommit) nodeProps.git_commit = input.gitCommit; + + const propsString = this.buildPropertyString(nodeProps); + + // Create node and link to session + await this.query( + `MATCH (s:Session {id: $sessionId}) + WHERE s.tt_end = ${this.maxDate} + CREATE (t:Turn {${propsString}}) + CREATE (s)-[:${EdgeTypes.HAS_TURN} {vt_start: $vt_start, vt_end: $vt_end, tt_start: $tt_start, tt_end: $tt_end}]->(t)`, + { sessionId: input.sessionId, ...nodeProps }, + ); + + // Link to previous turn if exists + if (input.sequenceIndex > 0) { + await this.query( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(prev:Turn {sequence_index: $prevIndex}) + MATCH (s)-[:${EdgeTypes.HAS_TURN}]->(curr:Turn {id: $currId}) + WHERE prev.tt_end = ${this.maxDate} AND curr.tt_end = ${this.maxDate} + CREATE (prev)-[:${EdgeTypes.NEXT} {vt_start: $vtStart, vt_end: ${this.maxDate}, tt_start: $ttStart, tt_end: ${this.maxDate}}]->(curr)`, + { + sessionId: input.sessionId, + prevIndex: input.sequenceIndex - 1, + currId: id, + vtStart: temporal.vt_start, + ttStart: temporal.tt_start, + }, + ); + } + + return { + id, + sessionId: input.sessionId, + userContent: input.userContent, + userContentHash: input.userContentHash, + assistantPreview: input.assistantPreview, + assistantBlobRef: input.assistantBlobRef, + embedding: input.embedding, + sequenceIndex: input.sequenceIndex, + filesTouched: input.filesTouched ?? [], + toolCallsCount: input.toolCallsCount ?? 0, + inputTokens: input.inputTokens, + outputTokens: input.outputTokens, + cacheReadTokens: input.cacheReadTokens, + cacheWriteTokens: input.cacheWriteTokens, + reasoningTokens: input.reasoningTokens, + costUsd: input.costUsd, + durationMs: input.durationMs, + gitCommit: input.gitCommit, + vtStart: temporal.vt_start, + vtEnd: temporal.vt_end, + ttStart: temporal.tt_start, + ttEnd: temporal.tt_end, + }; + } + + async update(id: string, updates: UpdateTurnInput): Promise { + const existing = await this.findById(id); + if (!existing) { + throw new Error(`Turn not found: ${id}`); + } + + // Build update SET clause + const updateProps: Record = {}; + if (updates.assistantPreview !== undefined) + updateProps.assistant_preview = updates.assistantPreview; + if (updates.assistantBlobRef !== undefined) + updateProps.assistant_blob_ref = updates.assistantBlobRef; + if (updates.embedding !== undefined) updateProps.embedding = updates.embedding; + if (updates.filesTouched !== undefined) updateProps.files_touched = updates.filesTouched; + if (updates.toolCallsCount !== undefined) updateProps.tool_calls_count = updates.toolCallsCount; + if (updates.inputTokens !== undefined) updateProps.input_tokens = updates.inputTokens; + if (updates.outputTokens !== undefined) updateProps.output_tokens = updates.outputTokens; + if (updates.cacheReadTokens !== undefined) + updateProps.cache_read_tokens = updates.cacheReadTokens; + if (updates.cacheWriteTokens !== undefined) + updateProps.cache_write_tokens = updates.cacheWriteTokens; + if (updates.reasoningTokens !== undefined) + updateProps.reasoning_tokens = updates.reasoningTokens; + if (updates.costUsd !== undefined) updateProps.cost_usd = updates.costUsd; + if (updates.durationMs !== undefined) updateProps.duration_ms = updates.durationMs; + if (updates.gitCommit !== undefined) updateProps.git_commit = updates.gitCommit; + + if (Object.keys(updateProps).length === 0) { + return existing; + } + + const setClause = this.buildSetClause(updateProps, "t"); + await this.query(`MATCH (t:Turn {id: $id}) WHERE t.tt_end = ${this.maxDate} SET ${setClause}`, { + id, + ...updateProps, + }); + + // Return updated turn + return { + ...existing, + assistantPreview: updates.assistantPreview ?? existing.assistantPreview, + assistantBlobRef: updates.assistantBlobRef ?? existing.assistantBlobRef, + embedding: updates.embedding ?? existing.embedding, + filesTouched: updates.filesTouched ?? existing.filesTouched, + toolCallsCount: updates.toolCallsCount ?? existing.toolCallsCount, + inputTokens: updates.inputTokens ?? existing.inputTokens, + outputTokens: updates.outputTokens ?? existing.outputTokens, + cacheReadTokens: updates.cacheReadTokens ?? existing.cacheReadTokens, + cacheWriteTokens: updates.cacheWriteTokens ?? existing.cacheWriteTokens, + reasoningTokens: updates.reasoningTokens ?? existing.reasoningTokens, + costUsd: updates.costUsd ?? existing.costUsd, + durationMs: updates.durationMs ?? existing.durationMs, + gitCommit: updates.gitCommit ?? existing.gitCommit, + }; + } + + async count(sessionId: string): Promise { + const results = await this.query<{ cnt: number }>( + `MATCH (s:Session {id: $sessionId})-[:${EdgeTypes.HAS_TURN}]->(t:Turn) + WHERE t.tt_end = ${this.maxDate} + RETURN count(t) as cnt`, + { sessionId }, + ); + return results[0]?.cnt ?? 0; + } + + /** + * Map FalkorDB node to domain Turn object. + */ + private mapToTurn(node: FalkorNode, sessionId: string): Turn { + const props = node.properties; + return { + id: props.id, + sessionId, + userContent: props.user_content, + userContentHash: props.user_content_hash, + assistantPreview: props.assistant_preview, + assistantBlobRef: props.assistant_blob_ref, + embedding: props.embedding, + sequenceIndex: props.sequence_index, + filesTouched: props.files_touched ?? [], + toolCallsCount: props.tool_calls_count ?? 0, + inputTokens: props.input_tokens, + outputTokens: props.output_tokens, + cacheReadTokens: props.cache_read_tokens, + cacheWriteTokens: props.cache_write_tokens, + reasoningTokens: props.reasoning_tokens, + costUsd: props.cost_usd, + durationMs: props.duration_ms, + gitCommit: props.git_commit, + vtStart: props.vt_start, + vtEnd: props.vt_end, + ttStart: props.tt_start, + ttEnd: props.tt_end, + }; + } +} diff --git a/packages/graph/src/repositories/index.ts b/packages/graph/src/repositories/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b6bc4a76afb55d7d68b537ea8985444cf5b04a4 --- /dev/null +++ b/packages/graph/src/repositories/index.ts @@ -0,0 +1,50 @@ +// ============================================================================= +// Repository Interfaces +// ============================================================================= + +export type { ReasoningRepository } from "./reasoning.repository"; +export type { SessionRepository } from "./session.repository"; +export type { ToolCallRepository } from "./tool-call.repository"; +export type { TurnRepository } from "./turn.repository"; + +// ============================================================================= +// Repository Types (DTOs and Entities) +// ============================================================================= + +export type { + // Reasoning types + CreateReasoningInput, + // Session types + CreateSessionInput, + // ToolCall types + CreateToolCallInput, + // Turn types + CreateTurnInput, + Reasoning, + Session, + ToolCall, + ToolResult, + Turn, + UpdateSessionInput, + UpdateTurnInput, +} from "./types"; + +export { + CreateReasoningInputSchema, + CreateSessionInputSchema, + CreateToolCallInputSchema, + CreateTurnInputSchema, + ToolResultSchema, + UpdateSessionInputSchema, + UpdateTurnInputSchema, +} from "./types"; + +// ============================================================================= +// FalkorDB Implementations +// ============================================================================= + +export { FalkorBaseRepository } from "./falkor-base"; +export { FalkorReasoningRepository } from "./falkor-reasoning.repository"; +export { FalkorSessionRepository } from "./falkor-session.repository"; +export { FalkorToolCallRepository } from "./falkor-tool-call.repository"; +export { FalkorTurnRepository } from "./falkor-turn.repository"; diff --git a/packages/graph/src/repositories/reasoning.repository.ts b/packages/graph/src/repositories/reasoning.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3db4ec7f90c9b1e2aceb64e21afc72f97575eb6 --- /dev/null +++ b/packages/graph/src/repositories/reasoning.repository.ts @@ -0,0 +1,61 @@ +import type { CreateReasoningInput, Reasoning } from "./types"; + +/** + * ReasoningRepository abstracts data access for Reasoning entities. + * + * Reasoning nodes capture thinking/reasoning blocks within a turn. + * They are linked to Turns via CONTAINS edges and may TRIGGER ToolCalls. + */ +export interface ReasoningRepository { + /** + * Find a reasoning block by its ULID. + * @param id - The reasoning ID + * @returns The reasoning or null if not found + */ + findById(id: string): Promise; + + /** + * Find all reasoning blocks within a turn. + * @param turnId - The parent turn ID + * @returns Array of reasoning blocks, ordered by sequence index + */ + findByTurn(turnId: string): Promise; + + /** + * Find all reasoning blocks within a session. + * Aggregates reasoning across all turns in the session. + * @param sessionId - The session ID + * @returns Array of reasoning blocks, ordered by turn sequence then reasoning sequence + */ + findBySession(sessionId: string): Promise; + + /** + * Find reasoning by type within a session. + * @param sessionId - The session ID + * @param reasoningType - The type of reasoning (chain_of_thought, reflection, etc.) + * @returns Array of matching reasoning blocks + */ + findByType(sessionId: string, reasoningType: string): Promise; + + /** + * Create a new reasoning block and link it to its turn. + * @param input - Reasoning creation parameters including turnId + * @returns The created reasoning block + */ + create(input: CreateReasoningInput): Promise; + + /** + * Create multiple reasoning blocks in a batch. + * More efficient than creating one at a time. + * @param inputs - Array of reasoning creation parameters + * @returns Array of created reasoning blocks + */ + createBatch(inputs: CreateReasoningInput[]): Promise; + + /** + * Count reasoning blocks in a turn. + * @param turnId - The parent turn ID + * @returns Number of reasoning blocks in the turn + */ + count(turnId: string): Promise; +} diff --git a/packages/graph/src/repositories/repositories.test.ts b/packages/graph/src/repositories/repositories.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c64c19129fad111148e5466f4d775c0cb02e33a3 --- /dev/null +++ b/packages/graph/src/repositories/repositories.test.ts @@ -0,0 +1,509 @@ +import type { GraphClient } from "@engram/storage"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { FalkorReasoningRepository } from "./falkor-reasoning.repository"; +import { FalkorSessionRepository } from "./falkor-session.repository"; +import { FalkorToolCallRepository } from "./falkor-tool-call.repository"; +import { FalkorTurnRepository } from "./falkor-turn.repository"; + +// Mock GraphClient +const createMockGraphClient = () => ({ + connect: vi.fn(async () => {}), + disconnect: vi.fn(async () => {}), + query: vi.fn(async () => []), + isConnected: vi.fn(() => true), +}); + +describe("FalkorSessionRepository", () => { + let mockClient: ReturnType; + let repository: FalkorSessionRepository; + + beforeEach(() => { + mockClient = createMockGraphClient(); + repository = new FalkorSessionRepository(mockClient as unknown as GraphClient); + }); + + describe("findById", () => { + it("should return null when session not found", async () => { + mockClient.query.mockResolvedValueOnce([]); + + const result = await repository.findById("non-existent"); + + expect(result).toBeNull(); + expect(mockClient.query).toHaveBeenCalledWith( + expect.stringContaining("MATCH (s:Session {id: $id})"), + { id: "non-existent" }, + ); + }); + + it("should return mapped session when found", async () => { + mockClient.query.mockResolvedValueOnce([ + { + s: { + id: 1, + labels: ["Session"], + properties: { + id: "sess-123", + user_id: "user-1", + started_at: 1700000000000, + agent_type: "claude-code", + vt_start: 1700000000000, + vt_end: 253402300799000, + tt_start: 1700000000000, + tt_end: 253402300799000, + }, + }, + }, + ]); + + const result = await repository.findById("sess-123"); + + expect(result).not.toBeNull(); + expect(result?.id).toBe("sess-123"); + expect(result?.userId).toBe("user-1"); + expect(result?.agentType).toBe("claude-code"); + }); + }); + + describe("create", () => { + it("should create a session with required fields", async () => { + mockClient.query.mockResolvedValueOnce([ + { + s: { + id: 1, + labels: ["Session"], + properties: { + id: expect.any(String), + user_id: "user-1", + started_at: expect.any(Number), + agent_type: "opencode", + vt_start: expect.any(Number), + vt_end: 253402300799000, + tt_start: expect.any(Number), + tt_end: 253402300799000, + }, + }, + }, + ]); + + const result = await repository.create({ + userId: "user-1", + agentType: "opencode", + }); + + expect(mockClient.query).toHaveBeenCalled(); + const [query, params] = mockClient.query.mock.calls[0]; + expect(query).toContain("CREATE (s:Session"); + expect(params).toMatchObject({ + user_id: "user-1", + agent_type: "opencode", + }); + }); + + it("should include optional fields when provided", async () => { + mockClient.query.mockResolvedValueOnce([ + { + s: { + id: 1, + labels: ["Session"], + properties: { + id: expect.any(String), + user_id: "user-1", + external_id: "ext-123", + title: "Test Session", + working_dir: "/projects/test", + started_at: expect.any(Number), + agent_type: "claude-code", + vt_start: expect.any(Number), + vt_end: 253402300799000, + tt_start: expect.any(Number), + tt_end: 253402300799000, + }, + }, + }, + ]); + + await repository.create({ + userId: "user-1", + externalId: "ext-123", + title: "Test Session", + workingDir: "/projects/test", + agentType: "claude-code", + }); + + const [, params] = mockClient.query.mock.calls[0]; + expect(params).toMatchObject({ + external_id: "ext-123", + title: "Test Session", + working_dir: "/projects/test", + }); + }); + }); + + describe("delete", () => { + it("should soft delete by setting tt_end", async () => { + // First call for findById + mockClient.query.mockResolvedValueOnce([ + { + s: { + id: 1, + labels: ["Session"], + properties: { + id: "sess-123", + user_id: "user-1", + started_at: 1700000000000, + agent_type: "claude-code", + vt_start: 1700000000000, + vt_end: 253402300799000, + tt_start: 1700000000000, + tt_end: 253402300799000, + }, + }, + }, + ]); + + // Second call for soft delete + mockClient.query.mockResolvedValueOnce([]); + + await repository.delete("sess-123"); + + expect(mockClient.query).toHaveBeenCalledTimes(2); + const [deleteQuery] = mockClient.query.mock.calls[1]; + expect(deleteQuery).toContain("SET n.tt_end = $t"); + }); + + it("should throw when session not found", async () => { + mockClient.query.mockResolvedValueOnce([]); + + await expect(repository.delete("non-existent")).rejects.toThrow( + "Session not found: non-existent", + ); + }); + }); +}); + +describe("FalkorTurnRepository", () => { + let mockClient: ReturnType; + let repository: FalkorTurnRepository; + + beforeEach(() => { + mockClient = createMockGraphClient(); + repository = new FalkorTurnRepository(mockClient as unknown as GraphClient); + }); + + describe("findBySession", () => { + it("should return turns ordered by sequence index", async () => { + mockClient.query.mockResolvedValueOnce([ + { + t: { + id: 1, + labels: ["Turn"], + properties: { + id: "turn-1", + user_content: "Hello", + user_content_hash: "abc123", + assistant_preview: "Hi there!", + sequence_index: 0, + files_touched: [], + tool_calls_count: 0, + vt_start: 1700000000000, + vt_end: 253402300799000, + tt_start: 1700000000000, + tt_end: 253402300799000, + }, + }, + }, + { + t: { + id: 2, + labels: ["Turn"], + properties: { + id: "turn-2", + user_content: "How are you?", + user_content_hash: "def456", + assistant_preview: "I am fine!", + sequence_index: 1, + files_touched: [], + tool_calls_count: 0, + vt_start: 1700000001000, + vt_end: 253402300799000, + tt_start: 1700000001000, + tt_end: 253402300799000, + }, + }, + }, + ]); + + const result = await repository.findBySession("sess-123"); + + expect(result).toHaveLength(2); + expect(result[0].sequenceIndex).toBe(0); + expect(result[1].sequenceIndex).toBe(1); + }); + }); + + describe("create", () => { + it("should create turn and link to session", async () => { + // Mock for create query + mockClient.query.mockResolvedValueOnce([]); + + await repository.create({ + sessionId: "sess-123", + userContent: "Hello", + userContentHash: "abc123", + assistantPreview: "Hi there!", + sequenceIndex: 0, + filesTouched: [], + toolCallsCount: 0, + }); + + const [query] = mockClient.query.mock.calls[0]; + expect(query).toContain("MATCH (s:Session {id: $sessionId})"); + expect(query).toContain("CREATE (t:Turn"); + expect(query).toContain("CREATE (s)-[:HAS_TURN"); + }); + + it("should link to previous turn when sequence > 0", async () => { + // Mock for create query + mockClient.query.mockResolvedValueOnce([]); + // Mock for NEXT edge query + mockClient.query.mockResolvedValueOnce([]); + + await repository.create({ + sessionId: "sess-123", + userContent: "Follow up", + userContentHash: "xyz789", + assistantPreview: "Response", + sequenceIndex: 1, + filesTouched: [], + toolCallsCount: 0, + }); + + expect(mockClient.query).toHaveBeenCalledTimes(2); + const [nextQuery] = mockClient.query.mock.calls[1]; + expect(nextQuery).toContain("CREATE (prev)-[:NEXT"); + }); + }); + + describe("count", () => { + it("should return count of turns in session", async () => { + mockClient.query.mockResolvedValueOnce([{ cnt: 5 }]); + + const result = await repository.count("sess-123"); + + expect(result).toBe(5); + }); + }); +}); + +describe("FalkorReasoningRepository", () => { + let mockClient: ReturnType; + let repository: FalkorReasoningRepository; + + beforeEach(() => { + mockClient = createMockGraphClient(); + repository = new FalkorReasoningRepository(mockClient as unknown as GraphClient); + }); + + describe("findByTurn", () => { + it("should return reasoning blocks ordered by sequence", async () => { + mockClient.query.mockResolvedValueOnce([ + { + r: { + id: 1, + labels: ["Reasoning"], + properties: { + id: "reason-1", + content_hash: "hash1", + preview: "Let me think...", + reasoning_type: "chain_of_thought", + sequence_index: 0, + vt_start: 1700000000000, + vt_end: 253402300799000, + tt_start: 1700000000000, + tt_end: 253402300799000, + }, + }, + }, + ]); + + const result = await repository.findByTurn("turn-123"); + + expect(result).toHaveLength(1); + expect(result[0].reasoningType).toBe("chain_of_thought"); + }); + }); + + describe("create", () => { + it("should create reasoning and link to turn", async () => { + mockClient.query.mockResolvedValueOnce([]); + + const result = await repository.create({ + turnId: "turn-123", + contentHash: "hash123", + preview: "Thinking about this...", + reasoningType: "analysis", + sequenceIndex: 0, + }); + + const [query, params] = mockClient.query.mock.calls[0]; + expect(query).toContain("MATCH (t:Turn {id: $turnId})"); + expect(query).toContain("CREATE (r:Reasoning"); + expect(query).toContain("CREATE (t)-[:CONTAINS"); + expect(params).toMatchObject({ + turnId: "turn-123", + content_hash: "hash123", + }); + expect(result.turnId).toBe("turn-123"); + }); + }); +}); + +describe("FalkorToolCallRepository", () => { + let mockClient: ReturnType; + let repository: FalkorToolCallRepository; + + beforeEach(() => { + mockClient = createMockGraphClient(); + repository = new FalkorToolCallRepository(mockClient as unknown as GraphClient); + }); + + describe("findByCallId", () => { + it("should find tool call by provider call ID", async () => { + mockClient.query.mockResolvedValueOnce([ + { + tc: { + id: 1, + labels: ["ToolCall"], + properties: { + id: "tc-123", + call_id: "toolu_01ABC", + tool_name: "Read", + tool_type: "file_read", + arguments_json: '{"path": "/test.ts"}', + status: "success", + sequence_index: 0, + vt_start: 1700000000000, + vt_end: 253402300799000, + tt_start: 1700000000000, + tt_end: 253402300799000, + }, + }, + turnId: "turn-123", + }, + ]); + + const result = await repository.findByCallId("toolu_01ABC"); + + expect(result).not.toBeNull(); + expect(result?.callId).toBe("toolu_01ABC"); + expect(result?.toolType).toBe("file_read"); + }); + }); + + describe("create", () => { + it("should create tool call and link to turn", async () => { + mockClient.query.mockResolvedValueOnce([]); + + const result = await repository.create({ + turnId: "turn-123", + callId: "toolu_01XYZ", + toolName: "Bash", + toolType: "bash_exec", + argumentsJson: '{"command": "ls"}', + sequenceIndex: 0, + }); + + const [query, params] = mockClient.query.mock.calls[0]; + expect(query).toContain("MATCH (t:Turn {id: $turnId})"); + expect(query).toContain("CREATE (tc:ToolCall"); + expect(query).toContain("CREATE (t)-[:INVOKES"); + expect(params.call_id).toBe("toolu_01XYZ"); + expect(result.status).toBe("pending"); + }); + + it("should link to reasoning when reasoningSequence provided", async () => { + // First call for create + mockClient.query.mockResolvedValueOnce([]); + // Second call for TRIGGERS edge + mockClient.query.mockResolvedValueOnce([]); + + await repository.create({ + turnId: "turn-123", + callId: "toolu_01XYZ", + toolName: "Read", + toolType: "file_read", + argumentsJson: '{"path": "/test.ts"}', + sequenceIndex: 0, + reasoningSequence: 0, + }); + + expect(mockClient.query).toHaveBeenCalledTimes(2); + const [triggersQuery] = mockClient.query.mock.calls[1]; + expect(triggersQuery).toContain("CREATE (r)-[:TRIGGERS"); + }); + }); + + describe("updateResult", () => { + it("should update tool call status and error", async () => { + // First call for findById + mockClient.query.mockResolvedValueOnce([ + { + tc: { + id: 1, + labels: ["ToolCall"], + properties: { + id: "tc-123", + call_id: "toolu_01ABC", + tool_name: "Bash", + tool_type: "bash_exec", + arguments_json: '{"command": "ls"}', + status: "pending", + sequence_index: 0, + vt_start: 1700000000000, + vt_end: 253402300799000, + tt_start: 1700000000000, + tt_end: 253402300799000, + }, + }, + turnId: "turn-123", + }, + ]); + // Second call for update + mockClient.query.mockResolvedValueOnce([]); + + const result = await repository.updateResult("tc-123", { + status: "error", + errorMessage: "Command failed", + }); + + expect(result.status).toBe("error"); + expect(result.errorMessage).toBe("Command failed"); + }); + + it("should throw when tool call not found", async () => { + mockClient.query.mockResolvedValueOnce([]); + + await expect(repository.updateResult("non-existent", { status: "success" })).rejects.toThrow( + "ToolCall not found: non-existent", + ); + }); + }); + + describe("countByStatus", () => { + it("should return counts grouped by status", async () => { + mockClient.query.mockResolvedValueOnce([ + { status: "success", cnt: 10 }, + { status: "error", cnt: 2 }, + { status: "pending", cnt: 1 }, + ]); + + const result = await repository.countByStatus("sess-123"); + + expect(result).toEqual({ + success: 10, + error: 2, + pending: 1, + }); + }); + }); +}); diff --git a/packages/graph/src/repositories/session.repository.ts b/packages/graph/src/repositories/session.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..82a0f5ce67b108d2eee99e6c135fa048cb2c4c0b --- /dev/null +++ b/packages/graph/src/repositories/session.repository.ts @@ -0,0 +1,79 @@ +import type { CreateSessionInput, Session, UpdateSessionInput } from "./types"; + +/** + * SessionRepository abstracts data access for Session entities. + * + * This interface decouples business logic from the underlying graph database, + * enabling: + * - Unit testing with mock implementations + * - Swapping storage backends without changing consumers + * - Clear separation of concerns + */ +export interface SessionRepository { + /** + * Find a session by its internal ULID. + * @param id - The internal session ID (ULID) + * @returns The session or null if not found + */ + findById(id: string): Promise; + + /** + * Find a session by its external provider ID. + * @param externalId - The external ID from the agent provider (e.g., Claude session ID) + * @returns The session or null if not found + */ + findByExternalId(externalId: string): Promise; + + /** + * Find all active sessions (not logically deleted). + * Active sessions have tt_end = MAX_DATE. + * @returns Array of active sessions, ordered by start time descending + */ + findActive(): Promise; + + /** + * Find all sessions from a specific agent provider. + * @param provider - The agent provider name (e.g., "claude-code", "opencode") + * @returns Array of sessions for the provider + */ + findByProvider(provider: string): Promise; + + /** + * Find all sessions for a specific user. + * @param userId - The user ID + * @returns Array of sessions for the user + */ + findByUser(userId: string): Promise; + + /** + * Find sessions by working directory (project context). + * @param workingDir - The working directory path + * @returns Array of sessions for the working directory + */ + findByWorkingDir(workingDir: string): Promise; + + /** + * Create a new session. + * @param input - Session creation parameters + * @returns The created session with generated ID and timestamps + */ + create(input: CreateSessionInput): Promise; + + /** + * Update an existing session. + * Creates a new bitemporal version (old version is preserved with closed tt_end). + * @param id - The session ID to update + * @param updates - Partial session fields to update + * @returns The updated session + * @throws Error if session not found + */ + update(id: string, updates: UpdateSessionInput): Promise; + + /** + * Soft delete a session (closes its transaction time). + * The session is preserved for historical queries but won't appear in findActive(). + * @param id - The session ID to delete + * @throws Error if session not found + */ + delete(id: string): Promise; +} diff --git a/packages/graph/src/repositories/tool-call.repository.ts b/packages/graph/src/repositories/tool-call.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..63957ab07e045bb3b7e4c6f7feef1501fe71294c --- /dev/null +++ b/packages/graph/src/repositories/tool-call.repository.ts @@ -0,0 +1,100 @@ +import type { CreateToolCallInput, ToolCall, ToolResult } from "./types"; + +/** + * ToolCallRepository abstracts data access for ToolCall entities. + * + * ToolCall nodes capture every tool invocation during agent execution. + * They are linked to Turns via INVOKES edges and may be TRIGGERED by Reasoning. + */ +export interface ToolCallRepository { + /** + * Find a tool call by its ULID. + * @param id - The tool call ID + * @returns The tool call or null if not found + */ + findById(id: string): Promise; + + /** + * Find a tool call by its provider call ID. + * @param callId - The provider's call ID (e.g., "toolu_01ABC...") + * @returns The tool call or null if not found + */ + findByCallId(callId: string): Promise; + + /** + * Find all tool calls within a turn. + * @param turnId - The parent turn ID + * @returns Array of tool calls, ordered by sequence index + */ + findByTurn(turnId: string): Promise; + + /** + * Find all tool calls within a session. + * Aggregates tool calls across all turns in the session. + * @param sessionId - The session ID + * @returns Array of tool calls, ordered by turn sequence then tool sequence + */ + findBySession(sessionId: string): Promise; + + /** + * Find tool calls by tool type within a session. + * @param sessionId - The session ID + * @param toolType - The categorized tool type (e.g., "file_read", "bash_exec") + * @returns Array of matching tool calls + */ + findByToolType(sessionId: string, toolType: string): Promise; + + /** + * Find tool calls by status within a session. + * @param sessionId - The session ID + * @param status - The tool call status (pending, success, error, cancelled) + * @returns Array of matching tool calls + */ + findByStatus(sessionId: string, status: string): Promise; + + /** + * Find pending tool calls (not yet completed). + * @param sessionId - Optional session ID to filter by + * @returns Array of pending tool calls + */ + findPending(sessionId?: string): Promise; + + /** + * Create a new tool call and link it to its turn. + * @param input - Tool call creation parameters including turnId + * @returns The created tool call + */ + create(input: CreateToolCallInput): Promise; + + /** + * Create multiple tool calls in a batch. + * More efficient than creating one at a time. + * @param inputs - Array of tool call creation parameters + * @returns Array of created tool calls + */ + createBatch(inputs: CreateToolCallInput[]): Promise; + + /** + * Update a tool call with its execution result. + * Typically called after tool execution completes. + * @param id - The tool call ID + * @param result - The execution result (status, error, timing) + * @returns The updated tool call + * @throws Error if tool call not found + */ + updateResult(id: string, result: ToolResult): Promise; + + /** + * Count tool calls in a turn. + * @param turnId - The parent turn ID + * @returns Number of tool calls in the turn + */ + count(turnId: string): Promise; + + /** + * Count tool calls by status in a session. + * @param sessionId - The session ID + * @returns Object with counts per status + */ + countByStatus(sessionId: string): Promise>; +} diff --git a/packages/graph/src/repositories/turn.repository.ts b/packages/graph/src/repositories/turn.repository.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f2718493ec019dd359b32321fc3834190e7e832 --- /dev/null +++ b/packages/graph/src/repositories/turn.repository.ts @@ -0,0 +1,75 @@ +import type { CreateTurnInput, Turn, UpdateTurnInput } from "./types"; + +/** + * TurnRepository abstracts data access for Turn entities. + * + * A Turn represents a single conversation exchange: user prompt + assistant response. + * Turns are linked to Sessions via HAS_TURN edges and to each other via NEXT edges. + */ +export interface TurnRepository { + /** + * Find a turn by its ULID. + * @param id - The turn ID + * @returns The turn or null if not found + */ + findById(id: string): Promise; + + /** + * Find all turns belonging to a session. + * @param sessionId - The parent session ID + * @returns Array of turns, ordered by sequence index + */ + findBySession(sessionId: string): Promise; + + /** + * Find turns within a time range (by valid time). + * Useful for filtering conversation history by time window. + * @param sessionId - The parent session ID + * @param start - Start of time range (inclusive) + * @param end - End of time range (exclusive) + * @returns Array of turns within the time range + */ + findByTimeRange(sessionId: string, start: Date, end: Date): Promise; + + /** + * Find the most recent turns in a session. + * Useful for building conversation context windows. + * @param sessionId - The parent session ID + * @param limit - Maximum number of turns to return (default: 10) + * @returns Array of recent turns, ordered by sequence index descending + */ + findLatest(sessionId: string, limit?: number): Promise; + + /** + * Find turns that touched specific files. + * @param sessionId - The parent session ID + * @param filePath - The file path to search for (exact match) + * @returns Array of turns that touched the file + */ + findByFilePath(sessionId: string, filePath: string): Promise; + + /** + * Create a new turn and link it to its session. + * Also creates NEXT edge to the previous turn if one exists. + * @param input - Turn creation parameters including sessionId + * @returns The created turn + */ + create(input: CreateTurnInput): Promise; + + /** + * Update an existing turn. + * Creates a new bitemporal version. + * @param id - The turn ID to update + * @param updates - Partial turn fields to update + * @returns The updated turn + * @throws Error if turn not found + */ + update(id: string, updates: UpdateTurnInput): Promise; + + /** + * Count total turns in a session. + * @param sessionId - The parent session ID + * @returns Number of turns in the session + */ + count(sessionId: string): Promise; +} diff --git a/packages/graph/src/repositories/types.ts b/packages/graph/src/repositories/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..8eecbc968247a6b3843a1b27db10b3c417d458bb --- /dev/null +++ b/packages/graph/src/repositories/types.ts @@ -0,0 +1,212 @@ +import { z } from "zod"; + +// ============================================================================= +// Session Repository Types +// ============================================================================= + +export const CreateSessionInputSchema = z.object({ + externalId: z.string().optional(), + title: z.string().optional(), + userId: z.string(), + provider: z.string().optional(), + workingDir: z.string().optional(), + gitRemote: z.string().optional(), + agentType: z + .enum(["claude-code", "codex", "gemini-cli", "opencode", "aider", "cursor", "unknown"]) + .default("unknown"), + metadata: z.record(z.string(), z.unknown()).optional(), +}); + +export type CreateSessionInput = z.infer; + +export const UpdateSessionInputSchema = z.object({ + title: z.string().optional(), + summary: z.string().optional(), + embedding: z.array(z.number()).optional(), + metadata: z.record(z.string(), z.unknown()).optional(), +}); + +export type UpdateSessionInput = z.infer; + +/** + * Session entity returned from repository. + * Maps FalkorDB node properties to a clean domain object. + */ +export interface Session { + id: string; + externalId?: string; + title?: string; + userId: string; + provider?: string; + startedAt: Date; + workingDir?: string; + gitRemote?: string; + agentType: string; + summary?: string; + embedding?: number[]; + metadata?: Record; + // Bitemporal + vtStart: number; + vtEnd: number; + ttStart: number; + ttEnd: number; +} + +// ============================================================================= +// Turn Repository Types +// ============================================================================= + +export const CreateTurnInputSchema = z.object({ + sessionId: z.string(), + userContent: z.string(), + userContentHash: z.string(), + assistantPreview: z.string().max(2000), + assistantBlobRef: z.string().optional(), + embedding: z.array(z.number()).optional(), + sequenceIndex: z.number().int(), + filesTouched: z.array(z.string()).default([]), + toolCallsCount: z.number().int().default(0), + inputTokens: z.number().int().optional(), + outputTokens: z.number().int().optional(), + cacheReadTokens: z.number().int().optional(), + cacheWriteTokens: z.number().int().optional(), + reasoningTokens: z.number().int().optional(), + costUsd: z.number().optional(), + durationMs: z.number().int().optional(), + gitCommit: z.string().optional(), +}); + +export type CreateTurnInput = z.infer; + +export const UpdateTurnInputSchema = z.object({ + assistantPreview: z.string().max(2000).optional(), + assistantBlobRef: z.string().optional(), + embedding: z.array(z.number()).optional(), + filesTouched: z.array(z.string()).optional(), + toolCallsCount: z.number().int().optional(), + inputTokens: z.number().int().optional(), + outputTokens: z.number().int().optional(), + cacheReadTokens: z.number().int().optional(), + cacheWriteTokens: z.number().int().optional(), + reasoningTokens: z.number().int().optional(), + costUsd: z.number().optional(), + durationMs: z.number().int().optional(), + gitCommit: z.string().optional(), +}); + +export type UpdateTurnInput = z.infer; + +/** + * Turn entity returned from repository. + */ +export interface Turn { + id: string; + sessionId: string; + userContent: string; + userContentHash: string; + assistantPreview: string; + assistantBlobRef?: string; + embedding?: number[]; + sequenceIndex: number; + filesTouched: string[]; + toolCallsCount: number; + inputTokens?: number; + outputTokens?: number; + cacheReadTokens?: number; + cacheWriteTokens?: number; + reasoningTokens?: number; + costUsd?: number; + durationMs?: number; + gitCommit?: string; + // Bitemporal + vtStart: number; + vtEnd: number; + ttStart: number; + ttEnd: number; +} + +// ============================================================================= +// Reasoning Repository Types +// ============================================================================= + +export const CreateReasoningInputSchema = z.object({ + turnId: z.string(), + contentHash: z.string(), + preview: z.string().max(1000), + blobRef: z.string().optional(), + reasoningType: z + .enum(["chain_of_thought", "reflection", "planning", "analysis", "unknown"]) + .default("unknown"), + sequenceIndex: z.number().int(), + embedding: z.array(z.number()).optional(), +}); + +export type CreateReasoningInput = z.infer; + +/** + * Reasoning entity returned from repository. + */ +export interface Reasoning { + id: string; + turnId: string; + contentHash: string; + preview: string; + blobRef?: string; + reasoningType: string; + sequenceIndex: number; + embedding?: number[]; + // Bitemporal + vtStart: number; + vtEnd: number; + ttStart: number; + ttEnd: number; +} + +// ============================================================================= +// ToolCall Repository Types +// ============================================================================= + +export const CreateToolCallInputSchema = z.object({ + turnId: z.string(), + callId: z.string(), + toolName: z.string(), + toolType: z.string().default("unknown"), + argumentsJson: z.string(), + argumentsPreview: z.string().max(500).optional(), + status: z.enum(["pending", "success", "error", "cancelled"]).default("pending"), + errorMessage: z.string().optional(), + sequenceIndex: z.number().int(), + reasoningSequence: z.number().int().optional(), +}); + +export type CreateToolCallInput = z.infer; + +export const ToolResultSchema = z.object({ + status: z.enum(["success", "error", "cancelled"]), + errorMessage: z.string().optional(), + executionTimeMs: z.number().int().optional(), +}); + +export type ToolResult = z.infer; + +/** + * ToolCall entity returned from repository. + */ +export interface ToolCall { + id: string; + turnId: string; + callId: string; + toolName: string; + toolType: string; + argumentsJson: string; + argumentsPreview?: string; + status: string; + errorMessage?: string; + sequenceIndex: number; + reasoningSequence?: number; + // Bitemporal + vtStart: number; + vtEnd: number; + ttStart: number; + ttEnd: number; +} diff --git a/packages/graph/src/utils/time.test.ts b/packages/graph/src/utils/time.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0a2e6d0d15a8119ef74f9d959eb4470ddeaa0ca --- /dev/null +++ b/packages/graph/src/utils/time.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; +import { type Bitemporal, createBitemporal, MAX_DATE, now } from "./time"; + +describe("Time Utils", () => { + describe("MAX_DATE constant", () => { + it("should export MAX_DATE", () => { + expect(MAX_DATE).toBe(253402300799000); + }); + + it("should represent a date far in the future", () => { + const date = new Date(MAX_DATE); + expect(date.getFullYear()).toBe(9999); + }); + }); + + describe("now function", () => { + it("should return current timestamp", () => { + const before = Date.now(); + const result = now(); + const after = Date.now(); + + expect(result).toBeGreaterThanOrEqual(before); + expect(result).toBeLessThanOrEqual(after); + }); + + it("should return a number", () => { + expect(typeof now()).toBe("number"); + }); + }); + + describe("createBitemporal", () => { + it("should create bitemporal timestamps with defaults", () => { + const before = Date.now(); + const ts = createBitemporal(); + const after = Date.now(); + + expect(ts.vt_start).toBeGreaterThanOrEqual(before); + expect(ts.vt_start).toBeLessThanOrEqual(after); + expect(ts.vt_end).toBe(MAX_DATE); + expect(ts.tt_start).toBeGreaterThanOrEqual(before); + expect(ts.tt_start).toBeLessThanOrEqual(after); + expect(ts.tt_end).toBe(MAX_DATE); + }); + + it("should accept explicit valid time", () => { + const explicitTime = 1000; + const ts = createBitemporal(explicitTime); + + expect(ts.vt_start).toBe(explicitTime); + expect(ts.vt_end).toBe(MAX_DATE); + }); + + it("should set transaction time to current time regardless of valid time", () => { + const pastTime = 1000; // Way in the past + const before = Date.now(); + const ts = createBitemporal(pastTime); + const after = Date.now(); + + expect(ts.vt_start).toBe(pastTime); + expect(ts.tt_start).toBeGreaterThanOrEqual(before); + expect(ts.tt_start).toBeLessThanOrEqual(after); + }); + + it("should return Bitemporal type with all required fields", () => { + const ts: Bitemporal = createBitemporal(); + + expect(ts).toHaveProperty("vt_start"); + expect(ts).toHaveProperty("vt_end"); + expect(ts).toHaveProperty("tt_start"); + expect(ts).toHaveProperty("tt_end"); + }); + + it("should handle future valid time", () => { + const futureTime = Date.now() + 86400000; // Tomorrow + const ts = createBitemporal(futureTime); + + expect(ts.vt_start).toBe(futureTime); + expect(ts.vt_start).toBeGreaterThan(ts.tt_start); + }); + + it("should handle zero timestamp", () => { + const ts = createBitemporal(0); + + expect(ts.vt_start).toBe(0); + expect(ts.vt_end).toBe(MAX_DATE); + }); + }); +}); diff --git a/packages/graph/src/utils/time.ts b/packages/graph/src/utils/time.ts new file mode 100644 index 0000000000000000000000000000000000000000..d18a016564fe129db4a7d23df95cd707afd31435 --- /dev/null +++ b/packages/graph/src/utils/time.ts @@ -0,0 +1,15 @@ +import type { Bitemporal } from "../models/base"; + +export const MAX_DATE = 253402300799000; // 9999-12-31 + +export const now = () => Date.now(); + +export const createBitemporal = (validFrom: number = now()): Bitemporal => { + const t = now(); + return { + vt_start: validFrom, + vt_end: MAX_DATE, + tt_start: t, + tt_end: MAX_DATE, + }; +}; diff --git a/packages/graph/tsconfig.json b/packages/graph/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..641a81dc7930b9224a4c9e017be08450bf43e9f0 --- /dev/null +++ b/packages/graph/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@engram/tsconfig/base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "baseUrl": "." + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/logger/README.md b/packages/logger/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9e970f78292567d9ee2071b2576351a5467fc178 --- /dev/null +++ b/packages/logger/README.md @@ -0,0 +1,84 @@ +# @engram/logger + +Structured logging built on Pino. + +## Overview + +Provides consistent structured logging with support for tenant isolation and trace context propagation. Works in both Node.js and browser environments. + +## Installation + +```bash +npm install @engram/logger +``` + +## Usage + +### Node.js + +```typescript +import { createNodeLogger, childLogger } from "@engram/logger"; + +const logger = createNodeLogger({ + service: "memory", + level: "info", +}); + +logger.info("Service started"); +logger.error({ err }, "Operation failed"); + +// Create child logger with additional context +const requestLogger = childLogger(logger, { requestId: "abc-123" }); +requestLogger.info("Processing request"); +``` + +### Browser + +```typescript +import { createBrowserLogger } from "@engram/logger"; + +const logger = createBrowserLogger({ + service: "interface", + level: "debug", +}); +``` + +### Context Helpers + +```typescript +import { withTenantContext, withTraceContext } from "@engram/logger"; + +// Add tenant context +const tenantLogger = withTenantContext(logger, { tenantId: "tenant-1" }); + +// Add trace context +const traceLogger = withTraceContext(logger, { + traceId: "trace-123", + spanId: "span-456", +}); +``` + +### Direct Pino Access + +```typescript +import { pino } from "@engram/logger"; + +// Use Pino directly for advanced configuration +const customLogger = pino({ + level: "trace", + transport: { + target: "pino-pretty", + }, +}); +``` + +## Log Levels + +| Level | Use Case | +|:------|:---------| +| `fatal` | System is unusable | +| `error` | Error conditions | +| `warn` | Warning conditions | +| `info` | Normal operations | +| `debug` | Debug information | +| `trace` | Detailed tracing | diff --git a/packages/logger/package.json b/packages/logger/package.json new file mode 100644 index 0000000000000000000000000000000000000000..28bca3b7d5db0e60421e568e76a057fe01620463 --- /dev/null +++ b/packages/logger/package.json @@ -0,0 +1,20 @@ +{ + "name": "@engram/logger", + "version": "0.0.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "devDependencies": { + "typescript": "^5.9.3", + "@types/node": "^24.10.1", + "@engram/tsconfig": "*" + }, + "dependencies": { + "pino": "^10.1.0", + "pino-pretty": "^13.1.3" + }, + "scripts": { + "build": "echo 'Build success'", + "typecheck": "tsc --noEmit" + } +} diff --git a/packages/logger/src/browser.test.ts b/packages/logger/src/browser.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5511062d8a8a853a9eef898ef5bee79320a0a54 --- /dev/null +++ b/packages/logger/src/browser.test.ts @@ -0,0 +1,211 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// Mock pino before importing existing code +vi.mock("pino", () => { + const pinoMock = (options: any) => { + const createLogger = (opts: any) => { + return { + level: opts.level || "info", + info: (obj: any) => { + const logObj = typeof obj === "string" ? { msg: obj } : obj; + if (opts.browser?.write?.info) { + opts.browser.write.info(logObj); + } + }, + bindings: () => { + let b = opts.base || {}; + if (opts.formatters?.bindings) { + // Pass existing bindings (simulated as base) + b = opts.formatters.bindings(b); + } + return b; + }, + child: (childBindings: any) => { + // Merge bindings + const newBase = { ...opts.base, ...childBindings }; + // Return new logger with merged options + return createLogger({ ...opts, base: newBase }); + }, + debug: () => {}, + warn: () => {}, + error: () => {}, + fatal: () => {}, + trace: () => {}, + }; + }; + return createLogger(options); + }; + // Emulate default export + pinoMock.stdTimeFunctions = { isoTime: () => {} }; + return { default: pinoMock }; +}); + +// Import after mocking +import { createBrowserLogger } from "./browser"; + +describe("Browser Logger", () => { + // Mock global fetch + let mockFetch: ReturnType; + const originalFetch = global.fetch; + const originalWindow = global.window; + const originalDocument = global.document; + + beforeEach(() => { + mockFetch = vi.spyOn(global, "fetch").mockImplementation(async () => new Response("ok")); + global.window = { + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + } as any; + global.document = { + visibilityState: "visible", + } as any; + }); + + afterEach(() => { + mockFetch.mockRestore(); + global.fetch = originalFetch; + global.window = originalWindow; + global.document = originalDocument; + }); + + it("should create a logger with correct base context", () => { + const logger = createBrowserLogger({ + service: "test-browser-service", + environment: "test", + forwardToBackend: false, + }); + + expect(logger.bindings()).toMatchObject({ + service: "test-browser-service", + environment: "test", + }); + }); + + it("should buffer and flush logs", async () => { + const logger = createBrowserLogger({ + service: "test", + forwardToBackend: true, + batchSize: 2, + flushInterval: 10000, + }); + + // Log 1 - buffer + logger.info("Log 1"); + expect(mockFetch).not.toHaveBeenCalled(); + + // Log 2 - trigger batch + logger.info("Log 2"); + + // Wait a microtask for the async flush call (even though mocked logic is sync, flush is async) + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(mockFetch).toHaveBeenCalled(); + const callArgs = mockFetch.mock.calls[0]; + expect(callArgs[0]).toBe("/api/v1/logs/client"); + + const body = JSON.parse((callArgs[1] as any).body as string); + expect(body.logs).toHaveLength(2); + expect(body.logs[0].msg).toBe("Log 1"); + expect(body.logs[1].msg).toBe("Log 2"); + }); + + describe("destroy()", () => { + it("should have destroy method", () => { + const logger = createBrowserLogger({ + service: "test", + forwardToBackend: false, + }); + + expect(typeof logger.destroy).toBe("function"); + }); + + it("should flush remaining logs on destroy", async () => { + const logger = createBrowserLogger({ + service: "test", + forwardToBackend: true, + batchSize: 10, // High batch size so auto-flush doesn't trigger + flushInterval: 10000, + }); + + // Log without triggering batch + logger.info("Final log"); + + // Destroy should flush + logger.destroy(); + + // Wait for async flush + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(mockFetch).toHaveBeenCalled(); + }); + + it("should be idempotent (safe to call multiple times)", () => { + const logger = createBrowserLogger({ + service: "test", + forwardToBackend: false, + }); + + // Should not throw when called multiple times + expect(() => { + logger.destroy(); + logger.destroy(); + logger.destroy(); + }).not.toThrow(); + }); + + it("should remove event listeners on destroy", () => { + const removeEventListenerSpy = vi.fn(); + const addEventListenerSpy = vi.fn(); + + global.window = { + addEventListener: addEventListenerSpy, + removeEventListener: removeEventListenerSpy, + } as any; + + const logger = createBrowserLogger({ + service: "test", + forwardToBackend: false, + }); + + // Should have added listeners + expect(addEventListenerSpy).toHaveBeenCalledWith("beforeunload", expect.any(Function)); + expect(addEventListenerSpy).toHaveBeenCalledWith("visibilitychange", expect.any(Function)); + + // Destroy + logger.destroy(); + + // Should have removed listeners + expect(removeEventListenerSpy).toHaveBeenCalledWith("beforeunload", expect.any(Function)); + expect(removeEventListenerSpy).toHaveBeenCalledWith("visibilitychange", expect.any(Function)); + }); + + it("should not process new logs after destroy", async () => { + const logger = createBrowserLogger({ + service: "test", + forwardToBackend: true, + batchSize: 10, // High batch size so we can count logs + flushInterval: 10000, + }); + + // Log one message, then destroy + logger.info("Before destroy"); + logger.destroy(); + + // Wait for destroy's flush + await new Promise((resolve) => setTimeout(resolve, 10)); + + // Get the call count from destroy flush + const callCountAfterDestroy = mockFetch.mock.calls.length; + + // Try to log after destroy + logger.info("After destroy 1"); + logger.info("After destroy 2"); + + // Wait for any potential async operations + await new Promise((resolve) => setTimeout(resolve, 10)); + + // The call count should not have increased (destroy flag prevents further processing) + expect(mockFetch.mock.calls.length).toBe(callCountAfterDestroy); + }); + }); +}); diff --git a/packages/logger/src/browser.ts b/packages/logger/src/browser.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cab2644b62bd17b9910fb90ddd49012340a5f2d --- /dev/null +++ b/packages/logger/src/browser.ts @@ -0,0 +1,171 @@ +import pino from "pino"; +import type { BrowserLoggerOptions, Logger } from "./types"; + +/** + * Extended Logger interface with cleanup method for browser environments. + */ +export interface BrowserLogger extends Logger { + /** Clean up resources (event listeners, timers). Call before unmounting. */ + destroy: () => void; +} + +/** + * Create a Pino logger for browser environments. + * + * Features: + * - Console output with appropriate methods + * - Optional batched forwarding to backend + * - Respects log level + * - Debug only in development + * - destroy() method to clean up event listeners and timers + */ +export function createBrowserLogger(options: BrowserLoggerOptions): BrowserLogger { + const { + service, + level = typeof window !== "undefined" && process.env.NODE_ENV === "development" + ? "debug" + : "info", + environment = process.env.NODE_ENV || "development", + forwardToBackend = true, + logEndpoint = "/api/v1/logs/client", + batchSize = 10, + flushInterval = 5000, + onFlushError, + } = options; + + let logBuffer: Array> = []; + let flushTimer: ReturnType | null = null; + let destroyed = false; + + const flush = async () => { + if (logBuffer.length === 0) return; + + const logsToSend = [...logBuffer]; + logBuffer = []; + + if (!forwardToBackend) return; + + try { + const response = await fetch(logEndpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ logs: logsToSend }), + keepalive: true, + }); + + if (!response.ok) { + const error = new Error(`Log flush failed: ${response.status} ${response.statusText}`); + if (onFlushError) { + onFlushError(error, logsToSend); + } + } + } catch (e) { + // Call error callback if provided, otherwise silent (can't log about logging failures) + if (onFlushError) { + const error = e instanceof Error ? e : new Error(String(e)); + onFlushError(error, logsToSend); + } + } + }; + + const scheduleFlush = () => { + if (flushTimer) return; + flushTimer = setTimeout(() => { + flushTimer = null; + flush(); + }, flushInterval); + }; + + const addToBuffer = (logObject: Record) => { + logBuffer.push(logObject); + if (logBuffer.length >= batchSize) { + flush(); + } else { + scheduleFlush(); + } + }; + + // Custom browser transport using pino's browser option + const logger = pino({ + level, + browser: { + asObject: true, + write: { + trace: (o) => { + console.debug(o); + addToBuffer(o as Record); + }, + debug: (o) => { + console.debug(o); + addToBuffer(o as Record); + }, + info: (o) => { + console.info(o); + addToBuffer(o as Record); + }, + warn: (o) => { + console.warn(o); + addToBuffer(o as Record); + }, + error: (o) => { + console.error(o); + addToBuffer(o as Record); + }, + fatal: (o) => { + console.error(o); + addToBuffer(o as Record); + }, + }, + }, + base: { + service, + environment, + }, + }); + + // Event handlers for cleanup tracking + const handleBeforeUnload = () => { + if (!destroyed) flush(); + }; + const handleVisibilityChange = () => { + if (!destroyed && document.visibilityState === "hidden") { + flush(); + } + }; + + // Flush on page unload + if (typeof window !== "undefined") { + window.addEventListener("beforeunload", handleBeforeUnload); + window.addEventListener("visibilitychange", handleVisibilityChange); + } + + // Destroy method to clean up resources + const destroy = () => { + if (destroyed) return; + destroyed = true; + + // Clear flush timer + if (flushTimer) { + clearTimeout(flushTimer); + flushTimer = null; + } + + // Flush remaining logs + flush(); + + // Remove event listeners + if (typeof window !== "undefined") { + window.removeEventListener("beforeunload", handleBeforeUnload); + window.removeEventListener("visibilitychange", handleVisibilityChange); + } + + // Clear buffer + logBuffer = []; + }; + + // Attach destroy method to logger + const browserLogger = logger as BrowserLogger; + browserLogger.destroy = destroy; + + return browserLogger; +} diff --git a/packages/logger/src/index.test.ts b/packages/logger/src/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..10a51a21231bf0b888a6f4ea45364cbb31c6547c --- /dev/null +++ b/packages/logger/src/index.test.ts @@ -0,0 +1,231 @@ +import { describe, expect, it } from "vitest"; +import { createLogger } from "./index"; +import { childLogger, createNodeLogger, withTenantContext, withTraceContext } from "./node"; +import { DEFAULT_REDACT_PATHS, mergeRedactPaths } from "./redaction"; + +describe("Logger Package", () => { + describe("Redaction", () => { + it("should return default paths when no custom paths provided", () => { + const paths = mergeRedactPaths(); + expect(paths).toEqual(DEFAULT_REDACT_PATHS); + }); + + it("should return default paths with empty array", () => { + const paths = mergeRedactPaths([]); + expect(paths).toEqual(DEFAULT_REDACT_PATHS); + }); + + it("should merge custom paths with defaults", () => { + const customPaths = ["custom.secret"]; + const paths = mergeRedactPaths(customPaths); + expect(paths).toContain("custom.secret"); + expect(paths).toContain("req.headers.authorization"); + }); + + it("should deduplicate paths", () => { + const customPaths = ["req.headers.authorization"]; + const paths = mergeRedactPaths(customPaths); + const authPaths = paths.filter((p) => p === "req.headers.authorization"); + expect(authPaths).toHaveLength(1); + }); + + it("should handle multiple custom paths", () => { + const customPaths = ["my.secret", "another.key", "custom.token"]; + const paths = mergeRedactPaths(customPaths); + expect(paths).toContain("my.secret"); + expect(paths).toContain("another.key"); + expect(paths).toContain("custom.token"); + expect(paths.length).toBeGreaterThan(DEFAULT_REDACT_PATHS.length); + }); + }); + + describe("Node Logger", () => { + it("should create a logger with correct base context", () => { + const logger = createNodeLogger({ + service: "test-service", + environment: "test", + base: { component: "test-comp" }, + }); + + expect(logger.bindings()).toMatchObject({ + service: "test-service", + environment: "test", + component: "test-comp", + }); + }); + + it("should map log levels correctly", () => { + const logger = createNodeLogger({ service: "test" }); + expect(logger.level).toBe("info"); + }); + + it("should respect custom log level", () => { + const logger = createNodeLogger({ service: "test", level: "debug" }); + expect(logger.level).toBe("debug"); + }); + + it("should include version when provided", () => { + const logger = createNodeLogger({ + service: "test-service", + version: "1.2.3", + }); + expect(logger.bindings()).toMatchObject({ + version: "1.2.3", + }); + }); + + it("should create logger with custom redaction paths", () => { + const logger = createNodeLogger({ + service: "test", + redactPaths: ["my.custom.path"], + }); + // Logger should be created successfully with custom redaction + expect(logger).toBeDefined(); + expect(logger.level).toBe("info"); + }); + + it("should create logger with custom pino options", () => { + const logger = createNodeLogger({ + service: "test", + pinoOptions: { name: "custom-name" }, + }); + expect(logger).toBeDefined(); + }); + }); + + describe("childLogger", () => { + it("should create a child logger with component", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = childLogger(baseLogger, "MyComponent"); + + expect(child.bindings()).toMatchObject({ + component: "MyComponent", + }); + }); + + it("should create a child logger with component and extra context", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = childLogger(baseLogger, "MyComponent", { requestId: "req-123" }); + + expect(child.bindings()).toMatchObject({ + component: "MyComponent", + requestId: "req-123", + }); + }); + + it("should preserve parent bindings in child", () => { + const baseLogger = createNodeLogger({ service: "parent-service" }); + const child = childLogger(baseLogger, "ChildComponent"); + + expect(child.bindings()).toMatchObject({ + service: "parent-service", + component: "ChildComponent", + }); + }); + }); + + describe("Context Helpers", () => { + it("should add trace context with all fields", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = withTraceContext(baseLogger, { + correlationId: "corr-001", + traceId: "trace-123", + spanId: "span-456", + requestId: "req-789", + }); + + expect(child.bindings()).toMatchObject({ + correlation_id: "corr-001", + trace_id: "trace-123", + span_id: "span-456", + request_id: "req-789", + }); + }); + + it("should add trace context with partial fields", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = withTraceContext(baseLogger, { + traceId: "trace-123", + }); + + expect(child.bindings()).toMatchObject({ + trace_id: "trace-123", + }); + // Should not include undefined fields + expect(child.bindings().span_id).toBeUndefined(); + }); + + it("should add tenant context with all fields", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = withTenantContext(baseLogger, { + tenantId: "tenant-abc", + campaignId: "camp-xyz", + adminUserId: "admin-001", + externalUserId: "ext-user-002", + }); + + expect(child.bindings()).toMatchObject({ + tenant_id: "tenant-abc", + campaign_id: "camp-xyz", + admin_user_id: "admin-001", + external_user_id: "ext-user-002", + }); + }); + + it("should add tenant context with partial fields", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = withTenantContext(baseLogger, { + tenantId: "tenant-abc", + }); + + expect(child.bindings()).toMatchObject({ + tenant_id: "tenant-abc", + }); + // Should not include undefined fields + expect(child.bindings().campaign_id).toBeUndefined(); + }); + + it("should handle empty trace context", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = withTraceContext(baseLogger, {}); + + // Should still create child logger without errors + expect(child).toBeDefined(); + }); + + it("should handle empty tenant context", () => { + const baseLogger = createNodeLogger({ service: "test" }); + const child = withTenantContext(baseLogger, {}); + + // Should still create child logger without errors + expect(child).toBeDefined(); + }); + }); + + describe("Legacy createLogger", () => { + it("should create a logger with default options", () => { + const logger = createLogger(); + expect(logger).toBeDefined(); + expect(logger.level).toBe("info"); + }); + + it("should create a logger with custom level", () => { + const logger = createLogger({ level: "debug" }); + expect(logger.level).toBe("debug"); + }); + + it("should create a logger with component", () => { + const logger = createLogger({ component: "TestComponent" }); + expect(logger.bindings()).toMatchObject({ + component: "TestComponent", + }); + }); + + it("should use engram-system as default service", () => { + const logger = createLogger(); + expect(logger.bindings()).toMatchObject({ + service: "engram-system", + }); + }); + }); +}); diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2492dfcbeff22f4a07ed450633b2097c9c02f792 --- /dev/null +++ b/packages/logger/src/index.ts @@ -0,0 +1,29 @@ +// Main exports for the logging package + +import pino from "pino"; + +export { createBrowserLogger } from "./browser"; +export { childLogger, createNodeLogger, withTenantContext, withTraceContext } from "./node"; +export * from "./redaction"; +export * from "./types"; +export { pino }; + +// Re-export legacy createLogger for backward compatibility during refactor (mapped to createNodeLogger) +import { createNodeLogger } from "./node"; +import type { LogLevel } from "./types"; + +// Shim for legacy LoggerOptions to new NodeLoggerOptions +export interface LegacyLoggerOptions { + level?: string; + component?: string; +} + +export type LoggerOptions = LegacyLoggerOptions; + +export const createLogger = (options: LegacyLoggerOptions = {}) => { + return createNodeLogger({ + service: "engram-system", // Default service name + level: (options.level as LogLevel | undefined) ?? "info", + base: { component: options.component }, + }); +}; diff --git a/packages/logger/src/node.ts b/packages/logger/src/node.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ccfbd8cbfbcd2efa0b80d486e19ea7ec72a791c --- /dev/null +++ b/packages/logger/src/node.ts @@ -0,0 +1,133 @@ +import pino, { type DestinationStream } from "pino"; +import { mergeRedactPaths } from "./redaction"; +import type { Logger, NodeLoggerOptions, TenantContext, TraceContext } from "./types"; + +/** + * Create a Pino logger for Node.js/Bun environments. + * + * Features: + * - Uppercase severity levels for Cloud Logging compatibility + * - ISO timestamps + * - PII redaction via Pino's built-in redaction + * - Pretty printing in development + * - Structured JSON in production + */ +export function createNodeLogger( + options: NodeLoggerOptions, + destination?: DestinationStream, +): Logger { + const { + service, + level = "info", + environment = process.env.NODE_ENV || "development", + version = process.env.npm_package_version, + pretty = environment === "development", + redactPaths, + base = {}, + pinoOptions = {}, + } = options; + + const transport = pretty + ? { + target: "pino-pretty", + options: { + colorize: true, + translateTime: "SYS:standard", + ignore: "pid,hostname", + levelFirst: true, + messageFormat: "{component} - {msg}", + }, + } + : undefined; + + const logger = pino( + { + level, + // Custom level labels for Cloud Logging compatibility + formatters: { + level(label) { + // Map to Cloud Logging severity + const severityMap: Record = { + trace: "DEBUG", + debug: "DEBUG", + info: "INFO", + warn: "WARNING", + error: "ERROR", + fatal: "CRITICAL", + }; + return { severity: severityMap[label] || label.toUpperCase() }; + }, + bindings(bindings) { + // Remove default pid/hostname, add our base context + const { pid: _pid, hostname: _hostname, ...rest } = bindings; + return { + service, + environment, + ...(version && { version }), + ...base, + ...rest, + }; + }, + }, + // ISO timestamp for Cloud Logging + timestamp: pino.stdTimeFunctions.isoTime, + // Redaction for PII + redact: { + paths: mergeRedactPaths(redactPaths) as string[], + censor: "[REDACTED]", + }, + // Transport for pretty printing in dev + ...(transport && { transport }), + // Merge any custom options + ...pinoOptions, + }, + destination, + ); + + return logger; +} + +/** + * Create a child logger with additional context. + * + * @param logger - Parent logger + * @param component - Component name + * @param context - Additional context + */ +export function childLogger( + logger: Logger, + component: string, + context?: Record, +): Logger { + return logger.child({ component, ...context }); +} + +/** + * Create a child logger with trace context. + * + * @param logger - Parent logger + * @param trace - Trace context from request + */ +export function withTraceContext(logger: Logger, trace: TraceContext): Logger { + return logger.child({ + ...(trace.correlationId && { correlation_id: trace.correlationId }), + ...(trace.traceId && { trace_id: trace.traceId }), + ...(trace.spanId && { span_id: trace.spanId }), + ...(trace.requestId && { request_id: trace.requestId }), + }); +} + +/** + * Create a child logger with tenant context. + * + * @param logger - Parent logger + * @param tenant - Tenant context + */ +export function withTenantContext(logger: Logger, tenant: TenantContext): Logger { + return logger.child({ + ...(tenant.tenantId && { tenant_id: tenant.tenantId }), + ...(tenant.campaignId && { campaign_id: tenant.campaignId }), + ...(tenant.adminUserId && { admin_user_id: tenant.adminUserId }), + ...(tenant.externalUserId && { external_user_id: tenant.externalUserId }), + }); +} diff --git a/packages/logger/src/redaction.ts b/packages/logger/src/redaction.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a81c4449e4f5027d50d289d64b1497c1363070b --- /dev/null +++ b/packages/logger/src/redaction.ts @@ -0,0 +1,55 @@ +/** + * Pino Redaction Configuration + * + * Paths to redact sensitive data from logs. + * Uses Pino's built-in redaction which is more performant than manual scrubbing. + */ + +export const DEFAULT_REDACT_PATHS = [ + // Request headers + "req.headers.authorization", + "req.headers.cookie", + "req.headers['x-api-key']", + + // Request body sensitive fields + "req.body.password", + "req.body.token", + "req.body.refreshToken", + "req.body.refresh_token", + "req.body.accessToken", + "req.body.access_token", + "req.body.apiKey", + "req.body.api_key", + "req.body.secret", + "req.body.credential", + "req.body.credentials", + + // Auth objects + "auth.*", + "identity.token", + "identity.refreshToken", + "secrets.*", + + // User PII + "*.email", + "*.phone", + "*.ssn", + "*.creditCard", + "*.cardNumber", + "user.password", + + // Response sensitive fields + "res.headers['set-cookie']", +] as const; + +export type RedactPath = (typeof DEFAULT_REDACT_PATHS)[number]; + +/** + * Merge custom redaction paths with defaults + */ +export function mergeRedactPaths(customPaths?: readonly string[]): readonly string[] { + if (!customPaths?.length) { + return DEFAULT_REDACT_PATHS; + } + return [...new Set([...DEFAULT_REDACT_PATHS, ...customPaths])]; +} diff --git a/packages/logger/src/types.ts b/packages/logger/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..9fd225fac5a7920eefd5a5d56c7b30a191cd4409 --- /dev/null +++ b/packages/logger/src/types.ts @@ -0,0 +1,65 @@ +import type { Logger as PinoLogger, LoggerOptions as PinoOptions } from "pino"; + +export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal"; + +export interface BaseLogContext { + service?: string; + component?: string; + environment?: string; + version?: string; + instanceId?: string; +} + +export interface TraceContext { + correlationId?: string; + traceId?: string; + spanId?: string; + requestId?: string; +} + +export interface TenantContext { + tenantId?: string; + campaignId?: string; + adminUserId?: string; + externalUserId?: string; +} + +export interface NodeLoggerOptions { + /** Service name for all logs */ + service: string; + /** Log level (default: 'info') */ + level?: LogLevel; + /** Environment name */ + environment?: string; + /** Service version */ + version?: string; + /** Enable pretty printing (default: based on NODE_ENV) */ + pretty?: boolean; + /** Additional redaction paths */ + redactPaths?: readonly string[]; + /** Base context to include in all logs */ + base?: Record; + /** Custom Pino options */ + pinoOptions?: Partial; +} + +export interface BrowserLoggerOptions { + /** Service name for all logs */ + service: string; + /** Log level (default: 'info' in prod, 'debug' in dev) */ + level?: LogLevel; + /** Environment name */ + environment?: string; + /** Whether to forward logs to backend (default: true) */ + forwardToBackend?: boolean; + /** Backend log endpoint */ + logEndpoint?: string; + /** Batch size before sending (default: 10) */ + batchSize?: number; + /** Flush interval in ms (default: 5000) */ + flushInterval?: number; + /** Error callback for flush failures (default: silent) */ + onFlushError?: (error: Error, failedLogs: Array>) => void; +} + +export type Logger = PinoLogger; diff --git a/packages/logger/tsconfig.json b/packages/logger/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..641a81dc7930b9224a4c9e017be08450bf43e9f0 --- /dev/null +++ b/packages/logger/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@engram/tsconfig/base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "baseUrl": "." + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/search/README.md b/packages/search/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cb512b8e1ae19503a8041bd92379d832b935956f --- /dev/null +++ b/packages/search/README.md @@ -0,0 +1,115 @@ +# @engram/search + +Full semantic search stack with embeddings, reranking, and retrieval. + +## Overview + +Comprehensive search engine with multi-stage retrieval, hybrid search (dense + sparse via SPLADE), caching, and performance optimization. Integrates with Qdrant for vector storage. + +## Installation + +```bash +npm install @engram/search +``` + +## Core Components + +### Embedders + +```typescript +import { + TextEmbedder, + CodeEmbedder, + ColbertEmbedder, + SpladeEmbedder, +} from "@engram/search"; + +const embedder = new TextEmbedder({ model: "e5-small" }); +const embedding = await embedder.embed("query text"); +``` + +### Retrieval + +```typescript +import { SearchRetriever, SessionRetriever } from "@engram/search"; + +const retriever = new SearchRetriever({ + qdrantUrl: "http://localhost:6333", + collection: "engram", +}); + +const results = await retriever.search({ + query: "how to implement auth", + topK: 10, +}); +``` + +### Reranking + +```typescript +import { Reranker, RerankerRouter } from "@engram/search"; + +const reranker = new Reranker({ tier: "accurate" }); +const reranked = await reranker.rerank(query, documents); + +// Or use the router for automatic tier selection +const router = new RerankerRouter(); +const results = await router.rerank(query, documents, { tier: "auto" }); +``` + +### Hybrid Search + +```typescript +import { MultiQueryRetriever, LearnedFusion } from "@engram/search"; + +// Multi-query with fusion +const retriever = new MultiQueryRetriever({ + dense: denseRetriever, + sparse: sparseRetriever, + fusion: new LearnedFusion(), +}); +``` + +## Reranker Tiers + +| Tier | Model | Latency | Use Case | +|:-----|:------|:--------|:---------| +| `fast` | MiniLM-L-6-v2 | ~50ms | Quick lookups | +| `accurate` | BGE-reranker-base | ~150ms | Complex queries | +| `code` | Jina-reranker-v2 | ~150ms | Code search | +| `colbert` | ColBERT-v2 | ~200ms | Token-level matching | + +## Caching + +```typescript +import { QueryCache, EmbeddingCache } from "@engram/search"; + +const queryCache = new QueryCache({ ttl: 3600 }); +const embeddingCache = new EmbeddingCache({ maxSize: 10000 }); +``` + +## Analysis & Metrics + +```typescript +import { QueryClassifier, RerankMetrics, CacheMetrics } from "@engram/search"; + +const classifier = new QueryClassifier(); +const features = classifier.classify(query); +// { isCode: true, hasTemporal: false, complexity: "medium" } +``` + +## Configuration + +```typescript +import { SearchConfig } from "@engram/search"; + +const config: SearchConfig = { + qdrantUrl: "http://localhost:6333", + collection: "engram", + embeddingModel: "e5-small", + hybridSearch: true, + rerank: true, + rerankTier: "accurate", + rerankDepth: 30, +}; +``` diff --git a/packages/search/package.json b/packages/search/package.json new file mode 100644 index 0000000000000000000000000000000000000000..098383bf4f14098b48a53835da93086487a5e182 --- /dev/null +++ b/packages/search/package.json @@ -0,0 +1,29 @@ +{ + "name": "@engram/search", + "version": "0.0.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "devDependencies": { + "@engram/tsconfig": "*", + "@types/node": "^24.10.1", + "typescript": "^5.9.3" + }, + "dependencies": { + "@ai-sdk/google": "^1.2.18", + "@engram/common": "*", + "@engram/logger": "*", + "@huggingface/transformers": "^3.8.1", + "@qdrant/js-client-rest": "^1.16.2", + "ai": "^4.3.16", + "chrono-node": "^2.9.0", + "ioredis": "^5.8.2", + "p-queue": "^8.0.1", + "prom-client": "^15.1.3", + "zod": "^4.1.13" + }, + "scripts": { + "build": "echo 'Build success'", + "typecheck": "tsc --noEmit" + } +} diff --git a/packages/search/scripts/evaluate-reranker.ts b/packages/search/scripts/evaluate-reranker.ts new file mode 100644 index 0000000000000000000000000000000000000000..53a0977f053fcc6f225e79a2151c2cc8145cc61b --- /dev/null +++ b/packages/search/scripts/evaluate-reranker.ts @@ -0,0 +1,356 @@ +#!/usr/bin/env bun + +/** + * Quality evaluation script for reranker. + * + * This script computes standard information retrieval metrics: + * - NDCG@k (Normalized Discounted Cumulative Gain) + * - MRR (Mean Reciprocal Rank) + * + * Usage: + * bun run packages/search-core/scripts/evaluate-reranker.ts + * + * The script uses test queries with known relevance judgments to evaluate + * the reranker's quality. It compares results with and without reranking. + */ + +import type { RerankerTier } from "../src/models/schema"; +import { BatchedReranker, type DocumentCandidate } from "../src/services/batched-reranker"; + +// ============================================================================= +// Test Data +// ============================================================================= + +interface RelevanceJudgment { + query: string; + /** Document IDs ordered by relevance (most relevant first) */ + relevant_docs: string[]; + /** Document content */ + documents: Record; +} + +/** + * Test dataset with known relevance judgments. + * Each query has a list of relevant documents in order of relevance. + */ +const TEST_QUERIES: RelevanceJudgment[] = [ + { + query: "What is machine learning?", + relevant_docs: ["ml1", "ml2", "ml3", "ai1"], + documents: { + ml1: "Machine learning is a subset of artificial intelligence that enables systems to learn from data without being explicitly programmed.", + ml2: "Machine learning algorithms use statistical techniques to give computers the ability to learn and improve from experience.", + ml3: "Machine learning models are trained on data to make predictions or decisions without being explicitly programmed for the task.", + ai1: "Artificial intelligence is a broad field that encompasses machine learning, natural language processing, and computer vision.", + weather1: "The weather today is sunny with a high of 75 degrees.", + food1: "Pizza is a popular Italian dish made with dough, sauce, and cheese.", + sports1: "Basketball is a team sport played on a court with a hoop at each end.", + }, + }, + { + query: "neural networks deep learning", + relevant_docs: ["nn1", "nn2", "dl1", "ml1"], + documents: { + nn1: "Neural networks are computational models inspired by biological neural systems, consisting of interconnected nodes that process information.", + nn2: "Artificial neural networks use layers of neurons to learn patterns in data through backpropagation and gradient descent.", + dl1: "Deep learning uses neural networks with multiple hidden layers to learn hierarchical representations of data.", + ml1: "Machine learning is the foundation for deep learning and neural network architectures.", + stats1: + "Statistical analysis involves collecting, organizing, and interpreting data to find patterns.", + bio1: "The human brain contains billions of neurons connected by synapses.", + history1: "World War II was a global conflict that lasted from 1939 to 1945.", + }, + }, + { + query: "How do transformers work in NLP?", + relevant_docs: ["trans1", "trans2", "attn1", "nlp1"], + documents: { + trans1: + "Transformers are neural network architectures that use self-attention mechanisms to process sequential data in parallel.", + trans2: + "The Transformer architecture revolutionized NLP by replacing recurrent layers with multi-head attention.", + attn1: + "Self-attention allows the model to weigh the importance of different words in a sequence when processing each word.", + nlp1: "Natural language processing uses machine learning to understand and generate human language.", + rnn1: "Recurrent neural networks process sequences one element at a time, maintaining hidden state.", + cv1: "Computer vision uses neural networks to analyze and understand images.", + music1: "Music theory encompasses the study of harmony, melody, and rhythm.", + }, + }, + { + query: "function to sort array in Python", + relevant_docs: ["py1", "py2", "algo1"], + documents: { + py1: "In Python, you can sort a list using the sorted() function or the list.sort() method.", + py2: "my_list.sort() sorts the list in-place, while sorted(my_list) returns a new sorted list.", + algo1: + "Common sorting algorithms include quicksort, mergesort, and heapsort with different time complexities.", + js1: "In JavaScript, use array.sort() to sort an array in place.", + java1: "Java provides Arrays.sort() and Collections.sort() for sorting arrays and lists.", + ml1: "Machine learning models can be trained to predict sorted orders from data.", + book1: "The Lord of the Rings is a fantasy novel by J.R.R. Tolkien.", + }, + }, +]; + +// ============================================================================= +// Metrics +// ============================================================================= + +/** + * Compute Discounted Cumulative Gain at k. + * + * DCG@k = sum_{i=1}^{k} (rel_i / log2(i + 1)) + * + * where rel_i is the relevance of the document at position i. + * For binary relevance: rel_i = 1 if relevant, 0 otherwise. + * For graded relevance: rel_i = position in relevant_docs (inverted). + */ +function computeDCG(ranked: string[], relevant: string[], k: number): number { + let dcg = 0; + + for (let i = 0; i < Math.min(k, ranked.length); i++) { + const docId = ranked[i]; + const relevanceIdx = relevant.indexOf(docId); + + // Graded relevance: most relevant doc gets highest score + const relevance = relevanceIdx === -1 ? 0 : relevant.length - relevanceIdx; + + // Logarithmic discount (i+2 because i is 0-indexed and we use log2(i+1)) + dcg += relevance / Math.log2(i + 2); + } + + return dcg; +} + +/** + * Compute Normalized Discounted Cumulative Gain at k. + * + * NDCG@k = DCG@k / IDCG@k + * + * where IDCG@k is the ideal DCG (DCG of the perfect ranking). + */ +function computeNDCG(ranked: string[], relevant: string[], k: number): number { + const dcg = computeDCG(ranked, relevant, k); + const idcg = computeDCG(relevant, relevant, k); // Perfect ranking + + if (idcg === 0) { + return 0; // No relevant documents + } + + return dcg / idcg; +} + +/** + * Compute Mean Reciprocal Rank. + * + * MRR = 1 / rank_of_first_relevant_doc + * + * Returns 0 if no relevant document is found. + */ +function computeMRR(ranked: string[], relevant: string[]): number { + for (let i = 0; i < ranked.length; i++) { + if (relevant.includes(ranked[i])) { + return 1 / (i + 1); // i+1 because ranks start at 1 + } + } + return 0; // No relevant document found +} + +/** + * Compute Precision at k. + * + * P@k = (number of relevant docs in top k) / k + */ +function computePrecisionAtK(ranked: string[], relevant: string[], k: number): number { + const topK = ranked.slice(0, k); + const relevantInTopK = topK.filter((id) => relevant.includes(id)).length; + return relevantInTopK / k; +} + +/** + * Compute Recall at k. + * + * R@k = (number of relevant docs in top k) / (total relevant docs) + */ +function computeRecallAtK(ranked: string[], relevant: string[], k: number): number { + if (relevant.length === 0) { + return 0; + } + + const topK = ranked.slice(0, k); + const relevantInTopK = topK.filter((id) => relevant.includes(id)).length; + return relevantInTopK / relevant.length; +} + +// ============================================================================= +// Evaluation +// ============================================================================= + +interface EvaluationResult { + tier: RerankerTier; + ndcg_at_3: number; + ndcg_at_5: number; + ndcg_at_10: number; + mrr: number; + precision_at_3: number; + recall_at_3: number; + precision_at_5: number; + recall_at_5: number; +} + +/** + * Evaluate a reranker tier on the test queries. + */ +async function evaluateTier(tier: RerankerTier): Promise { + const reranker = BatchedReranker.forTier(tier); + + // Warm up the model + console.log(`[${tier}] Loading model...`); + await reranker.warmup(); + console.log(`[${tier}] Model loaded.`); + + const metrics = { + ndcg_at_3: [] as number[], + ndcg_at_5: [] as number[], + ndcg_at_10: [] as number[], + mrr: [] as number[], + precision_at_3: [] as number[], + recall_at_3: [] as number[], + precision_at_5: [] as number[], + recall_at_5: [] as number[], + }; + + for (const testCase of TEST_QUERIES) { + const { query, relevant_docs, documents } = testCase; + + // Create candidates from all documents + const candidates: DocumentCandidate[] = Object.entries(documents).map(([id, content]) => ({ + id, + content, + score: Math.random(), // Random initial scores + })); + + // Shuffle to avoid positional bias + candidates.sort(() => Math.random() - 0.5); + + // Rerank + const results = await reranker.rerank(query, candidates, 10); + + // Extract ranked doc IDs + const rankedIds = results.map((r) => String(r.id)); + + // Compute metrics + metrics.ndcg_at_3.push(computeNDCG(rankedIds, relevant_docs, 3)); + metrics.ndcg_at_5.push(computeNDCG(rankedIds, relevant_docs, 5)); + metrics.ndcg_at_10.push(computeNDCG(rankedIds, relevant_docs, 10)); + metrics.mrr.push(computeMRR(rankedIds, relevant_docs)); + metrics.precision_at_3.push(computePrecisionAtK(rankedIds, relevant_docs, 3)); + metrics.recall_at_3.push(computeRecallAtK(rankedIds, relevant_docs, 3)); + metrics.precision_at_5.push(computePrecisionAtK(rankedIds, relevant_docs, 5)); + metrics.recall_at_5.push(computeRecallAtK(rankedIds, relevant_docs, 5)); + + console.log( + `[${tier}] Query: "${query.slice(0, 40)}..." | NDCG@5: ${metrics.ndcg_at_5[metrics.ndcg_at_5.length - 1].toFixed(3)} | MRR: ${metrics.mrr[metrics.mrr.length - 1].toFixed(3)}`, + ); + } + + // Average metrics + const avg = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length; + + return { + tier, + ndcg_at_3: avg(metrics.ndcg_at_3), + ndcg_at_5: avg(metrics.ndcg_at_5), + ndcg_at_10: avg(metrics.ndcg_at_10), + mrr: avg(metrics.mrr), + precision_at_3: avg(metrics.precision_at_3), + recall_at_3: avg(metrics.recall_at_3), + precision_at_5: avg(metrics.precision_at_5), + recall_at_5: avg(metrics.recall_at_5), + }; +} + +/** + * Print evaluation results in a formatted table. + */ +function printResults(results: EvaluationResult[]): void { + console.log(`\n${"=".repeat(80)}`); + console.log("RERANKER QUALITY EVALUATION RESULTS"); + console.log("=".repeat(80)); + console.log(); + + // Header + console.log( + `${"Tier".padEnd(12)} | ${"NDCG@3".padEnd(8)} | ${"NDCG@5".padEnd(8)} | ${"NDCG@10".padEnd(8)} | ${"MRR".padEnd(8)} | ${"P@3".padEnd(8)} | ${"R@3".padEnd(8)} | ${"P@5".padEnd(8)} | ${"R@5".padEnd(8)}`, + ); + console.log("-".repeat(120)); + + // Results + for (const result of results) { + console.log( + `${result.tier.padEnd(12)} | ${result.ndcg_at_3.toFixed(4).padEnd(8)} | ${result.ndcg_at_5.toFixed(4).padEnd(8)} | ${result.ndcg_at_10.toFixed(4).padEnd(8)} | ${result.mrr.toFixed(4).padEnd(8)} | ${result.precision_at_3.toFixed(4).padEnd(8)} | ${result.recall_at_3.toFixed(4).padEnd(8)} | ${result.precision_at_5.toFixed(4).padEnd(8)} | ${result.recall_at_5.toFixed(4).padEnd(8)}`, + ); + } + + console.log(); + console.log("=".repeat(80)); + console.log("Legend:"); + console.log(" NDCG@k: Normalized Discounted Cumulative Gain at k (higher is better)"); + console.log(" MRR: Mean Reciprocal Rank (higher is better)"); + console.log(" P@k: Precision at k (higher is better)"); + console.log(" R@k: Recall at k (higher is better)"); + console.log("=".repeat(80)); +} + +// ============================================================================= +// Main +// ============================================================================= + +async function main(): Promise { + console.log("Starting reranker quality evaluation...\n"); + + const tiers: RerankerTier[] = ["fast", "accurate", "code"]; + const results: EvaluationResult[] = []; + + for (const tier of tiers) { + console.log(`\nEvaluating tier: ${tier}`); + console.log("-".repeat(80)); + + try { + const result = await evaluateTier(tier); + results.push(result); + } catch (error) { + console.error(`[${tier}] Evaluation failed:`, error); + } + } + + // Print results + printResults(results); + + // Find best tier for each metric + console.log("\nBest performing tier by metric:"); + const metrics: (keyof Omit)[] = [ + "ndcg_at_5", + "mrr", + "precision_at_5", + "recall_at_5", + ]; + + for (const metric of metrics) { + const best = results.reduce((prev, current) => + current[metric] > prev[metric] ? current : prev, + ); + console.log(` ${metric}: ${best.tier} (${best[metric].toFixed(4)})`); + } + + console.log("\nEvaluation complete!"); +} + +// Run if executed directly +if (import.meta.main) { + main().catch(console.error); +} + +// Export for testing +export { computeNDCG, computeMRR, computePrecisionAtK, computeRecallAtK }; diff --git a/packages/search/src/clients/index.ts b/packages/search/src/clients/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e39c603b7a07284f8004286a0a1408eca7bbb096 --- /dev/null +++ b/packages/search/src/clients/index.ts @@ -0,0 +1 @@ +// Re-exports for client utilities (xai-client replaced by @ai-sdk/xai) diff --git a/packages/search/src/config.ts b/packages/search/src/config.ts new file mode 100644 index 0000000000000000000000000000000000000000..65a93a44f746d6d5a4cc95e604e01026008b27f3 --- /dev/null +++ b/packages/search/src/config.ts @@ -0,0 +1,10 @@ +/** + * Re-export all configuration from the consolidated config module. + * + * @deprecated Import directly from '@engram/search/config' instead. + * This file exists for backward compatibility with existing imports. + * + * @module @engram/search + */ + +export * from "./config/index"; diff --git a/packages/search/src/config/env.test.ts b/packages/search/src/config/env.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ffb903838e8aeb1cec5c84d3777d84855cb919f --- /dev/null +++ b/packages/search/src/config/env.test.ts @@ -0,0 +1,127 @@ +import { envBool, envNum, envStr } from "@engram/common"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { DEFAULT_TIER_CONFIGS, rerankerConfig } from "./index"; + +/** + * Tests for environment variable handling in search-core config. + * + * Note: The env helper functions (envBool, envNum, envStr) are now provided + * by @engram/common. These tests verify the integration with the reranker config. + */ +describe("env", () => { + // Store original env + const originalEnv = { ...process.env }; + + beforeEach(() => { + // Clear relevant env vars before each test + delete process.env.RERANKER_ENABLED; + delete process.env.RERANKER_DEFAULT_TIER; + delete process.env.RERANKER_TIMEOUT_MS; + delete process.env.RERANKER_FAST_MODEL; + delete process.env.RERANKER_CACHE_ENABLED; + delete process.env.RERANKER_AB_ROLLOUT; + delete process.env.XAI_API_KEY; + }); + + afterEach(() => { + // Restore original env + process.env = { ...originalEnv }; + }); + + describe("envBool from @engram/common", () => { + test("should return default when env var not set", () => { + expect(envBool("NONEXISTENT_VAR", true)).toBe(true); + expect(envBool("NONEXISTENT_VAR", false)).toBe(false); + }); + + test("should parse 'true' as true", () => { + process.env.TEST_BOOL = "true"; + expect(envBool("TEST_BOOL", false)).toBe(true); + }); + + test("should parse 'TRUE' as true (case insensitive)", () => { + process.env.TEST_BOOL = "TRUE"; + expect(envBool("TEST_BOOL", false)).toBe(true); + }); + + test("should parse '1' as true", () => { + process.env.TEST_BOOL = "1"; + expect(envBool("TEST_BOOL", false)).toBe(true); + }); + + test("should parse 'false' as false", () => { + process.env.TEST_BOOL = "false"; + expect(envBool("TEST_BOOL", true)).toBe(false); + }); + + test("should parse '0' as false", () => { + process.env.TEST_BOOL = "0"; + expect(envBool("TEST_BOOL", true)).toBe(false); + }); + }); + + describe("envNum from @engram/common", () => { + test("should return default when env var not set", () => { + expect(envNum("NONEXISTENT_VAR", 42)).toBe(42); + }); + + test("should parse valid integer", () => { + process.env.TEST_NUM = "123"; + expect(envNum("TEST_NUM", 0)).toBe(123); + }); + + test("should parse negative integer", () => { + process.env.TEST_NUM = "-456"; + expect(envNum("TEST_NUM", 0)).toBe(-456); + }); + + test("should return default for invalid number", () => { + process.env.TEST_NUM = "not_a_number"; + expect(envNum("TEST_NUM", 42)).toBe(42); + }); + + test("should return default for empty string", () => { + process.env.TEST_NUM = ""; + expect(envNum("TEST_NUM", 42)).toBe(42); + }); + }); + + describe("envStr from @engram/common", () => { + test("should return default when env var not set", () => { + expect(envStr("NONEXISTENT_VAR", "default")).toBe("default"); + }); + + test("should return env var value when set", () => { + process.env.TEST_STR = "hello world"; + expect(envStr("TEST_STR", "default")).toBe("hello world"); + }); + + test("should return empty string if env var is empty", () => { + process.env.TEST_STR = ""; + expect(envStr("TEST_STR", "default")).toBe(""); + }); + }); + + describe("rerankerConfig defaults", () => { + test("should have default values when no env vars set", () => { + // These test the defaults in the consolidated config + expect(rerankerConfig.enabled).toBe(true); + expect(rerankerConfig.defaultTier).toBe("fast"); + expect(rerankerConfig.timeoutMs).toBe(500); + }); + + test("should have valid tier configs", () => { + expect(rerankerConfig.tiers.fast.model).toBe(DEFAULT_TIER_CONFIGS.fast.model); + expect(rerankerConfig.tiers.accurate.model).toBe(DEFAULT_TIER_CONFIGS.accurate.model); + expect(rerankerConfig.tiers.code.model).toBe(DEFAULT_TIER_CONFIGS.code.model); + expect(rerankerConfig.tiers.llm.model).toBe(DEFAULT_TIER_CONFIGS.llm.model); + }); + + test("should preserve regex patterns in routing config", () => { + expect(rerankerConfig.routing.codePatterns).toBeInstanceOf(Array); + expect(rerankerConfig.routing.codePatterns[0]).toBeInstanceOf(RegExp); + expect(rerankerConfig.routing.agenticPatterns).toBeInstanceOf(Array); + expect(rerankerConfig.routing.agenticPatterns[0]).toBeInstanceOf(RegExp); + }); + }); +}); diff --git a/packages/search/src/config/index.ts b/packages/search/src/config/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..25fa4da7032ae3310b905a56d8440d1aaad1f28c --- /dev/null +++ b/packages/search/src/config/index.ts @@ -0,0 +1,329 @@ +/** + * Consolidated configuration for the Engram search-core package. + * + * This module provides comprehensive configuration management including: + * - Type-safe configuration interfaces + * - Environment variable loading with helpers from @engram/common + * - Runtime configuration updates with hot reload + * - Schema validation using Zod + * - Business logic validation + * + * Example usage: + * ```ts + * import { searchConfig, rerankerConfig, RuntimeConfig } from '@engram/search/config'; + * + * // Access static configuration + * const limit = searchConfig.retrieval.defaultLimit; + * const tier = rerankerConfig.defaultTier; + * + * // Get runtime configuration + * const config = RuntimeConfig.get(); + * + * // Update configuration at runtime + * RuntimeConfig.update({ defaultTier: 'accurate' }); + * + * // Watch for configuration changes + * const unwatch = RuntimeConfig.watch((newConfig) => { + * console.log('Config updated:', newConfig); + * }); + * ``` + * + * @module @engram/search/config + */ + +import { envBool, envFloat, envNum, envStr } from "@engram/common"; +import type { RerankerTier } from "../models/schema"; + +// ============================================================================= +// Search Configuration +// ============================================================================= + +/** + * Core search configuration with score thresholds and limits. + * Uses environment variables with sensible defaults. + */ +export const searchConfig = { + /** Minimum score thresholds by search strategy */ + minScore: { + // Tuned for e5-small (cosine similarity) + // e5-small scores are usually between 0.7 and 0.9 for relevant items. + // < 0.75 is often irrelevant noise. + dense: envFloat("SEARCH_MIN_SCORE_DENSE", 0.75), + + // Sparse (BM25/SPLADE) scores are unbounded but usually normalized or relative. + // For Qdrant sparse, it depends on payload. + sparse: envFloat("SEARCH_MIN_SCORE_SPARSE", 0.1), + + // RRF/Hybrid fusion score (0-1 usually) + hybrid: envFloat("SEARCH_MIN_SCORE_HYBRID", 0.5), + }, + + /** Result limits */ + limits: { + maxResults: envNum("SEARCH_MAX_RESULTS", 100), + defaultResults: envNum("SEARCH_DEFAULT_RESULTS", 10), + }, + + /** Retrieval settings */ + retrieval: { + defaultLimit: envNum("RETRIEVAL_DEFAULT_LIMIT", 10), + maxLimit: envNum("RETRIEVAL_MAX_LIMIT", 100), + scoreThreshold: envFloat("RETRIEVAL_SCORE_THRESHOLD", 0.7), + }, + + /** Cache settings */ + cache: { + enabled: envBool("SEARCH_CACHE_ENABLED", true), + ttlSeconds: envNum("SEARCH_CACHE_TTL", 300), + }, +} as const; + +export type SearchConfig = typeof searchConfig; +export type SearchMinScoreConfig = typeof searchConfig.minScore; +export type SearchLimitsConfig = typeof searchConfig.limits; +export type RetrievalConfig = typeof searchConfig.retrieval; +export type SearchCacheConfig = typeof searchConfig.cache; + +// Backward compatibility exports +export const DEFAULT_SEARCH_CONFIG = searchConfig; + +// ============================================================================= +// Reranker Configuration Types +// ============================================================================= + +/** + * Tier-specific configuration for a reranker model. + */ +export interface TierConfig { + /** Model identifier (Hugging Face model ID or API model name) */ + model: string; + /** Maximum latency in milliseconds for this tier */ + maxLatencyMs: number; + /** Batch size for processing (local models only) */ + batchSize: number; + /** Maximum number of candidates to rerank in this tier */ + maxCandidates: number; + /** Whether this tier is enabled */ + enabled: boolean; +} + +/** + * Query routing heuristics configuration. + */ +export interface RoutingConfig { + /** Regex patterns that indicate code queries */ + codePatterns: RegExp[]; + /** Character count threshold for "complex" queries */ + complexThreshold: number; + /** Regex patterns that indicate agentic/tool queries */ + agenticPatterns: RegExp[]; + /** Weight for code pattern matching (0-1) */ + codePatternWeight: number; + /** Default latency budget in milliseconds */ + latencyBudgetDefault: number; +} + +/** + * Caching configuration for reranker system. + */ +export interface RerankerCacheConfig { + /** TTL for query result cache in seconds */ + queryResultTTL: number; + /** TTL for document representation cache in seconds */ + documentRepresentationTTL: number; + /** Maximum cache size in bytes */ + maxCacheSize: number; + /** Maximum size of embedding cache (number of entries) */ + embeddingCacheMaxSize: number; + /** Embedding cache TTL in milliseconds */ + embeddingCacheTTLMs: number; + /** Query cache TTL in milliseconds */ + queryCacheTTLMs: number; + /** Enable query result caching */ + queryCacheEnabled: boolean; +} + +/** + * Rate limiting configuration for LLM tier. + */ +export interface RateLimitConfig { + /** Maximum requests per hour per user */ + requestsPerHour: number; + /** Budget limit in cents */ + budgetLimit: number; + /** Cost per request in cents */ + costPerRequest: number; +} + +/** + * A/B testing configuration for gradual rollout. + */ +export interface ABTestingConfig { + /** Enable A/B testing */ + enabled: boolean; + /** Percentage of users with reranking enabled (0-100) */ + rolloutPercentage: number; +} + +/** + * Complete configuration for the reranking system. + */ +export interface RerankerConfig { + // Global settings + /** Enable/disable reranking globally */ + enabled: boolean; + /** Default tier to use if auto-routing is disabled */ + defaultTier: RerankerTier; + /** Default depth for reranking - how many candidates to fetch */ + depth: number; + /** Timeout for reranking operations in milliseconds */ + timeoutMs: number; + + // Tier-specific settings + tiers: Record; + + // Routing settings + routing: RoutingConfig; + + // Caching settings + cache: RerankerCacheConfig; + + // Rate limiting (primarily for LLM tier) + rateLimit: RateLimitConfig; + + // A/B testing + abTesting: ABTestingConfig; +} + +// ============================================================================= +// Reranker Configuration Values +// ============================================================================= + +/** + * Default tier configuration values. + */ +export const DEFAULT_TIER_CONFIGS: Record = { + fast: { + model: envStr("RERANKER_FAST_MODEL", "Xenova/ms-marco-MiniLM-L-6-v2"), + maxLatencyMs: 50, + batchSize: envNum("RERANKER_FAST_BATCH_SIZE", 16), + maxCandidates: envNum("RERANKER_FAST_MAX_CANDIDATES", 50), + enabled: envBool("RERANKER_FAST_ENABLED", true), + }, + accurate: { + model: envStr("RERANKER_ACCURATE_MODEL", "Xenova/bge-reranker-base"), + maxLatencyMs: 150, + batchSize: envNum("RERANKER_ACCURATE_BATCH_SIZE", 8), + maxCandidates: envNum("RERANKER_ACCURATE_MAX_CANDIDATES", 30), + enabled: envBool("RERANKER_ACCURATE_ENABLED", true), + }, + code: { + model: envStr("RERANKER_CODE_MODEL", "jinaai/jina-reranker-v2-base-multilingual"), + maxLatencyMs: 150, + batchSize: envNum("RERANKER_CODE_BATCH_SIZE", 8), + maxCandidates: envNum("RERANKER_CODE_MAX_CANDIDATES", 30), + enabled: envBool("RERANKER_CODE_ENABLED", true), + }, + llm: { + model: envStr("RERANKER_LLM_MODEL", "grok-4-1-fast-reasoning"), + maxLatencyMs: 2000, + batchSize: 1, // Always 1 for LLM + maxCandidates: envNum("RERANKER_LLM_MAX_CANDIDATES", 10), + enabled: envBool("RERANKER_LLM_ENABLED", true), + }, +}; + +/** + * Default routing configuration. + */ +export const DEFAULT_ROUTING_CONFIG: RoutingConfig = { + codePatterns: [ + /\w+\.\w+\(/, // method calls: foo.bar() + /function\s+\w+/, // function declarations + /class\s+\w+/, // class declarations + /import\s+/, // import statements + /export\s+/, // export statements + /const\s+\w+\s*=/, // variable declarations + /interface\s+\w+/, // interface declarations + /type\s+\w+/, // type declarations + ], + complexThreshold: envNum("RERANKER_COMPLEXITY_THRESHOLD", 50), + agenticPatterns: [/tool|function|call|execute|invoke|run/i], + codePatternWeight: envFloat("RERANKER_CODE_PATTERN_WEIGHT", 0.8), + latencyBudgetDefault: envNum("RERANKER_LATENCY_BUDGET", 500), +}; + +/** + * Default cache configuration. + */ +export const DEFAULT_CACHE_CONFIG: RerankerCacheConfig = { + queryResultTTL: envNum("RERANKER_QUERY_CACHE_TTL", 300), // 5 minutes + documentRepresentationTTL: envNum("RERANKER_DOC_CACHE_TTL", 3600), // 1 hour + maxCacheSize: envNum("RERANKER_MAX_CACHE_SIZE", 1024 * 1024 * 1024), // 1GB + embeddingCacheMaxSize: envNum("RERANKER_EMBEDDING_CACHE_MAX_SIZE", 10000), + embeddingCacheTTLMs: envNum("RERANKER_EMBEDDING_CACHE_TTL_MS", 3600000), // 1 hour + queryCacheTTLMs: envNum("RERANKER_QUERY_CACHE_TTL_MS", 300000), // 5 minutes + queryCacheEnabled: envBool("RERANKER_CACHE_ENABLED", true), +}; + +/** + * Default rate limit configuration. + */ +export const DEFAULT_RATE_LIMIT_CONFIG: RateLimitConfig = { + requestsPerHour: envNum("RERANKER_RATE_LIMIT_REQUESTS_PER_HOUR", 100), + budgetLimit: envNum("RERANKER_RATE_LIMIT_BUDGET", 1000), // $10 + costPerRequest: envNum("RERANKER_RATE_LIMIT_COST_PER_REQUEST", 5), // 5 cents +}; + +/** + * Default A/B testing configuration. + */ +export const DEFAULT_AB_TESTING_CONFIG: ABTestingConfig = { + enabled: envBool("RERANKER_AB_ENABLED", false), + rolloutPercentage: envNum("RERANKER_AB_ROLLOUT", 100), +}; + +/** + * Complete reranker configuration with environment variable overrides. + */ +export const rerankerConfig: RerankerConfig = { + enabled: envBool("RERANKER_ENABLED", true), + defaultTier: envStr("RERANKER_DEFAULT_TIER", "fast") as RerankerTier, + depth: envNum("RERANKER_DEPTH", 30), + timeoutMs: envNum("RERANKER_TIMEOUT_MS", 500), + tiers: DEFAULT_TIER_CONFIGS, + routing: DEFAULT_ROUTING_CONFIG, + cache: DEFAULT_CACHE_CONFIG, + rateLimit: DEFAULT_RATE_LIMIT_CONFIG, + abTesting: DEFAULT_AB_TESTING_CONFIG, +}; + +// Backward compatibility: RERANK_CONFIG alias +export const RERANK_CONFIG = rerankerConfig; +export const DEFAULT_RERANKER_CONFIG = rerankerConfig; + +// ============================================================================= +// Runtime Configuration Management +// ============================================================================= + +export { RuntimeConfig } from "./runtime-config"; + +// ============================================================================= +// Validation Utilities +// ============================================================================= + +export type { ValidationError, ValidationResult } from "./validation"; +export { + assertValidConfig, + validateBusinessLogic, + validateComprehensive, + validateConfig, + validateModelNames, +} from "./validation"; + +// ============================================================================= +// Re-export types for backward compatibility +// ============================================================================= + +// Re-export CacheConfig type alias for backward compatibility +export type CacheConfig = RerankerCacheConfig; diff --git a/packages/search/src/config/reranker-config.test.ts b/packages/search/src/config/reranker-config.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b801dda15e93d1c4ef0ff924aa78668d1aa8f33b --- /dev/null +++ b/packages/search/src/config/reranker-config.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, test } from "vitest"; +import { + DEFAULT_AB_TESTING_CONFIG, + DEFAULT_CACHE_CONFIG, + DEFAULT_RATE_LIMIT_CONFIG, + DEFAULT_RERANKER_CONFIG, + DEFAULT_ROUTING_CONFIG, + DEFAULT_TIER_CONFIGS, +} from "./index"; + +describe("reranker-config", () => { + describe("DEFAULT_TIER_CONFIGS", () => { + test("should have all required tiers", () => { + expect(DEFAULT_TIER_CONFIGS).toHaveProperty("fast"); + expect(DEFAULT_TIER_CONFIGS).toHaveProperty("accurate"); + expect(DEFAULT_TIER_CONFIGS).toHaveProperty("code"); + expect(DEFAULT_TIER_CONFIGS).toHaveProperty("llm"); + }); + + test("should have valid fast tier config", () => { + const fast = DEFAULT_TIER_CONFIGS.fast; + expect(fast.model).toBe("Xenova/ms-marco-MiniLM-L-6-v2"); + expect(fast.maxCandidates).toBe(50); + expect(fast.batchSize).toBe(16); + expect(fast.enabled).toBe(true); + }); + + test("should have valid accurate tier config", () => { + const accurate = DEFAULT_TIER_CONFIGS.accurate; + expect(accurate.model).toBe("Xenova/bge-reranker-base"); + expect(accurate.maxCandidates).toBe(30); + expect(accurate.batchSize).toBe(8); + expect(accurate.enabled).toBe(true); + }); + + test("should have valid code tier config", () => { + const code = DEFAULT_TIER_CONFIGS.code; + expect(code.model).toBe("jinaai/jina-reranker-v2-base-multilingual"); + expect(code.maxCandidates).toBe(30); + expect(code.batchSize).toBe(8); + expect(code.enabled).toBe(true); + }); + + test("should have valid llm tier config", () => { + const llm = DEFAULT_TIER_CONFIGS.llm; + expect(llm.model).toBe("grok-4-1-fast-reasoning"); + expect(llm.maxCandidates).toBe(10); + expect(llm.batchSize).toBe(1); + expect(llm.enabled).toBe(true); + }); + + test("should have LLM maxCandidates less than other tiers", () => { + expect(DEFAULT_TIER_CONFIGS.llm.maxCandidates).toBeLessThan( + DEFAULT_TIER_CONFIGS.fast.maxCandidates, + ); + expect(DEFAULT_TIER_CONFIGS.llm.maxCandidates).toBeLessThanOrEqual( + DEFAULT_TIER_CONFIGS.accurate.maxCandidates, + ); + expect(DEFAULT_TIER_CONFIGS.llm.maxCandidates).toBeLessThanOrEqual( + DEFAULT_TIER_CONFIGS.code.maxCandidates, + ); + }); + }); + + describe("DEFAULT_ROUTING_CONFIG", () => { + test("should have valid routing thresholds", () => { + expect(DEFAULT_ROUTING_CONFIG.complexThreshold).toBe(50); + expect(DEFAULT_ROUTING_CONFIG.codePatternWeight).toBe(0.8); + expect(DEFAULT_ROUTING_CONFIG.latencyBudgetDefault).toBe(500); + }); + + test("should have code patterns", () => { + expect(DEFAULT_ROUTING_CONFIG.codePatterns).toBeInstanceOf(Array); + expect(DEFAULT_ROUTING_CONFIG.codePatterns.length).toBeGreaterThan(0); + expect(DEFAULT_ROUTING_CONFIG.codePatterns[0]).toBeInstanceOf(RegExp); + }); + + test("should have agentic patterns", () => { + expect(DEFAULT_ROUTING_CONFIG.agenticPatterns).toBeInstanceOf(Array); + expect(DEFAULT_ROUTING_CONFIG.agenticPatterns.length).toBeGreaterThan(0); + expect(DEFAULT_ROUTING_CONFIG.agenticPatterns[0]).toBeInstanceOf(RegExp); + }); + + test("code patterns should match code syntax", () => { + const patterns = DEFAULT_ROUTING_CONFIG.codePatterns; + + // Test method calls + expect(patterns.some((p) => p.test("foo.bar()"))).toBe(true); + + // Test function declarations + expect(patterns.some((p) => p.test("function myFunc()"))).toBe(true); + + // Test class declarations + expect(patterns.some((p) => p.test("class MyClass"))).toBe(true); + + // Test import statements + expect(patterns.some((p) => p.test("import React from 'react'"))).toBe(true); + + // Test variable declarations + expect(patterns.some((p) => p.test("const x = 5"))).toBe(true); + }); + }); + + describe("DEFAULT_CACHE_CONFIG", () => { + test("should have valid cache settings", () => { + expect(DEFAULT_CACHE_CONFIG.embeddingCacheMaxSize).toBe(10000); + expect(DEFAULT_CACHE_CONFIG.embeddingCacheTTLMs).toBe(3600000); // 1 hour + expect(DEFAULT_CACHE_CONFIG.queryCacheTTLMs).toBe(300000); // 5 minutes + expect(DEFAULT_CACHE_CONFIG.queryCacheEnabled).toBe(true); + }); + + test("should have reasonable TTL values", () => { + // Embedding cache should be longer than query cache + expect(DEFAULT_CACHE_CONFIG.embeddingCacheTTLMs).toBeGreaterThan( + DEFAULT_CACHE_CONFIG.queryCacheTTLMs, + ); + }); + }); + + describe("DEFAULT_RATE_LIMIT_CONFIG", () => { + test("should have valid rate limit settings", () => { + expect(DEFAULT_RATE_LIMIT_CONFIG.requestsPerHour).toBe(100); + expect(DEFAULT_RATE_LIMIT_CONFIG.budgetLimit).toBe(1000); // $10 + expect(DEFAULT_RATE_LIMIT_CONFIG.costPerRequest).toBe(5); // 5 cents + }); + + test("should allow at least one request within budget", () => { + const { budgetLimit, costPerRequest } = DEFAULT_RATE_LIMIT_CONFIG; + expect(budgetLimit).toBeGreaterThanOrEqual(costPerRequest); + }); + }); + + describe("DEFAULT_AB_TESTING_CONFIG", () => { + test("should have valid A/B testing settings", () => { + expect(DEFAULT_AB_TESTING_CONFIG.enabled).toBe(false); + expect(DEFAULT_AB_TESTING_CONFIG.rolloutPercentage).toBe(100); + }); + + test("should have rollout percentage in valid range", () => { + expect(DEFAULT_AB_TESTING_CONFIG.rolloutPercentage).toBeGreaterThanOrEqual(0); + expect(DEFAULT_AB_TESTING_CONFIG.rolloutPercentage).toBeLessThanOrEqual(100); + }); + }); + + describe("DEFAULT_RERANKER_CONFIG", () => { + test("should have all required top-level properties", () => { + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("enabled"); + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("defaultTier"); + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("timeoutMs"); + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("tiers"); + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("routing"); + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("cache"); + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("rateLimit"); + expect(DEFAULT_RERANKER_CONFIG).toHaveProperty("abTesting"); + }); + + test("should have reranking enabled by default", () => { + expect(DEFAULT_RERANKER_CONFIG.enabled).toBe(true); + }); + + test("should have fast as default tier", () => { + expect(DEFAULT_RERANKER_CONFIG.defaultTier).toBe("fast"); + }); + + test("should have reasonable timeout", () => { + expect(DEFAULT_RERANKER_CONFIG.timeoutMs).toBe(500); + expect(DEFAULT_RERANKER_CONFIG.timeoutMs).toBeGreaterThan(0); + expect(DEFAULT_RERANKER_CONFIG.timeoutMs).toBeLessThan(10000); + }); + + test("should include all tier configs", () => { + expect(DEFAULT_RERANKER_CONFIG.tiers).toEqual(DEFAULT_TIER_CONFIGS); + }); + + test("should include routing config", () => { + expect(DEFAULT_RERANKER_CONFIG.routing).toEqual(DEFAULT_ROUTING_CONFIG); + }); + + test("should include cache config", () => { + expect(DEFAULT_RERANKER_CONFIG.cache).toEqual(DEFAULT_CACHE_CONFIG); + }); + + test("should include rate limit config", () => { + expect(DEFAULT_RERANKER_CONFIG.rateLimit).toEqual(DEFAULT_RATE_LIMIT_CONFIG); + }); + + test("should include A/B testing config", () => { + expect(DEFAULT_RERANKER_CONFIG.abTesting).toEqual(DEFAULT_AB_TESTING_CONFIG); + }); + }); +}); diff --git a/packages/search/src/config/runtime-config.test.ts b/packages/search/src/config/runtime-config.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..79c5589d51532722d7249df24abf792f7eff9d7e --- /dev/null +++ b/packages/search/src/config/runtime-config.test.ts @@ -0,0 +1,358 @@ +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { DEFAULT_RERANKER_CONFIG, RuntimeConfig } from "./index"; + +describe("RuntimeConfig", () => { + // Store original env + const originalEnv = { ...process.env }; + + beforeEach(() => { + // Set dummy API key to avoid validation errors + process.env.XAI_API_KEY = "test-api-key"; + // Clean up singleton before each test + RuntimeConfig.destroy(); + }); + + afterEach(() => { + RuntimeConfig.destroy(); + // Restore original env + process.env = { ...originalEnv }; + }); + + describe("get", () => { + test("should initialize from environment on first call", () => { + const config = RuntimeConfig.get(); + + expect(config).toBeDefined(); + expect(config.enabled).toBe(true); + expect(config.defaultTier).toBe("fast"); + }); + + test("should return same config on subsequent calls", () => { + const config1 = RuntimeConfig.get(); + const config2 = RuntimeConfig.get(); + + expect(config1).toEqual(config2); + }); + + test("should return deep copy (prevent external mutation)", () => { + const config1 = RuntimeConfig.get(); + config1.enabled = false; + config1.defaultTier = "llm"; + + const config2 = RuntimeConfig.get(); + + expect(config2.enabled).toBe(true); + expect(config2.defaultTier).toBe("fast"); + }); + }); + + describe("update", () => { + test("should update top-level properties", () => { + RuntimeConfig.update({ enabled: false }); + + const config = RuntimeConfig.get(); + expect(config.enabled).toBe(false); + }); + + test("should update nested properties", () => { + RuntimeConfig.update({ + tiers: { + fast: { + model: "custom/model", + maxCandidates: 100, + batchSize: 32, + enabled: false, + }, + }, + }); + + const config = RuntimeConfig.get(); + expect(config.tiers.fast.model).toBe("custom/model"); + expect(config.tiers.fast.maxCandidates).toBe(100); + expect(config.tiers.fast.batchSize).toBe(32); + expect(config.tiers.fast.enabled).toBe(false); + }); + + test("should deep merge nested objects", () => { + // Update only one property of fast tier + RuntimeConfig.update({ + tiers: { + fast: { + model: "custom/model", + }, + }, + }); + + const config = RuntimeConfig.get(); + expect(config.tiers.fast.model).toBe("custom/model"); + // Other properties should remain unchanged + expect(config.tiers.fast.maxCandidates).toBe( + DEFAULT_RERANKER_CONFIG.tiers.fast.maxCandidates, + ); + expect(config.tiers.fast.batchSize).toBe(DEFAULT_RERANKER_CONFIG.tiers.fast.batchSize); + expect(config.tiers.fast.enabled).toBe(DEFAULT_RERANKER_CONFIG.tiers.fast.enabled); + }); + + test("should notify watchers on update", () => { + let callCount = 0; + let lastConfig = null; + + RuntimeConfig.watch((config) => { + callCount++; + lastConfig = config; + }); + + // Reset count after initial watch call + callCount = 0; + + RuntimeConfig.update({ enabled: false }); + + expect(callCount).toBe(1); + expect(lastConfig?.enabled).toBe(false); + }); + + test("should auto-disable LLM tier when API key is missing", () => { + // Delete XAI_API_KEY before update + delete process.env.XAI_API_KEY; + + // Try to enable LLM tier without API key + RuntimeConfig.update({ + tiers: { + llm: { + enabled: true, + }, + }, + }); + + const currentConfig = RuntimeConfig.get(); + // LLM tier should be auto-disabled (not crash) when API key is missing + expect(currentConfig.tiers.llm.enabled).toBe(false); + }); + }); + + describe("reset", () => { + test("should reset to environment defaults", () => { + // Make some updates + RuntimeConfig.update({ enabled: false, defaultTier: "llm" }); + + const updatedConfig = RuntimeConfig.get(); + expect(updatedConfig.enabled).toBe(false); + expect(updatedConfig.defaultTier).toBe("llm"); + + // Reset + RuntimeConfig.reset(); + + const resetConfig = RuntimeConfig.get(); + expect(resetConfig.enabled).toBe(true); + expect(resetConfig.defaultTier).toBe("fast"); + }); + + test("should notify watchers on reset", () => { + let callCount = 0; + + RuntimeConfig.watch(() => { + callCount++; + }); + + // Reset count after initial watch call + callCount = 0; + + RuntimeConfig.reset(); + + expect(callCount).toBe(1); + }); + }); + + describe("watch", () => { + test("should invoke callback immediately with current config", () => { + let callCount = 0; + let receivedConfig = null; + + RuntimeConfig.watch((config) => { + callCount++; + receivedConfig = config; + }); + + expect(callCount).toBe(1); + expect(receivedConfig).toBeDefined(); + }); + + test("should invoke callback on config update", () => { + let callCount = 0; + + RuntimeConfig.watch(() => { + callCount++; + }); + + // Reset count after initial call + callCount = 0; + + RuntimeConfig.update({ enabled: false }); + + expect(callCount).toBe(1); + }); + + test("should support multiple watchers", () => { + let count1 = 0; + let count2 = 0; + + RuntimeConfig.watch(() => { + count1++; + }); + RuntimeConfig.watch(() => { + count2++; + }); + + // Reset counts after initial calls + count1 = 0; + count2 = 0; + + RuntimeConfig.update({ enabled: false }); + + expect(count1).toBe(1); + expect(count2).toBe(1); + }); + + test("should return unwatch function", () => { + let callCount = 0; + + const unwatch = RuntimeConfig.watch(() => { + callCount++; + }); + + // Reset count after initial call + callCount = 0; + + RuntimeConfig.update({ enabled: false }); + expect(callCount).toBe(1); + + // Unwatch + unwatch(); + + RuntimeConfig.update({ enabled: true }); + expect(callCount).toBe(1); // Should not increase + }); + + test("should handle watcher errors gracefully", () => { + let goodCallCount = 0; + let badWatcherCalled = false; + + // Add a watcher that throws (but catch it) + RuntimeConfig.watch(() => { + badWatcherCalled = true; + if (badWatcherCalled && goodCallCount > 0) { + // Only throw on update, not initial call + throw new Error("Watcher error"); + } + }); + + // Add a good watcher + RuntimeConfig.watch(() => { + goodCallCount++; + }); + + // Reset state after initial calls + goodCallCount = 0; + badWatcherCalled = false; + + // Update should not throw, and good watcher should still be called + expect(() => RuntimeConfig.update({ enabled: false })).not.toThrow(); + expect(goodCallCount).toBe(1); + }); + + test("should provide deep copy to watchers", () => { + let receivedConfig = null; + + RuntimeConfig.watch((config) => { + receivedConfig = config; + }); + + // Mutate received config + receivedConfig.enabled = false; + + // Get fresh config + const freshConfig = RuntimeConfig.get(); + expect(freshConfig.enabled).toBe(true); + }); + }); + + describe("initialize", () => { + test("should initialize with custom config", () => { + const customConfig = { + ...DEFAULT_RERANKER_CONFIG, + enabled: false, + defaultTier: "accurate" as const, + }; + + RuntimeConfig.initialize(customConfig); + + const config = RuntimeConfig.get(); + expect(config.enabled).toBe(false); + expect(config.defaultTier).toBe("accurate"); + }); + + test("should replace existing instance", () => { + // Initialize first time + RuntimeConfig.get(); + + const customConfig = { + ...DEFAULT_RERANKER_CONFIG, + enabled: false, + }; + + RuntimeConfig.initialize(customConfig); + + const config = RuntimeConfig.get(); + expect(config.enabled).toBe(false); + }); + }); + + describe("destroy", () => { + test("should clear singleton instance", () => { + RuntimeConfig.get(); + RuntimeConfig.destroy(); + + // Should reinitialize on next get + const config = RuntimeConfig.get(); + expect(config).toBeDefined(); + }); + + test("should clear all watchers", () => { + let callCount = 0; + + RuntimeConfig.watch(() => { + callCount++; + }); + + RuntimeConfig.destroy(); + callCount = 0; + + // Reinitialize + RuntimeConfig.get(); + + // Update should not trigger old watcher + RuntimeConfig.update({ enabled: false }); + expect(callCount).toBe(0); + }); + }); + + describe("getWatcherCount", () => { + test("should return 0 when no instance", () => { + expect(RuntimeConfig.getWatcherCount()).toBe(0); + }); + + test("should return correct count", () => { + RuntimeConfig.watch(() => {}); + expect(RuntimeConfig.getWatcherCount()).toBe(1); + + RuntimeConfig.watch(() => {}); + expect(RuntimeConfig.getWatcherCount()).toBe(2); + + const unwatch = RuntimeConfig.watch(() => {}); + expect(RuntimeConfig.getWatcherCount()).toBe(3); + + unwatch(); + expect(RuntimeConfig.getWatcherCount()).toBe(2); + }); + }); +}); diff --git a/packages/search/src/config/runtime-config.ts b/packages/search/src/config/runtime-config.ts new file mode 100644 index 0000000000000000000000000000000000000000..4747a5449e685092c57ca6870c05dab5fd6b2f42 --- /dev/null +++ b/packages/search/src/config/runtime-config.ts @@ -0,0 +1,272 @@ +import { createLogger } from "@engram/logger"; +import type { RerankerConfig } from "./index"; +import { rerankerConfig } from "./index"; + +const logger = createLogger({ component: "RuntimeConfig" }); + +/** + * Type for configuration update callback. + */ +type ConfigUpdateCallback = (config: RerankerConfig) => void; + +/** + * RuntimeConfig provides a singleton for managing reranker configuration + * with support for runtime updates and hot reload. + * + * Features: + * - Lazy initialization from environment + * - Runtime configuration updates via update() + * - Watch callbacks for configuration changes + * - Thread-safe singleton pattern + * - Validation on updates + * + * Example usage: + * ```ts + * // Get current config + * const config = RuntimeConfig.get(); + * + * // Update config at runtime + * RuntimeConfig.update({ defaultTier: 'accurate' }); + * + * // Watch for changes + * const unwatch = RuntimeConfig.watch((config) => { + * console.log('Config updated:', config); + * }); + * + * // Later: stop watching + * unwatch(); + * ``` + */ +export class RuntimeConfig { + private static instance: RuntimeConfig | null = null; + private config: RerankerConfig; + private watchers: Set = new Set(); + + private constructor(initialConfig?: RerankerConfig) { + if (initialConfig) { + this.config = initialConfig; + } else { + // Use the pre-loaded config from index (already has env vars applied) + this.config = structuredClone(rerankerConfig); + this.validateApiKeys(this.config); + } + + logger.info({ + msg: "Runtime configuration initialized", + enabled: this.config.enabled, + defaultTier: this.config.defaultTier, + timeoutMs: this.config.timeoutMs, + abTesting: this.config.abTesting, + }); + } + + /** + * Get the singleton instance of RuntimeConfig. + * Initializes from environment on first call. + * + * @returns Current reranker configuration + */ + static get(): RerankerConfig { + if (!RuntimeConfig.instance) { + RuntimeConfig.instance = new RuntimeConfig(); + } + // Return a deep copy to prevent external mutation + return structuredClone(RuntimeConfig.instance.config); + } + + /** + * Update configuration at runtime. + * Performs deep merge with existing configuration. + * + * @param partial - Partial configuration to update + * @throws {Error} If validation fails + */ + static update(partial: Partial): void { + if (!RuntimeConfig.instance) { + RuntimeConfig.instance = new RuntimeConfig(); + } + + const instance = RuntimeConfig.instance; + const oldConfig = structuredClone(instance.config); + + // Deep merge partial config + instance.config = RuntimeConfig.deepMerge(instance.config, partial); + + // Validate updated config + try { + instance.validateApiKeys(instance.config); + } catch (error) { + // Rollback on validation failure + instance.config = oldConfig; + throw error; + } + + logger.info({ + msg: "Configuration updated", + changes: partial, + }); + + // Notify watchers + instance.notifyWatchers(); + } + + /** + * Reset configuration to environment defaults. + * Clears all runtime updates. + */ + static reset(): void { + if (!RuntimeConfig.instance) { + return; + } + + const instance = RuntimeConfig.instance; + instance.config = structuredClone(rerankerConfig); + instance.validateApiKeys(instance.config); + + logger.info({ + msg: "Configuration reset to environment defaults", + }); + + instance.notifyWatchers(); + } + + /** + * Watch for configuration changes. + * Callback is invoked immediately with current config and on every update. + * + * @param callback - Function to call when configuration changes + * @returns Unwatch function to stop receiving updates + */ + static watch(callback: ConfigUpdateCallback): () => void { + if (!RuntimeConfig.instance) { + RuntimeConfig.instance = new RuntimeConfig(); + } + + const instance = RuntimeConfig.instance; + instance.watchers.add(callback); + + // Invoke callback immediately with current config + callback(structuredClone(instance.config)); + + logger.debug({ + msg: "Configuration watcher registered", + totalWatchers: instance.watchers.size, + }); + + // Return unwatch function + return () => { + instance.watchers.delete(callback); + logger.debug({ + msg: "Configuration watcher removed", + totalWatchers: instance.watchers.size, + }); + }; + } + + /** + * Initialize runtime configuration with a specific config. + * Useful for testing or manual initialization. + * + * @param config - Initial configuration + */ + static initialize(config: RerankerConfig): void { + RuntimeConfig.instance = new RuntimeConfig(config); + logger.info({ + msg: "Runtime configuration manually initialized", + }); + } + + /** + * Clear the singleton instance. + * Primarily for testing purposes. + */ + static destroy(): void { + if (RuntimeConfig.instance) { + RuntimeConfig.instance.watchers.clear(); + RuntimeConfig.instance = null; + logger.debug({ + msg: "Runtime configuration destroyed", + }); + } + } + + /** + * Get the number of active watchers. + * Useful for debugging and testing. + */ + static getWatcherCount(): number { + return RuntimeConfig.instance?.watchers.size ?? 0; + } + + /** + * Validate that required API keys are present for enabled tiers. + * Logs a warning and disables the tier if API key is missing (instead of crashing). + * + * @param config - Reranker configuration + */ + private validateApiKeys(config: RerankerConfig): void { + // Check if LLM tier is enabled and requires API key + if (config.tiers.llm.enabled && !process.env.XAI_API_KEY) { + // Log warning and disable tier instead of crashing + logger.warn({ + msg: "XAI_API_KEY not set - LLM reranker tier will be disabled", + tier: "llm", + }); + config.tiers.llm.enabled = false; + } + } + + /** + * Notify all watchers of configuration change. + */ + private notifyWatchers(): void { + const configCopy = structuredClone(this.config); + for (const callback of this.watchers) { + try { + callback(configCopy); + } catch (error) { + logger.error({ + msg: "Error in configuration watcher callback", + error, + }); + } + } + } + + /** + * Deep merge two configuration objects. + * Arrays are replaced, not merged. + */ + private static deepMerge(target: T, source: Partial): T { + const result = { ...target }; + + for (const key in source) { + const sourceValue = source[key]; + const targetValue = result[key]; + + if (sourceValue === undefined) { + continue; + } + + // Handle nested objects + if ( + typeof sourceValue === "object" && + sourceValue !== null && + !Array.isArray(sourceValue) && + typeof targetValue === "object" && + targetValue !== null && + !Array.isArray(targetValue) + ) { + result[key] = RuntimeConfig.deepMerge( + targetValue, + sourceValue as Partial, + ) as T[Extract]; + } else { + // Replace value (including arrays) + result[key] = sourceValue as T[Extract]; + } + } + + return result; + } +} diff --git a/packages/search/src/config/validation.test.ts b/packages/search/src/config/validation.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe1f8e7d6173943f8e62e4da53e425d476549426 --- /dev/null +++ b/packages/search/src/config/validation.test.ts @@ -0,0 +1,513 @@ +import { describe, expect, test } from "vitest"; +import { + assertValidConfig, + DEFAULT_RERANKER_CONFIG, + validateBusinessLogic, + validateComprehensive, + validateConfig, + validateModelNames, +} from "./index"; + +describe("validation", () => { + describe("validateConfig", () => { + test("should validate default config", () => { + const result = validateConfig(DEFAULT_RERANKER_CONFIG); + + expect(result.valid).toBe(true); + expect(result.errors).toHaveLength(0); + }); + + test("should reject config with missing required fields", () => { + const invalidConfig = { + enabled: true, + // Missing defaultTier, timeoutMs, etc. + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + test("should reject config with invalid types", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + enabled: "yes", // Should be boolean + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path === "enabled")).toBe(true); + }); + + test("should reject config with invalid tier", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + defaultTier: "super_fast", // Invalid tier + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path === "defaultTier")).toBe(true); + }); + + test("should reject config with negative timeoutMs", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + timeoutMs: -100, + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path === "timeoutMs")).toBe(true); + }); + + test("should reject config with excessive timeoutMs", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + timeoutMs: 60000, // > 30 seconds + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path === "timeoutMs")).toBe(true); + }); + + test("should reject config with empty model name", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + model: "", + }, + }, + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path.includes("fast.model"))).toBe(true); + }); + + test("should reject config with invalid maxCandidates", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + maxCandidates: 0, + }, + }, + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path.includes("fast.maxCandidates"))).toBe(true); + }); + + test("should reject config with excessive maxCandidates", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + maxCandidates: 2000, + }, + }, + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path.includes("fast.maxCandidates"))).toBe(true); + }); + + test("should reject config with invalid rolloutPercentage", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + abTesting: { + enabled: true, + rolloutPercentage: 150, // > 100 + }, + }; + + const result = validateConfig(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path.includes("rolloutPercentage"))).toBe(true); + }); + + test("should provide detailed error messages", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + timeoutMs: -100, + }; + + const result = validateConfig(invalidConfig); + + expect(result.errors[0]).toHaveProperty("path"); + expect(result.errors[0]).toHaveProperty("message"); + expect(result.errors[0]).toHaveProperty("code"); + }); + }); + + describe("assertValidConfig", () => { + test("should not throw for valid config", () => { + expect(() => assertValidConfig(DEFAULT_RERANKER_CONFIG)).not.toThrow(); + }); + + test("should throw for invalid config", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + enabled: "yes", + }; + + expect(() => assertValidConfig(invalidConfig)).toThrow("Invalid reranker configuration"); + }); + + test("should include error details in exception", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + enabled: "yes", + }; + + try { + assertValidConfig(invalidConfig); + expect.unreachable("Should have thrown"); + } catch (error) { + expect(error.message).toContain("enabled"); + } + }); + }); + + describe("validateModelNames", () => { + test("should validate default config models", () => { + const result = validateModelNames(DEFAULT_RERANKER_CONFIG); + + expect(result.valid).toBe(true); + expect(result.errors).toHaveLength(0); + }); + + test("should warn about unknown local model", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + model: "unknown/custom-model", + }, + }, + }; + + const result = validateModelNames(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path === "tiers.fast.model")).toBe(true); + expect(result.errors.some((err) => err.code === "unknown_model")).toBe(true); + }); + + test("should warn about unknown LLM model", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + llm: { + ...DEFAULT_RERANKER_CONFIG.tiers.llm, + model: "unknown-llm-model", + }, + }, + }; + + const result = validateModelNames(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.path === "tiers.llm.model")).toBe(true); + expect(result.errors.some((err) => err.code === "unknown_model")).toBe(true); + }); + + test("should validate all known local models", () => { + const knownModels = [ + "Xenova/ms-marco-MiniLM-L-6-v2", + "Xenova/bge-reranker-base", + "jinaai/jina-reranker-v2-base-multilingual", + "BAAI/bge-reranker-base", + "BAAI/bge-reranker-large", + ]; + + for (const model of knownModels) { + const config = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + model, + }, + }, + }; + + const result = validateModelNames(config); + expect(result.errors.filter((err) => err.path === "tiers.fast.model")).toHaveLength(0); + } + }); + + test("should validate all known LLM models", () => { + const knownModels = [ + "grok-4-1-fast-reasoning", + "grok-beta", + "grok-vision-beta", + "grok-2-latest", + ]; + + for (const model of knownModels) { + const config = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + llm: { + ...DEFAULT_RERANKER_CONFIG.tiers.llm, + model, + }, + }, + }; + + const result = validateModelNames(config); + expect(result.errors.filter((err) => err.path === "tiers.llm.model")).toHaveLength(0); + } + }); + }); + + describe("validateBusinessLogic", () => { + test("should validate default config", () => { + const result = validateBusinessLogic(DEFAULT_RERANKER_CONFIG); + + expect(result.valid).toBe(true); + expect(result.errors).toHaveLength(0); + }); + + test("should reject config with all tiers disabled when reranking enabled", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + enabled: true, + tiers: { + fast: { ...DEFAULT_RERANKER_CONFIG.tiers.fast, enabled: false }, + accurate: { ...DEFAULT_RERANKER_CONFIG.tiers.accurate, enabled: false }, + code: { ...DEFAULT_RERANKER_CONFIG.tiers.code, enabled: false }, + llm: { ...DEFAULT_RERANKER_CONFIG.tiers.llm, enabled: false }, + }, + }; + + const result = validateBusinessLogic(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.code === "no_enabled_tiers")).toBe(true); + }); + + test("should accept config with all tiers disabled when reranking disabled", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + enabled: false, + tiers: { + fast: { ...DEFAULT_RERANKER_CONFIG.tiers.fast, enabled: false }, + accurate: { ...DEFAULT_RERANKER_CONFIG.tiers.accurate, enabled: false }, + code: { ...DEFAULT_RERANKER_CONFIG.tiers.code, enabled: false }, + llm: { ...DEFAULT_RERANKER_CONFIG.tiers.llm, enabled: false }, + }, + }; + + const result = validateBusinessLogic(config); + + // No error for no_enabled_tiers when reranking is disabled + expect(result.errors.some((err) => err.code === "no_enabled_tiers")).toBe(false); + }); + + test("should reject config with disabled default tier", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + enabled: true, + defaultTier: "fast" as const, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + fast: { ...DEFAULT_RERANKER_CONFIG.tiers.fast, enabled: false }, + }, + }; + + const result = validateBusinessLogic(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.code === "default_tier_disabled")).toBe(true); + }); + + test("should reject config with LLM maxCandidates > fast maxCandidates", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + llm: { + ...DEFAULT_RERANKER_CONFIG.tiers.llm, + maxCandidates: 100, + }, + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + maxCandidates: 50, + }, + }, + }; + + const result = validateBusinessLogic(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.code === "invalid_candidate_hierarchy")).toBe(true); + }); + + test("should reject A/B testing enabled with 0% rollout", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + abTesting: { + enabled: true, + rolloutPercentage: 0, + }, + }; + + const result = validateBusinessLogic(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.code === "invalid_rollout")).toBe(true); + }); + + test("should accept A/B testing disabled with 0% rollout", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + abTesting: { + enabled: false, + rolloutPercentage: 0, + }, + }; + + const result = validateBusinessLogic(config); + + expect(result.errors.some((err) => err.code === "invalid_rollout")).toBe(false); + }); + + test("should reject budget limit less than cost per request", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + rateLimit: { + ...DEFAULT_RERANKER_CONFIG.rateLimit, + budgetLimit: 3, // 3 cents + costPerRequest: 5, // 5 cents + }, + }; + + const result = validateBusinessLogic(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.code === "invalid_budget")).toBe(true); + }); + + test("should accept budget limit equal to cost per request", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + rateLimit: { + ...DEFAULT_RERANKER_CONFIG.rateLimit, + budgetLimit: 5, + costPerRequest: 5, + }, + }; + + const result = validateBusinessLogic(config); + + expect(result.errors.some((err) => err.code === "invalid_budget")).toBe(false); + }); + }); + + describe("validateComprehensive", () => { + test("should validate default config", () => { + const result = validateComprehensive(DEFAULT_RERANKER_CONFIG); + + expect(result.valid).toBe(true); + expect(result.errors).toHaveLength(0); + }); + + test("should catch schema validation errors", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + enabled: "yes", + }; + + const result = validateComprehensive(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + test("should catch business logic errors", () => { + const invalidConfig = { + ...DEFAULT_RERANKER_CONFIG, + enabled: true, + tiers: { + fast: { ...DEFAULT_RERANKER_CONFIG.tiers.fast, enabled: false }, + accurate: { ...DEFAULT_RERANKER_CONFIG.tiers.accurate, enabled: false }, + code: { ...DEFAULT_RERANKER_CONFIG.tiers.code, enabled: false }, + llm: { ...DEFAULT_RERANKER_CONFIG.tiers.llm, enabled: false }, + }, + }; + + const result = validateComprehensive(invalidConfig); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.code === "no_enabled_tiers")).toBe(true); + }); + + test("should catch model name warnings", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + tiers: { + ...DEFAULT_RERANKER_CONFIG.tiers, + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + model: "unknown/model", + }, + }, + }; + + const result = validateComprehensive(config); + + expect(result.valid).toBe(false); + expect(result.errors.some((err) => err.code === "unknown_model")).toBe(true); + }); + + test("should return all errors from all validators", () => { + const config = { + ...DEFAULT_RERANKER_CONFIG, + enabled: true, + tiers: { + fast: { + ...DEFAULT_RERANKER_CONFIG.tiers.fast, + model: "unknown/model", + enabled: false, + }, + accurate: { ...DEFAULT_RERANKER_CONFIG.tiers.accurate, enabled: false }, + code: { ...DEFAULT_RERANKER_CONFIG.tiers.code, enabled: false }, + llm: { ...DEFAULT_RERANKER_CONFIG.tiers.llm, enabled: false }, + }, + }; + + const result = validateComprehensive(config); + + expect(result.valid).toBe(false); + // Should have both model name error and no_enabled_tiers error + expect(result.errors.length).toBeGreaterThanOrEqual(2); + }); + }); +}); diff --git a/packages/search/src/config/validation.ts b/packages/search/src/config/validation.ts new file mode 100644 index 0000000000000000000000000000000000000000..a959295e082ad8af51f84ad4d9e1f480a112fc62 --- /dev/null +++ b/packages/search/src/config/validation.ts @@ -0,0 +1,333 @@ +import { z } from "zod"; +import type { RerankerTier } from "../models/schema"; +import type { RerankerConfig } from "./index"; + +/** + * Zod schema for TierConfig validation. + * Uses passthrough to allow additional fields like maxLatencyMs. + */ +const TierConfigSchema = z + .object({ + model: z.string().min(1, "Model name cannot be empty"), + maxCandidates: z + .number() + .int() + .positive("maxCandidates must be positive") + .max(1000, "maxCandidates cannot exceed 1000"), + batchSize: z + .number() + .int() + .positive("batchSize must be positive") + .max(128, "batchSize cannot exceed 128"), + enabled: z.boolean(), + }) + .passthrough(); + +/** + * Zod schema for RoutingConfig validation. + */ +const RoutingConfigSchema = z.object({ + complexThreshold: z + .number() + .int() + .min(0, "complexThreshold must be non-negative") + .max(1000, "complexThreshold cannot exceed 1000"), + codePatternWeight: z + .number() + .min(0, "codePatternWeight must be at least 0") + .max(1, "codePatternWeight cannot exceed 1"), + latencyBudgetDefault: z + .number() + .int() + .positive("latencyBudgetDefault must be positive") + .max(10000, "latencyBudgetDefault cannot exceed 10000ms"), + codePatterns: z.array(z.instanceof(RegExp)), + agenticPatterns: z.array(z.instanceof(RegExp)), +}); + +/** + * Zod schema for CacheConfig validation. + * Uses passthrough to allow additional cache-related fields. + */ +const CacheConfigSchema = z + .object({ + embeddingCacheMaxSize: z + .number() + .int() + .positive("embeddingCacheMaxSize must be positive") + .max(1000000, "embeddingCacheMaxSize cannot exceed 1,000,000"), + embeddingCacheTTLMs: z + .number() + .int() + .positive("embeddingCacheTTLMs must be positive") + .max(86400000, "embeddingCacheTTLMs cannot exceed 24 hours"), + queryCacheTTLMs: z + .number() + .int() + .positive("queryCacheTTLMs must be positive") + .max(3600000, "queryCacheTTLMs cannot exceed 1 hour"), + queryCacheEnabled: z.boolean(), + }) + .passthrough(); + +/** + * Zod schema for RateLimitConfig validation. + */ +const RateLimitConfigSchema = z.object({ + requestsPerHour: z + .number() + .int() + .positive("requestsPerHour must be positive") + .max(10000, "requestsPerHour cannot exceed 10,000"), + budgetLimit: z + .number() + .int() + .positive("budgetLimit must be positive") + .max(1000000, "budgetLimit cannot exceed $10,000"), + costPerRequest: z + .number() + .positive("costPerRequest must be positive") + .max(1000, "costPerRequest cannot exceed $10"), +}); + +/** + * Zod schema for ABTestingConfig validation. + */ +const ABTestingConfigSchema = z.object({ + enabled: z.boolean(), + rolloutPercentage: z + .number() + .int() + .min(0, "rolloutPercentage must be at least 0") + .max(100, "rolloutPercentage cannot exceed 100"), +}); + +/** + * Complete Zod schema for RerankerConfig validation. + * Uses passthrough to allow additional fields like depth. + */ +const RerankerConfigSchema = z + .object({ + enabled: z.boolean(), + defaultTier: z.enum(["fast", "accurate", "code", "llm"]), + timeoutMs: z + .number() + .int() + .positive("timeoutMs must be positive") + .max(30000, "timeoutMs cannot exceed 30 seconds"), + tiers: z.object({ + fast: TierConfigSchema, + accurate: TierConfigSchema, + code: TierConfigSchema, + llm: TierConfigSchema, + }), + routing: RoutingConfigSchema, + cache: CacheConfigSchema, + rateLimit: RateLimitConfigSchema, + abTesting: ABTestingConfigSchema, + }) + .passthrough(); + +/** + * Validation error details. + */ +export interface ValidationError { + path: string; + message: string; + code: string; +} + +/** + * Validation result. + */ +export interface ValidationResult { + valid: boolean; + errors: ValidationError[]; +} + +/** + * Validate a reranker configuration object. + * + * @param config - Configuration to validate + * @returns Validation result with errors if invalid + */ +export function validateConfig(config: unknown): ValidationResult { + const result = RerankerConfigSchema.safeParse(config); + + if (result.success) { + return { valid: true, errors: [] }; + } + + // Handle Zod v4 error structure (uses 'issues' not 'errors') + const issues = result.error?.issues ?? []; + + const errors: ValidationError[] = issues.map((issue) => ({ + path: issue.path.join("."), + message: issue.message, + code: issue.code, + })); + + return { valid: false, errors }; +} + +/** + * Validate and assert a reranker configuration. + * Throws an error if validation fails. + * + * @param config - Configuration to validate + * @throws {Error} If validation fails + */ +export function assertValidConfig(config: unknown): asserts config is RerankerConfig { + const result = validateConfig(config); + + if (!result.valid) { + const errorMessages = result.errors.map((err) => ` - ${err.path}: ${err.message}`).join("\n"); + + throw new Error(`Invalid reranker configuration:\n${errorMessages}`); + } +} + +/** + * Known valid model names for local rerankers (Transformers.js). + */ +const KNOWN_LOCAL_MODELS = [ + "Xenova/ms-marco-MiniLM-L-6-v2", + "Xenova/bge-reranker-base", + "jinaai/jina-reranker-v2-base-multilingual", + "BAAI/bge-reranker-base", + "BAAI/bge-reranker-large", +]; + +/** + * Known valid LLM model names (xAI API). + */ +const KNOWN_LLM_MODELS = [ + "grok-4-1-fast-reasoning", + "grok-beta", + "grok-vision-beta", + "grok-2-latest", +]; + +/** + * Validate that model names are recognized. + * + * @param config - Reranker configuration + * @returns Validation result with warnings for unknown models + */ +export function validateModelNames(config: RerankerConfig): ValidationResult { + const errors: ValidationError[] = []; + + // Check local models + const localTiers: Array = ["fast", "accurate", "code"]; + for (const tier of localTiers) { + const model = config.tiers[tier].model; + if (!KNOWN_LOCAL_MODELS.includes(model)) { + errors.push({ + path: `tiers.${tier}.model`, + message: `Unknown local model: ${model}. Known models: ${KNOWN_LOCAL_MODELS.join(", ")}`, + code: "unknown_model", + }); + } + } + + // Check LLM model + const llmModel = config.tiers.llm.model; + if (!KNOWN_LLM_MODELS.includes(llmModel)) { + errors.push({ + path: "tiers.llm.model", + message: `Unknown LLM model: ${llmModel}. Known models: ${KNOWN_LLM_MODELS.join(", ")}`, + code: "unknown_model", + }); + } + + return { valid: errors.length === 0, errors }; +} + +/** + * Validate business logic constraints. + * + * @param config - Reranker configuration + * @returns Validation result with errors if constraints violated + */ +export function validateBusinessLogic(config: RerankerConfig): ValidationResult { + const errors: ValidationError[] = []; + + // Ensure at least one tier is enabled + const enabledTiers = Object.values(config.tiers).filter((tier) => tier.enabled); + if (enabledTiers.length === 0 && config.enabled) { + errors.push({ + path: "tiers", + message: "At least one reranker tier must be enabled when reranking is enabled", + code: "no_enabled_tiers", + }); + } + + // Ensure default tier is enabled + const defaultTierConfig = config.tiers[config.defaultTier]; + if (!defaultTierConfig.enabled && config.enabled) { + errors.push({ + path: "defaultTier", + message: `Default tier '${config.defaultTier}' must be enabled`, + code: "default_tier_disabled", + }); + } + + // Validate maxCandidates hierarchy (llm < others) + if (config.tiers.llm.maxCandidates > config.tiers.fast.maxCandidates) { + errors.push({ + path: "tiers.llm.maxCandidates", + message: "LLM tier maxCandidates should be less than or equal to fast tier", + code: "invalid_candidate_hierarchy", + }); + } + + // Validate A/B testing rollout when enabled + if (config.abTesting.enabled && config.abTesting.rolloutPercentage === 0) { + errors.push({ + path: "abTesting.rolloutPercentage", + message: "A/B testing rollout percentage must be greater than 0 when enabled", + code: "invalid_rollout", + }); + } + + // Validate rate limiting is reasonable + if (config.rateLimit.budgetLimit < config.rateLimit.costPerRequest) { + errors.push({ + path: "rateLimit.budgetLimit", + message: + "Budget limit must be at least equal to cost per request (allows at least 1 request)", + code: "invalid_budget", + }); + } + + return { valid: errors.length === 0, errors }; +} + +/** + * Perform comprehensive validation of reranker configuration. + * Includes schema validation, model name validation, and business logic validation. + * + * @param config - Configuration to validate + * @returns Comprehensive validation result + */ +export function validateComprehensive(config: unknown): ValidationResult { + // First, validate schema + const schemaResult = validateConfig(config); + if (!schemaResult.valid) { + return schemaResult; + } + + // Type assertion is safe here due to schema validation + const validConfig = config as RerankerConfig; + + // Validate model names (warnings only) + const modelResult = validateModelNames(validConfig); + + // Validate business logic + const businessResult = validateBusinessLogic(validConfig); + + // Combine all errors + const allErrors = [...modelResult.errors, ...businessResult.errors]; + + return { valid: allErrors.length === 0, errors: allErrors }; +} diff --git a/packages/search/src/index.ts b/packages/search/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..9fc0fd20c5853b320dd5858c0545164ec1e3b91a --- /dev/null +++ b/packages/search/src/index.ts @@ -0,0 +1,34 @@ +export * from "./config/index"; +export * from "./models/schema"; +export * from "./services/abstention-detector"; +export * from "./services/base-embedder"; +export * from "./services/batch-indexer"; +export * from "./services/batched-reranker"; +export * from "./services/cache-metrics"; +export * from "./services/classifier"; +export * from "./services/code-embedder"; +export * from "./services/colbert-embedder"; +export * from "./services/colbert-reranker"; +export * from "./services/deduplicator"; +export * from "./services/embedder-factory"; +export * from "./services/embedding-cache"; +export * from "./services/fusion-predictor"; +export * from "./services/indexer"; +export * from "./services/learned-fusion"; +export * from "./services/llm-reranker"; +export * from "./services/multi-query-retriever"; +export * from "./services/query-cache"; +export * from "./services/query-features"; +export * from "./services/rate-limiter"; +export * from "./services/reranker"; +export * from "./services/reranker-metrics"; +export * from "./services/reranker-router"; +export * from "./services/retriever"; +export * from "./services/schema-manager"; +export * from "./services/score-merger"; +export * from "./services/session-retriever"; +export * from "./services/session-summarizer"; +export * from "./services/snapshot-manager"; +export * from "./services/splade-embedder"; +export * from "./services/temporal-parser"; +export * from "./services/text-embedder"; diff --git a/packages/search/src/models/schema.ts b/packages/search/src/models/schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d9ef62b6e28d0ec67c6b91c9b408c61d4b86554 --- /dev/null +++ b/packages/search/src/models/schema.ts @@ -0,0 +1,100 @@ +import { z } from "zod"; + +// Sparse vector schema for BM25-based keyword search +const SparseVectorSchema = z.object({ + indices: z.array(z.number()), + values: z.array(z.number()), +}); + +// Vector point schema with separate text/code dense vectors +export const VectorPointSchema = z.object({ + id: z.string().uuid(), + vectors: z.object({ + // Text dense vector: 384d (e5-small) + text_dense: z.array(z.number()).optional(), + // Code dense vector: 768d (nomic-embed-text-v1) + code_dense: z.array(z.number()).optional(), + // Sparse vector for hybrid search + sparse: SparseVectorSchema, + }), + payload: z.object({ + content: z.string(), // The text chunk + node_id: z.string(), // Link back to Graph Node + session_id: z.string(), + type: z.enum(["thought", "code", "doc"]), + timestamp: z.number(), // Epoch + file_path: z.string().optional(), + }), +}); + +export type VectorPoint = z.infer; + +// Extract the 'type' enum from VectorPointSchema to ensure consistency +export const SearchTypeEnum = VectorPointSchema.shape.payload.shape.type; +export type SearchType = z.infer; + +/** + * Reranker tier determines which model is used for cross-encoder scoring. + * - fast: Optimized for speed (< 50ms), uses lightweight model + * - accurate: Higher quality scoring for complex queries + * - code: Specialized for code search queries + * - llm: Premium LLM-based listwise reranking (highest latency) + */ +export type RerankerTier = "fast" | "accurate" | "code" | "llm"; + +export interface SearchQuery { + text: string; + limit?: number; + threshold?: number; + filters?: { + session_id?: string; + // Use the inferred type from the schema + type?: SearchType; + time_range?: { start: number; end: number }; + }; + strategy?: "hybrid" | "dense" | "sparse"; + + // Reranking options + /** Enable/disable reranking. Default: true */ + rerank?: boolean; + /** Reranker tier to use. Default: auto-routed based on query */ + rerankTier?: RerankerTier; + /** Number of candidates to fetch for reranking. Default: 30 */ + rerankDepth?: number; +} + +/** Payload returned in search results */ +export interface SearchResultPayload { + content: string; + node_id: string; + session_id: string; + type: SearchType; + timestamp: number; + file_path?: string; +} + +/** Search result with optional reranking scores */ +export interface SearchResult { + id: string | number; + + /** Final score used for ranking (rerankerScore if reranked, otherwise original) */ + score: number; + + /** Original RRF/dense/sparse score before reranking */ + rrfScore?: number; + + /** Cross-encoder relevance score (0-1), present if reranking was applied */ + rerankerScore?: number; + + /** Which reranker tier was used, present if reranking was applied */ + rerankTier?: RerankerTier; + + /** Document payload */ + payload?: SearchResultPayload; + + /** Indicates if the search result is degraded (reranker failed) */ + degraded?: boolean; + + /** Reason for degradation if applicable */ + degradedReason?: string; +} diff --git a/packages/search/src/services/ab-testing.test.ts b/packages/search/src/services/ab-testing.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8301bbe84f83d0b355c6f965feffe3eca51e1bc7 --- /dev/null +++ b/packages/search/src/services/ab-testing.test.ts @@ -0,0 +1,297 @@ +import { describe, expect, it } from "vitest"; +import { ABTestingService } from "./ab-testing"; + +describe("ABTestingService", () => { + describe("Variant Assignment", () => { + it("should assign consistent variants for same session", () => { + const service = new ABTestingService({ rerankEnabledPct: 50 }); + + const sessionId = "test-session-123"; + + // Get assignment multiple times + const assignment1 = service.assign(sessionId); + const assignment2 = service.assign(sessionId); + const assignment3 = service.assign(sessionId); + + // Should always return same variant + expect(assignment1.variant).toBe(assignment2.variant); + expect(assignment2.variant).toBe(assignment3.variant); + expect(assignment1.bucket).toBe(assignment2.bucket); + }); + + it("should assign different variants to different sessions", () => { + const service = new ABTestingService({ rerankEnabledPct: 50 }); + + // Generate many session IDs and check distribution + const sessionIds = Array.from({ length: 100 }, (_, i) => `session-${i}`); + const assignments = sessionIds.map((id) => service.assign(id)); + + // Should have mix of control and treatment + const treatmentCount = assignments.filter((a) => a.variant === "treatment").length; + const controlCount = assignments.filter((a) => a.variant === "control").length; + + // With 50% rollout, expect roughly 50/50 split (allow some variance) + expect(treatmentCount).toBeGreaterThan(30); + expect(treatmentCount).toBeLessThan(70); + expect(controlCount).toBeGreaterThan(30); + expect(controlCount).toBeLessThan(70); + expect(treatmentCount + controlCount).toBe(100); + }); + + it("should respect rollout percentage", () => { + const service = new ABTestingService({ rerankEnabledPct: 20 }); // 20% rollout + + // Generate many sessions + const sessionIds = Array.from({ length: 1000 }, (_, i) => `session-${i}`); + const assignments = sessionIds.map((id) => service.assign(id)); + + const treatmentCount = assignments.filter((a) => a.rerankEnabled).length; + const treatmentPct = (treatmentCount / 1000) * 100; + + // Should be close to 20% (allow 5% variance) + expect(treatmentPct).toBeGreaterThan(15); + expect(treatmentPct).toBeLessThan(25); + }); + + it("should assign treatment variant when rerankEnabled is true", () => { + const service = new ABTestingService({ rerankEnabledPct: 100 }); // 100% rollout + + const assignment = service.assign("any-session"); + + expect(assignment.variant).toBe("treatment"); + expect(assignment.rerankEnabled).toBe(true); + }); + + it("should assign control variant when rerankEnabled is false", () => { + const service = new ABTestingService({ rerankEnabledPct: 0 }); // 0% rollout + + const assignment = service.assign("any-session"); + + expect(assignment.variant).toBe("control"); + expect(assignment.rerankEnabled).toBe(false); + }); + + it("should map sessions to buckets 0-99", () => { + const service = new ABTestingService({ rerankEnabledPct: 50 }); + + const sessionIds = Array.from({ length: 100 }, (_, i) => `session-${i}`); + const assignments = sessionIds.map((id) => service.assign(id)); + + // Check all buckets are in valid range + for (const assignment of assignments) { + expect(assignment.bucket).toBeGreaterThanOrEqual(0); + expect(assignment.bucket).toBeLessThan(100); + } + + // Check we have good distribution across buckets + const buckets = new Set(assignments.map((a) => a.bucket)); + expect(buckets.size).toBeGreaterThan(50); // Should use many different buckets + }); + }); + + describe("Tier Override", () => { + it("should apply tier override when configured", () => { + const service = new ABTestingService({ + rerankEnabledPct: 50, + rerankTierOverride: "accurate", + }); + + const assignment = service.assign("test-session"); + + if (assignment.rerankEnabled) { + expect(assignment.rerankTier).toBe("accurate"); + } + }); + + it("should not set tier when no override", () => { + const service = new ABTestingService({ + rerankEnabledPct: 100, + }); + + const assignment = service.assign("test-session"); + + expect(assignment.rerankTier).toBeUndefined(); + }); + + it("should update tier override dynamically", () => { + const service = new ABTestingService({ + rerankEnabledPct: 100, + }); + + // Initially no override + let assignment = service.assign("test-session"); + expect(assignment.rerankTier).toBeUndefined(); + + // Set override + service.setTierOverride("code"); + assignment = service.assign("test-session"); + expect(assignment.rerankTier).toBe("code"); + + // Clear override + service.setTierOverride(undefined); + assignment = service.assign("test-session"); + expect(assignment.rerankTier).toBeUndefined(); + }); + }); + + describe("Rollout Percentage Updates", () => { + it("should update rollout percentage dynamically", () => { + const service = new ABTestingService({ rerankEnabledPct: 0 }); + + // Initially 0% - should be control + let assignment = service.assign("test-session"); + expect(assignment.rerankEnabled).toBe(false); + + // Update to 100% + service.setRolloutPercentage(100); + + // Now should be treatment + assignment = service.assign("test-session"); + expect(assignment.rerankEnabled).toBe(true); + }); + + it("should clamp rollout percentage to 0-100", () => { + const service = new ABTestingService({ rerankEnabledPct: 50 }); + + // Try to set negative + service.setRolloutPercentage(-10); + const config1 = service.getConfig(); + expect(config1.rerankEnabledPct).toBe(0); + + // Try to set above 100 + service.setRolloutPercentage(150); + const config2 = service.getConfig(); + expect(config2.rerankEnabledPct).toBe(100); + }); + }); + + describe("Helper Methods", () => { + it("should check if session is in treatment", () => { + const service = new ABTestingService({ rerankEnabledPct: 100 }); + + expect(service.isInTreatment("test-session")).toBe(true); + expect(service.isInControl("test-session")).toBe(false); + }); + + it("should check if session is in control", () => { + const service = new ABTestingService({ rerankEnabledPct: 0 }); + + expect(service.isInTreatment("test-session")).toBe(false); + expect(service.isInControl("test-session")).toBe(true); + }); + }); + + describe("Bucket Distribution Analysis", () => { + it("should analyze bucket distribution correctly", () => { + const service = new ABTestingService({ rerankEnabledPct: 30 }); + + const sessionIds = Array.from({ length: 100 }, (_, i) => `session-${i}`); + const analysis = service.analyzeBucketDistribution(sessionIds); + + expect(analysis.treatment + analysis.control).toBe(100); + expect(Object.keys(analysis.bucketCounts).length).toBeGreaterThan(0); + + // With 30% rollout, expect roughly 30 in treatment + expect(analysis.treatment).toBeGreaterThan(20); + expect(analysis.treatment).toBeLessThan(40); + }); + + it("should count buckets correctly", () => { + const service = new ABTestingService({ rerankEnabledPct: 50 }); + + // Use same session multiple times + const sessionIds = ["session-1", "session-1", "session-1"]; + const analysis = service.analyzeBucketDistribution(sessionIds); + + // Same session should map to same bucket + const buckets = Object.keys(analysis.bucketCounts); + expect(buckets.length).toBe(1); // Only one unique bucket + expect(analysis.bucketCounts[Number(buckets[0])]).toBe(3); // Count of 3 + }); + }); + + describe("Custom Seed", () => { + it("should produce different distributions with different seeds", () => { + const service1 = new ABTestingService({ + rerankEnabledPct: 50, + seed: "seed-a", + }); + + const service2 = new ABTestingService({ + rerankEnabledPct: 50, + seed: "seed-b", + }); + + const sessionId = "test-session"; + + const assignment1 = service1.assign(sessionId); + const assignment2 = service2.assign(sessionId); + + // Different seeds should produce different buckets + // (not guaranteed but highly likely with good hash) + // We test with multiple sessions to be sure + const sessionIds = Array.from({ length: 10 }, (_, i) => `session-${i}`); + + let differentCount = 0; + for (const id of sessionIds) { + const a1 = service1.assign(id); + const a2 = service2.assign(id); + if (a1.bucket !== a2.bucket) { + differentCount++; + } + } + + // At least some should be different + expect(differentCount).toBeGreaterThan(0); + }); + + it("should produce same distribution with same seed", () => { + const service1 = new ABTestingService({ + rerankEnabledPct: 50, + seed: "same-seed", + }); + + const service2 = new ABTestingService({ + rerankEnabledPct: 50, + seed: "same-seed", + }); + + const sessionIds = Array.from({ length: 10 }, (_, i) => `session-${i}`); + + for (const id of sessionIds) { + const a1 = service1.assign(id); + const a2 = service2.assign(id); + + // Same seed should produce identical assignments + expect(a1.bucket).toBe(a2.bucket); + expect(a1.variant).toBe(a2.variant); + } + }); + }); + + describe("Default Configuration", () => { + it("should use 100% rollout by default", () => { + const service = new ABTestingService(); + const config = service.getConfig(); + + expect(config.rerankEnabledPct).toBe(100); + }); + + it("should have default seed", () => { + const service = new ABTestingService(); + const config = service.getConfig(); + + expect(config.seed).toBe("engram-rerank-rollout-v1"); + }); + }); + + describe("Request Recording", () => { + it("should record search requests", () => { + const service = new ABTestingService({ rerankEnabledPct: 50 }); + + // Should not throw + expect(() => service.recordRequest("session-1", "fast")).not.toThrow(); + expect(() => service.recordRequest("session-2", undefined)).not.toThrow(); + }); + }); +}); diff --git a/packages/search/src/services/ab-testing.ts b/packages/search/src/services/ab-testing.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe0572088785e9573f9af374e3f680e758f9e507 --- /dev/null +++ b/packages/search/src/services/ab-testing.ts @@ -0,0 +1,270 @@ +import { createHash } from "node:crypto"; +import { createLogger } from "@engram/logger"; +import { Counter, Gauge } from "prom-client"; +import type { RerankerTier } from "../models/schema"; + +/** + * A/B testing configuration for gradual reranker rollout. + * + * Features: + * - Percentage-based rollout (0-100%) + * - Consistent session assignment via hashing + * - Tier override for forced variant selection + * - Metrics tracking per variant + */ +export interface ABTestConfig { + /** Feature flag: percentage of users with reranking enabled (0-100) */ + rerankEnabledPct: number; + /** Tier override: force specific tier for testing */ + rerankTierOverride?: RerankerTier; + /** Seed for consistent hashing */ + seed?: string; +} + +/** + * Variant assignment result + */ +export interface VariantAssignment { + /** Variant ID (e.g., "control", "treatment") */ + variant: "control" | "treatment"; + /** Whether reranking is enabled for this variant */ + rerankEnabled: boolean; + /** Reranker tier to use (if enabled) */ + rerankTier?: RerankerTier; + /** Hash bucket (0-99) used for assignment */ + bucket: number; +} + +/** + * Prometheus metrics for A/B testing + */ +const variantAssignmentCounter = new Counter({ + name: "engram_ab_variant_assignments_total", + help: "Total variant assignments by session", + labelNames: ["variant", "rerank_enabled"], +}); + +const variantRequestCounter = new Counter({ + name: "engram_ab_variant_requests_total", + help: "Total search requests by variant", + labelNames: ["variant", "tier"], +}); + +const rolloutPercentageGauge = new Gauge({ + name: "engram_ab_rollout_percentage", + help: "Current rollout percentage for reranking", +}); + +/** + * ABTestingService manages feature flags and variant assignment for reranker rollout. + * + * Uses deterministic hashing to ensure: + * - Same session always gets same variant + * - Uniform distribution across sessions + * - Easy percentage-based rollout control + * + * Example usage: + * ```ts + * const abTest = new ABTestingService({ rerankEnabledPct: 50 }); + * const assignment = abTest.assign(sessionId); + * if (assignment.rerankEnabled) { + * // Use reranking + * } + * ``` + */ +export class ABTestingService { + private config: Required> & { + rerankTierOverride?: RerankerTier; + }; + private logger = createLogger({ component: "ABTestingService" }); + + constructor(config: ABTestConfig = ABTestingService.defaultConfig()) { + this.config = { + rerankEnabledPct: Math.max(0, Math.min(100, config.rerankEnabledPct)), + rerankTierOverride: config.rerankTierOverride ?? undefined, + seed: config.seed ?? "engram-rerank-rollout-v1", + }; + + // Update rollout gauge + rolloutPercentageGauge.set(this.config.rerankEnabledPct); + + this.logger.info({ + msg: "A/B testing service initialized", + rerankEnabledPct: this.config.rerankEnabledPct, + rerankTierOverride: this.config.rerankTierOverride, + }); + } + + /** + * Default configuration: 100% rollout (reranking enabled for all) + */ + static defaultConfig(): ABTestConfig { + return { + rerankEnabledPct: 100, + seed: "engram-rerank-rollout-v1", + }; + } + + /** + * Assign a variant to a session. + * + * Uses deterministic hashing to ensure consistent assignment. + * Hash is computed from session ID + seed, then mapped to 0-99 bucket. + * + * @param sessionId - Unique session identifier + * @returns Variant assignment with rerank configuration + */ + assign(sessionId: string): VariantAssignment { + // Compute deterministic hash bucket (0-99) + const bucket = this.computeBucket(sessionId); + + // Check if session falls into treatment group + const rerankEnabled = bucket < this.config.rerankEnabledPct; + const variant = rerankEnabled ? "treatment" : "control"; + + // Apply tier override if configured + const assignment: VariantAssignment = { + variant, + rerankEnabled, + ...(this.config.rerankTierOverride && { rerankTier: this.config.rerankTierOverride }), + bucket, + }; + + // Record assignment + variantAssignmentCounter.inc({ + variant, + rerank_enabled: String(rerankEnabled), + }); + + this.logger.debug({ + msg: "Variant assigned", + sessionId, + variant, + rerankEnabled, + rerankTier: assignment.rerankTier, + bucket, + }); + + return assignment; + } + + /** + * Record a search request for metrics tracking. + * + * @param sessionId - Session identifier + * @param tier - Reranker tier used (if any) + */ + recordRequest(sessionId: string, tier?: RerankerTier): void { + const assignment = this.assign(sessionId); + variantRequestCounter.inc({ + variant: assignment.variant, + tier: tier ?? "none", + }); + } + + /** + * Update rollout percentage (hot reload). + * + * @param percentage - New percentage (0-100) + */ + setRolloutPercentage(percentage: number): void { + const newPct = Math.max(0, Math.min(100, percentage)); + const oldPct = this.config.rerankEnabledPct; + + this.config.rerankEnabledPct = newPct; + rolloutPercentageGauge.set(newPct); + + this.logger.info({ + msg: "Rollout percentage updated", + oldPct, + newPct, + }); + } + + /** + * Update tier override (hot reload). + * + * @param tier - Tier to force, or undefined to use routing + */ + setTierOverride(tier?: RerankerTier): void { + const oldTier = this.config.rerankTierOverride; + this.config.rerankTierOverride = tier; + + this.logger.info({ + msg: "Tier override updated", + oldTier, + newTier: tier, + }); + } + + /** + * Get current configuration. + */ + getConfig(): Readonly< + Required> & { rerankTierOverride?: RerankerTier } + > { + return { ...this.config }; + } + + /** + * Compute deterministic hash bucket (0-99) for a session. + * + * Uses MD5 hash of session ID + seed, then maps to 0-99 range. + */ + private computeBucket(sessionId: string): number { + const hash = createHash("md5").update(`${this.config.seed}:${sessionId}`).digest(); + + // Use first 4 bytes as uint32, then map to 0-99 + const value = hash.readUInt32BE(0); + return value % 100; + } + + /** + * Check if a session is in the treatment group (reranking enabled). + * + * @param sessionId - Session identifier + * @returns True if reranking should be enabled + */ + isInTreatment(sessionId: string): boolean { + return this.assign(sessionId).rerankEnabled; + } + + /** + * Check if a session is in the control group (reranking disabled). + * + * @param sessionId - Session identifier + * @returns True if reranking should be disabled + */ + isInControl(sessionId: string): boolean { + return !this.assign(sessionId).rerankEnabled; + } + + /** + * Get bucket distribution for analysis (debugging utility). + * + * @param sessionIds - List of session IDs to analyze + * @returns Distribution of buckets + */ + analyzeBucketDistribution(sessionIds: string[]): { + treatment: number; + control: number; + bucketCounts: Record; + } { + const bucketCounts: Record = {}; + let treatment = 0; + let control = 0; + + for (const sessionId of sessionIds) { + const assignment = this.assign(sessionId); + bucketCounts[assignment.bucket] = (bucketCounts[assignment.bucket] ?? 0) + 1; + + if (assignment.rerankEnabled) { + treatment++; + } else { + control++; + } + } + + return { treatment, control, bucketCounts }; + } +} diff --git a/packages/search/src/services/abstention-detector.test.ts b/packages/search/src/services/abstention-detector.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6cd421259a764010bfe50bb726f682f223331253 --- /dev/null +++ b/packages/search/src/services/abstention-detector.test.ts @@ -0,0 +1,553 @@ +import { describe, expect, it, vi } from "vitest"; +import type { SearchResult } from "../models/schema"; +import { + AbstentionDetector, + DEFAULT_ABSTENTION_CONFIG, + DEFAULT_HEDGING_PATTERNS, +} from "./abstention-detector"; + +/** + * Creates mock search results with specified scores + */ +function createResults(scores: number[]): SearchResult[] { + return scores.map((score, index) => ({ + id: `doc-${index}`, + score, + payload: { + content: `Test content ${index}`, + node_id: `node-${index}`, + session_id: "test-session", + type: "thought" as const, + timestamp: Date.now(), + }, + })); +} + +describe("AbstentionDetector", () => { + describe("constructor", () => { + it("uses default config when no config provided", () => { + const detector = new AbstentionDetector(); + const config = detector.getConfig(); + + expect(config.minRetrievalScore).toBe(DEFAULT_ABSTENTION_CONFIG.minRetrievalScore); + expect(config.minScoreGap).toBe(DEFAULT_ABSTENTION_CONFIG.minScoreGap); + expect(config.gapDetectionThreshold).toBe(DEFAULT_ABSTENTION_CONFIG.gapDetectionThreshold); + }); + + it("merges partial config with defaults", () => { + const detector = new AbstentionDetector({ minRetrievalScore: 0.5 }); + const config = detector.getConfig(); + + expect(config.minRetrievalScore).toBe(0.5); + expect(config.minScoreGap).toBe(DEFAULT_ABSTENTION_CONFIG.minScoreGap); + }); + }); + + describe("checkRetrievalConfidence", () => { + describe("no_results", () => { + it("abstains when no results", () => { + const detector = new AbstentionDetector(); + const result = detector.checkRetrievalConfidence([]); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("no_results"); + expect(result.confidence).toBe(1.0); + expect(result.details).toBe("No documents retrieved"); + }); + }); + + describe("low_retrieval_score", () => { + it("abstains when top score below threshold", () => { + const detector = new AbstentionDetector({ minRetrievalScore: 0.3 }); + const results = createResults([0.2, 0.15, 0.1]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("low_retrieval_score"); + expect(result.details).toContain("0.200"); + expect(result.details).toContain("threshold 0.3"); + }); + + it("does not abstain when top score meets threshold", () => { + const detector = new AbstentionDetector({ minRetrievalScore: 0.3 }); + const results = createResults([0.6, 0.5, 0.4]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBe(0.6); + }); + + it("does not abstain when top score exactly equals threshold with sufficient gap", () => { + // Use explicit config to ensure gap check passes (gap 0.2 > minScoreGap 0.1) + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + const results = createResults([0.3, 0.1, 0.05]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + }); + }); + + describe("no_score_gap", () => { + it("abstains when score gap too small and top score below gap threshold", () => { + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + // Top score 0.4, gap of 0.05 (below 0.1 threshold) + const results = createResults([0.4, 0.35, 0.3]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("no_score_gap"); + expect(result.details).toContain("0.050"); + }); + + it("does not check gap when top score above gap threshold", () => { + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + // Top score 0.6 (above 0.5 threshold), gap of 0.05 + const results = createResults([0.6, 0.55, 0.5]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBe(0.6); + }); + + it("does not abstain when score gap is sufficient", () => { + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + // Top score 0.45, gap of 0.15 (above 0.1 threshold) + const results = createResults([0.45, 0.3, 0.2]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + }); + + it("skips gap check with single result", () => { + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + const results = createResults([0.4]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBe(0.4); + }); + }); + + describe("confidence scoring", () => { + it("returns top score as confidence when not abstaining", () => { + const detector = new AbstentionDetector(); + const results = createResults([0.85, 0.6, 0.4]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBe(0.85); + }); + + it("returns inverse of top score as confidence for low_retrieval_score", () => { + const detector = new AbstentionDetector({ minRetrievalScore: 0.5 }); + const results = createResults([0.2, 0.1]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(true); + expect(result.confidence).toBe(0.8); // 1.0 - 0.2 + }); + + it("returns 0.7 confidence for no_score_gap", () => { + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + const results = createResults([0.4, 0.39]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("no_score_gap"); + expect(result.confidence).toBe(0.7); + }); + }); + }); + + describe("updateConfig", () => { + it("updates configuration at runtime", () => { + const detector = new AbstentionDetector({ minRetrievalScore: 0.3 }); + const results = createResults([0.25]); + + // Should abstain with 0.3 threshold + expect(detector.checkRetrievalConfidence(results).shouldAbstain).toBe(true); + + // Lower threshold + detector.updateConfig({ minRetrievalScore: 0.2 }); + + // Should not abstain with 0.2 threshold + expect(detector.checkRetrievalConfidence(results).shouldAbstain).toBe(false); + }); + }); + + describe("real-world scenarios", () => { + it("handles high-confidence retrieval (clear top result)", () => { + const detector = new AbstentionDetector(); + // Typical good retrieval: clear winner with high score + const results = createResults([0.92, 0.65, 0.55, 0.4, 0.35]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBe(0.92); + }); + + it("handles uncertain retrieval (multiple similar scores)", () => { + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + // Uncertain case: low scores, no clear winner + const results = createResults([0.42, 0.41, 0.4, 0.38, 0.35]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("no_score_gap"); + }); + + it("handles poor retrieval (no relevant docs)", () => { + const detector = new AbstentionDetector({ minRetrievalScore: 0.3 }); + // Poor retrieval: all scores very low + const results = createResults([0.15, 0.12, 0.08]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("low_retrieval_score"); + }); + + it("accepts medium confidence with clear winner", () => { + const detector = new AbstentionDetector({ + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + }); + // Medium confidence but clear winner: should proceed + const results = createResults([0.45, 0.25, 0.2]); + + const result = detector.checkRetrievalConfidence(results); + + expect(result.shouldAbstain).toBe(false); + }); + }); + + describe("checkHedgingPatterns (Layer 3)", () => { + it("detects 'I think' hedging pattern", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns("I think the answer might be 42."); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("hedging_detected"); + expect(result.details).toContain("I think"); + }); + + it("detects 'maybe' hedging pattern", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns("Maybe the meeting is at 3pm."); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("hedging_detected"); + expect(result.details).toContain("Maybe"); + }); + + it("detects 'I'm not sure' hedging pattern", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns( + "I'm not sure about this, but the event was in 2020.", + ); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("hedging_detected"); + expect(result.details).toContain("I'm not sure"); + }); + + it("detects 'cannot find' hedging pattern", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns( + "I cannot find any information about that topic.", + ); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("hedging_detected"); + expect(result.details).toContain("cannot find"); + }); + + it("detects 'no information' hedging pattern", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns( + "There is no information available on this subject.", + ); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("hedging_detected"); + expect(result.details).toContain("no information"); + }); + + it("detects 'it seems' hedging pattern", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns("It seems like the project started in January."); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("hedging_detected"); + expect(result.details).toContain("It seems"); + }); + + it("does not trigger on confident answers", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns("The meeting is scheduled for 3pm on Tuesday."); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBe(1.0); + }); + + it("does not trigger on assertive language", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns( + "The capital of France is Paris. This is a well-known fact.", + ); + + expect(result.shouldAbstain).toBe(false); + }); + + it("allows custom hedging patterns", () => { + const detector = new AbstentionDetector({ + hedgingPatterns: [/\bprobably\b/i], + }); + + // Custom pattern should trigger + const result1 = detector.checkHedgingPatterns("It's probably correct."); + expect(result1.shouldAbstain).toBe(true); + + // Default pattern should not trigger (replaced) + const result2 = detector.checkHedgingPatterns("I think this is correct."); + expect(result2.shouldAbstain).toBe(false); + }); + + it("returns 0.8 confidence for hedging detection", () => { + const detector = new AbstentionDetector(); + const result = detector.checkHedgingPatterns("Perhaps the answer is yes."); + + expect(result.shouldAbstain).toBe(true); + expect(result.confidence).toBe(0.8); + }); + }); + + describe("DEFAULT_HEDGING_PATTERNS", () => { + it("includes expected patterns", () => { + expect(DEFAULT_HEDGING_PATTERNS.length).toBeGreaterThan(5); + + // Verify key patterns exist + const patternStrings = DEFAULT_HEDGING_PATTERNS.map((p) => p.source); + expect(patternStrings.some((s) => s.includes("think"))).toBe(true); + expect(patternStrings.some((s) => s.includes("maybe"))).toBe(true); + expect(patternStrings.some((s) => s.includes("perhaps"))).toBe(true); + }); + }); + + describe("shouldAbstain (combined check)", () => { + it("abstains on Layer 1 failure (retrieval)", async () => { + const detector = new AbstentionDetector({ useNLI: false }); + const results = createResults([0.1]); // Low score + + const result = await detector.shouldAbstain(results, "Some answer", "Some context"); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("low_retrieval_score"); + }); + + it("abstains on Layer 3 failure (hedging) when Layer 1 passes", async () => { + const detector = new AbstentionDetector({ useNLI: false }); + const results = createResults([0.8, 0.4]); // Good retrieval + + const result = await detector.shouldAbstain( + results, + "I think the answer is 42.", + "Context here", + ); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("hedging_detected"); + }); + + it("proceeds when all layers pass", async () => { + const detector = new AbstentionDetector({ useNLI: false }); + const results = createResults([0.85, 0.5]); // Good retrieval + + const result = await detector.shouldAbstain( + results, + "The answer is 42.", // Confident answer + "The document states the answer is 42.", + ); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBe(0.85); + }); + + it("skips NLI when disabled", async () => { + const detector = new AbstentionDetector({ useNLI: false }); + const results = createResults([0.8]); + + // This would fail NLI (answer not grounded) but NLI is disabled + const result = await detector.shouldAbstain( + results, + "The sky is green.", // Hallucinated + "The document talks about weather patterns.", + ); + + // Should pass Layer 1 and Layer 3 (no hedging) + expect(result.shouldAbstain).toBe(false); + }); + }); + + describe("checkAnswerGrounding (Layer 2)", () => { + // Mock the pipeline for NLI tests + const mockPipeline = vi.fn(); + + it("abstains on contradiction", async () => { + // Create detector with mocked pipeline + const detector = new AbstentionDetector({ useNLI: true }); + + // Mock the pipeline method + mockPipeline.mockResolvedValueOnce({ + sequence: "test", + labels: ["contradiction", "neutral", "entailment"], + scores: [0.85, 0.1, 0.05], + }); + + // Access private method for testing (using type assertion) + const proto = Object.getPrototypeOf(detector); + proto.loadNLIPipeline = async () => mockPipeline; + + const result = await detector.checkAnswerGrounding( + "The capital of France is Berlin.", + "Paris is the capital of France.", + ); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("not_grounded"); + expect(result.details).toContain("contradiction"); + }); + + it("abstains on high-confidence neutral", async () => { + const detector = new AbstentionDetector({ + useNLI: true, + nliThreshold: 0.7, + }); + + mockPipeline.mockResolvedValueOnce({ + sequence: "test", + labels: ["neutral", "entailment", "contradiction"], + scores: [0.85, 0.1, 0.05], + }); + + const proto = Object.getPrototypeOf(detector); + proto.loadNLIPipeline = async () => mockPipeline; + + const result = await detector.checkAnswerGrounding( + "The meeting was productive.", + "We had a meeting yesterday.", + ); + + expect(result.shouldAbstain).toBe(true); + expect(result.reason).toBe("not_grounded"); + expect(result.details).toContain("neutral"); + }); + + it("proceeds on entailment", async () => { + const detector = new AbstentionDetector({ useNLI: true }); + + mockPipeline.mockResolvedValueOnce({ + sequence: "test", + labels: ["entailment", "neutral", "contradiction"], + scores: [0.92, 0.05, 0.03], + }); + + const proto = Object.getPrototypeOf(detector); + proto.loadNLIPipeline = async () => mockPipeline; + + const result = await detector.checkAnswerGrounding( + "Paris is the capital.", + "Paris is the capital of France.", + ); + + expect(result.shouldAbstain).toBe(false); + expect(result.confidence).toBeCloseTo(0.92); + }); + + it("proceeds on low-confidence neutral", async () => { + const detector = new AbstentionDetector({ + useNLI: true, + nliThreshold: 0.7, + }); + + mockPipeline.mockResolvedValueOnce({ + sequence: "test", + labels: ["neutral", "entailment", "contradiction"], + scores: [0.5, 0.35, 0.15], // Below threshold + }); + + const proto = Object.getPrototypeOf(detector); + proto.loadNLIPipeline = async () => mockPipeline; + + const result = await detector.checkAnswerGrounding("Some answer", "Some context"); + + expect(result.shouldAbstain).toBe(false); + }); + }); + + describe("NLI configuration", () => { + it("uses default NLI model", () => { + const detector = new AbstentionDetector(); + const config = detector.getConfig(); + + expect(config.nliModel).toBe("Xenova/mobilebert-uncased-mnli"); + }); + + it("allows custom NLI model", () => { + const detector = new AbstentionDetector({ + nliModel: "custom/nli-model", + }); + const config = detector.getConfig(); + + expect(config.nliModel).toBe("custom/nli-model"); + }); + + it("has NLI disabled by default", () => { + const detector = new AbstentionDetector(); + const config = detector.getConfig(); + + expect(config.useNLI).toBe(false); + }); + }); +}); diff --git a/packages/search/src/services/abstention-detector.ts b/packages/search/src/services/abstention-detector.ts new file mode 100644 index 0000000000000000000000000000000000000000..3dbc267216c034e7e167a37adb079d2b38efb938 --- /dev/null +++ b/packages/search/src/services/abstention-detector.ts @@ -0,0 +1,385 @@ +import type { SearchResult } from "../models/schema"; + +/** + * Configuration for abstention detection + */ +export interface AbstentionConfig { + /** Minimum retrieval score to proceed (default: 0.3) */ + minRetrievalScore: number; + /** Minimum score gap between top results for confident matching (default: 0.1) */ + minScoreGap: number; + /** Score threshold below which gap detection applies (default: 0.5) */ + gapDetectionThreshold: number; + /** Use NLI model for answer grounding check (default: false) */ + useNLI: boolean; + /** NLI entailment threshold - contradiction/neutral scores above this trigger abstention (default: 0.7) */ + nliThreshold: number; + /** NLI model to use for grounding check */ + nliModel: string; + /** Patterns that indicate hedging language (default: common hedging phrases) */ + hedgingPatterns: RegExp[]; +} + +/** + * Default hedging patterns that indicate uncertainty in answers. + * Based on common linguistic hedging markers. + */ +export const DEFAULT_HEDGING_PATTERNS: RegExp[] = [ + /\bI('m| am) not sure\b/i, + /\bI('m| am) uncertain\b/i, + /\bI don't know\b/i, + /\bI think\b/i, + /\bmaybe\b/i, + /\bpossibly\b/i, + /\bperhaps\b/i, + /\bcannot (find|determine|answer)\b/i, + /\bno (information|data|evidence)\b/i, + /\bnot (mentioned|specified|stated)\b/i, + /\bit (seems|appears)\b/i, + /\bto the best of my knowledge\b/i, + /\bif I recall correctly\b/i, +]; + +/** + * Default abstention configuration based on research findings + * @see https://arxiv.org/html/2509.07475 (HALT-RAG) + */ +export const DEFAULT_ABSTENTION_CONFIG: AbstentionConfig = { + minRetrievalScore: 0.3, + minScoreGap: 0.1, + gapDetectionThreshold: 0.5, + useNLI: false, + nliThreshold: 0.7, + nliModel: "Xenova/mobilebert-uncased-mnli", + hedgingPatterns: DEFAULT_HEDGING_PATTERNS, +}; + +/** + * Reason for abstaining from answering + */ +export type AbstentionReason = + | "no_results" + | "low_retrieval_score" + | "no_score_gap" + | "not_grounded" + | "hedging_detected"; + +/** + * Result of abstention detection + */ +export interface AbstentionResult { + /** Whether the system should abstain from answering */ + shouldAbstain: boolean; + /** Reason for abstention (if applicable) */ + reason?: AbstentionReason; + /** Confidence score (0-1, higher = more confident in decision) */ + confidence: number; + /** Human-readable explanation */ + details?: string; +} + +/** + * Result from NLI zero-shot classification + */ +interface NLIClassificationResult { + sequence: string; + labels: string[]; + scores: number[]; +} + +/** + * NLI pipeline function type + */ +type NLIPipeline = ( + text: string, + labels: string[], + options?: { multi_label?: boolean }, +) => Promise; + +/** + * AbstentionDetector implements a three-layer abstention system. + * + * Layer 1: Retrieval Confidence + * - Checks if retrieval scores are too low (no relevant documents found) + * - Checks if score gap is too small (uncertain which document is most relevant) + * + * Layer 2: Answer Grounding (NLI) + * - Uses Natural Language Inference to verify answer is entailed by context + * - Catches hallucinated answers not supported by retrieved documents + * + * Layer 3: Pattern Detection + * - Detects hedging language patterns in generated answers + * - Converts implicit uncertainty to explicit abstention + * + * @example + * ```typescript + * const detector = new AbstentionDetector({ useNLI: true }); + * + * // Layer 1: Check retrieval confidence + * const retrievalResult = detector.checkRetrievalConfidence(searchResults); + * + * // Layer 2: Check answer grounding (async) + * const groundingResult = await detector.checkAnswerGrounding(answer, context); + * + * // Layer 3: Check hedging patterns + * const hedgingResult = detector.checkHedgingPatterns(answer); + * + * // Combined check + * const shouldAbstain = await detector.shouldAbstain(searchResults, answer, context); + * ``` + */ +export class AbstentionDetector { + private config: AbstentionConfig; + private nliPipeline: NLIPipeline | null = null; + private nliLoadingPromise: Promise | null = null; + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_ABSTENTION_CONFIG, ...config }; + } + + /** + * Check if retrieval results indicate sufficient confidence to proceed. + * + * Implements two checks: + * 1. **Score threshold**: Top result must exceed minRetrievalScore + * 2. **Score gap**: When top score is below gapDetectionThreshold, + * the gap between top two results must exceed minScoreGap + * + * @param results - Search results with scores (should be sorted by score descending) + * @returns AbstentionResult indicating whether to abstain and why + */ + checkRetrievalConfidence(results: SearchResult[]): AbstentionResult { + // No results = abstain + if (results.length === 0) { + return { + shouldAbstain: true, + reason: "no_results", + confidence: 1.0, + details: "No documents retrieved", + }; + } + + const topScore = results[0].score; + + // Check minimum score threshold + if (topScore < this.config.minRetrievalScore) { + return { + shouldAbstain: true, + reason: "low_retrieval_score", + confidence: 1.0 - topScore, + details: `Top score ${topScore.toFixed(3)} below threshold ${this.config.minRetrievalScore}`, + }; + } + + // Check score gap for uncertain matches + // Only applies when top score is below the gap detection threshold + if (results.length >= 2 && topScore < this.config.gapDetectionThreshold) { + const scoreGap = topScore - results[1].score; + + if (scoreGap < this.config.minScoreGap) { + return { + shouldAbstain: true, + reason: "no_score_gap", + confidence: 0.7, + details: `Score gap ${scoreGap.toFixed(3)} below threshold ${this.config.minScoreGap} (uncertain match)`, + }; + } + } + + // Sufficient confidence to proceed + return { + shouldAbstain: false, + confidence: topScore, + }; + } + + /** + * Get the current configuration + */ + getConfig(): Readonly { + return this.config; + } + + /** + * Update configuration at runtime + */ + updateConfig(config: Partial): void { + this.config = { ...this.config, ...config }; + } + + /** + * Combined check of all three abstention layers. + * + * Runs checks in order and returns immediately if any layer triggers abstention: + * 1. Retrieval confidence (sync) + * 2. Answer grounding via NLI (async, if enabled) + * 3. Hedging pattern detection (sync) + * + * @param results - Search results from retrieval + * @param answer - Generated answer text + * @param context - Retrieved context used to generate the answer + * @returns AbstentionResult indicating whether to abstain and why + */ + async shouldAbstain( + results: SearchResult[], + answer: string, + context: string, + ): Promise { + // Layer 1: Retrieval confidence + const retrievalCheck = this.checkRetrievalConfidence(results); + if (retrievalCheck.shouldAbstain) { + return retrievalCheck; + } + + // Layer 2: Answer grounding (NLI) + if (this.config.useNLI) { + const groundingCheck = await this.checkAnswerGrounding(answer, context); + if (groundingCheck.shouldAbstain) { + return groundingCheck; + } + } + + // Layer 3: Hedging pattern detection + const hedgingCheck = this.checkHedgingPatterns(answer); + if (hedgingCheck.shouldAbstain) { + return hedgingCheck; + } + + // All checks passed - sufficient confidence to answer + return { + shouldAbstain: false, + confidence: retrievalCheck.confidence, + }; + } + + /** + * Layer 2: Check if the generated answer is grounded in the context. + * + * Uses Natural Language Inference (NLI) to classify the relationship + * between the context (premise) and answer (hypothesis): + * - **entailment**: Answer is supported by context → proceed + * - **contradiction**: Answer contradicts context → abstain + * - **neutral**: Answer not supported by context → abstain if high confidence + * + * @param answer - The generated answer to verify + * @param context - The retrieved context that should support the answer + * @returns AbstentionResult indicating whether the answer is grounded + */ + async checkAnswerGrounding(answer: string, context: string): Promise { + const pipeline = await this.loadNLIPipeline(); + + // NLI format: "premise. hypothesis" for zero-shot classification + // The model classifies whether the hypothesis is entailed by the premise + const inputText = `${context} ${answer}`; + + const result = await pipeline(inputText, ["entailment", "neutral", "contradiction"]); + + // Find the winning label and its score + const topLabel = result.labels[0]; + const topScore = result.scores[0]; + + // If contradiction or high-confidence neutral, abstain + if (topLabel === "contradiction") { + return { + shouldAbstain: true, + reason: "not_grounded", + confidence: topScore, + details: `Answer contradicts context (contradiction: ${topScore.toFixed(3)})`, + }; + } + + if (topLabel === "neutral" && topScore > this.config.nliThreshold) { + return { + shouldAbstain: true, + reason: "not_grounded", + confidence: topScore, + details: `Answer not supported by context (neutral: ${topScore.toFixed(3)})`, + }; + } + + // Entailment or low-confidence neutral - proceed + return { + shouldAbstain: false, + confidence: topLabel === "entailment" ? topScore : 1 - topScore, + }; + } + + /** + * Layer 3: Check if the answer contains hedging language patterns. + * + * Detects phrases that indicate the model is uncertain about its answer, + * such as "I think", "maybe", "not sure", etc. + * + * When hedging is detected, the answer should be converted to an explicit + * "I don't know" response rather than returning uncertain information. + * + * @param answer - The generated answer to check for hedging + * @returns AbstentionResult indicating whether hedging was detected + */ + checkHedgingPatterns(answer: string): AbstentionResult { + for (const pattern of this.config.hedgingPatterns) { + const match = pattern.exec(answer); + if (match) { + return { + shouldAbstain: true, + reason: "hedging_detected", + confidence: 0.8, + details: `Hedging pattern detected: "${match[0]}"`, + }; + } + } + + return { + shouldAbstain: false, + confidence: 1.0, + }; + } + + /** + * Lazy load the NLI pipeline. + * Uses singleton pattern to avoid loading the model multiple times. + */ + private async loadNLIPipeline(): Promise { + // Return cached pipeline if available + if (this.nliPipeline) { + return this.nliPipeline; + } + + // If already loading, wait for the existing promise + if (this.nliLoadingPromise) { + return this.nliLoadingPromise; + } + + // Start loading + this.nliLoadingPromise = this.initNLIPipeline(); + + try { + this.nliPipeline = await this.nliLoadingPromise; + return this.nliPipeline; + } finally { + this.nliLoadingPromise = null; + } + } + + /** + * Initialize the NLI pipeline from @huggingface/transformers. + */ + private async initNLIPipeline(): Promise { + const transformers = await import("@huggingface/transformers"); + const pipelineFn = transformers.pipeline as ( + task: string, + model: string, + ) => Promise; + return pipelineFn("zero-shot-classification", this.config.nliModel); + } + + /** + * Preload the NLI model for faster first inference. + * Call this during application startup if NLI is enabled. + */ + async preloadNLI(): Promise { + if (this.config.useNLI) { + await this.loadNLIPipeline(); + } + } +} diff --git a/packages/search/src/services/async-reranker.ts b/packages/search/src/services/async-reranker.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffef6b850c010aa14855658642d6125f70ceaf06 --- /dev/null +++ b/packages/search/src/services/async-reranker.ts @@ -0,0 +1,358 @@ +import { randomBytes } from "node:crypto"; +import { createLogger } from "@engram/logger"; +import type { BatchedReranker, BatchedRerankResult, DocumentCandidate } from "./batched-reranker"; + +const logger = createLogger({ component: "AsyncReranker" }); + +/** + * Options for async reranking operation. + */ +export interface AsyncRerankOptions { + /** Search query */ + query: string; + /** Documents to rerank */ + candidates: DocumentCandidate[]; + /** Number of top results to return */ + topK: number; + /** Callback when reranking completes */ + onComplete: (results: BatchedRerankResult[]) => void; + /** Optional callback for errors */ + onError?: (error: Error) => void; + /** Optional callback for progress updates */ + onProgress?: (progress: { processed: number; total: number }) => void; +} + +/** + * Status of an async reranking job. + */ +export type AsyncRerankStatus = "pending" | "running" | "completed" | "cancelled" | "failed"; + +/** + * Job metadata for tracking. + */ +interface RerankJob { + id: string; + status: AsyncRerankStatus; + query: string; + candidateCount: number; + startTime: number; + endTime?: number; + error?: Error; + cancelFn?: () => void; +} + +/** + * AsyncReranker enables background reranking with immediate RRF fallback. + * + * Use case: + * 1. Return RRF results immediately to user + * 2. Start reranking in background + * 3. Push refined results via WebSocket when ready + * + * Features: + * - Non-blocking reranking operations + * - Job tracking and status monitoring + * - Cancellable jobs + * - Progress callbacks + * - Error handling with fallback + */ +export class AsyncReranker { + private jobs: Map = new Map(); + private readonly maxConcurrentJobs: number; + private readonly jobRetentionMs: number; + private cleanupInterval?: NodeJS.Timeout; + + constructor( + private reranker: BatchedReranker, + options?: { + maxConcurrentJobs?: number; + jobRetentionMs?: number; + }, + ) { + this.maxConcurrentJobs = options?.maxConcurrentJobs ?? 10; + this.jobRetentionMs = options?.jobRetentionMs ?? 5 * 60 * 1000; // 5 minutes + + // Start periodic cleanup of old jobs + this.startCleanup(); + } + + /** + * Start background reranking. + * Returns immediately with job ID and cancel function. + * + * @param options - Reranking options with completion callback + * @returns Job ID and cancel function + */ + startAsync(options: AsyncRerankOptions): { jobId: string; cancel: () => void } { + const jobId = this.generateJobId(); + + // Check concurrent job limit + const runningJobs = Array.from(this.jobs.values()).filter( + (job) => job.status === "running" || job.status === "pending", + ); + + if (runningJobs.length >= this.maxConcurrentJobs) { + logger.warn({ + msg: "Max concurrent jobs reached, rejecting new job", + maxConcurrentJobs: this.maxConcurrentJobs, + currentJobs: runningJobs.length, + }); + + // Immediately call error callback + if (options.onError) { + options.onError(new Error("Max concurrent reranking jobs reached")); + } + + // Return a no-op cancel function + return { + jobId, + cancel: () => {}, + }; + } + + // Create job metadata + const job: RerankJob = { + id: jobId, + status: "pending", + query: options.query, + candidateCount: options.candidates.length, + startTime: Date.now(), + }; + + // Track whether job has been cancelled + let cancelled = false; + + // Create cancel function + const cancel = () => { + cancelled = true; + job.status = "cancelled"; + job.endTime = Date.now(); + + logger.info({ + msg: "Reranking job cancelled", + jobId, + query: options.query.substring(0, 50), + }); + }; + + job.cancelFn = cancel; + this.jobs.set(jobId, job); + + logger.info({ + msg: "Starting async reranking job", + jobId, + candidateCount: options.candidates.length, + topK: options.topK, + query: options.query.substring(0, 50), + }); + + // Start reranking in background (non-blocking) + this.executeReranking(job, options, () => cancelled).catch((error) => { + logger.error({ + msg: "Async reranking failed", + jobId, + error: error instanceof Error ? error.message : String(error), + }); + + // Update job status + job.status = "failed"; + job.endTime = Date.now(); + job.error = error instanceof Error ? error : new Error(String(error)); + + // Call error callback if provided + if (options.onError) { + options.onError(job.error); + } + }); + + return { jobId, cancel }; + } + + /** + * Check job status. + * + * @param jobId - Job identifier + * @returns Job status or undefined if not found + */ + getStatus(jobId: string): AsyncRerankStatus | undefined { + const job = this.jobs.get(jobId); + return job?.status; + } + + /** + * Get detailed job information. + * + * @param jobId - Job identifier + * @returns Job metadata or undefined if not found + */ + getJob(jobId: string): Readonly | undefined { + return this.jobs.get(jobId); + } + + /** + * Get all active jobs. + * + * @returns Array of active job metadata + */ + getActiveJobs(): ReadonlyArray> { + return Array.from(this.jobs.values()).filter( + (job) => job.status === "running" || job.status === "pending", + ); + } + + /** + * Execute reranking in background. + * + * @param job - Job metadata + * @param options - Reranking options + * @param isCancelled - Function to check if job is cancelled + */ + private async executeReranking( + job: RerankJob, + options: AsyncRerankOptions, + isCancelled: () => boolean, + ): Promise { + // Check if cancelled before starting + if (isCancelled()) { + return; + } + + // Update status to running + job.status = "running"; + + try { + // Perform reranking + const results = await this.reranker.rerank(options.query, options.candidates, options.topK); + + // Check if cancelled after reranking + if (isCancelled()) { + return; + } + + // Update job status + job.status = "completed"; + job.endTime = Date.now(); + + const durationMs = job.endTime - job.startTime; + + logger.info({ + msg: "Async reranking completed", + jobId: job.id, + durationMs, + resultCount: results.length, + }); + + // Call completion callback + options.onComplete(results); + } catch (error) { + // Update job status + job.status = "failed"; + job.endTime = Date.now(); + job.error = error instanceof Error ? error : new Error(String(error)); + + logger.error({ + msg: "Async reranking execution failed", + jobId: job.id, + error: error instanceof Error ? error.message : String(error), + }); + + throw error; + } + } + + /** + * Generate unique job ID. + */ + private generateJobId(): string { + return `rerank_${Date.now()}_${randomBytes(8).toString("hex")}`; + } + + /** + * Start periodic cleanup of old jobs. + */ + private startCleanup(): void { + // Clean up every minute + this.cleanupInterval = setInterval(() => { + this.cleanupOldJobs(); + }, 60 * 1000); + } + + /** + * Remove old completed/failed/cancelled jobs. + */ + private cleanupOldJobs(): void { + const now = Date.now(); + let removedCount = 0; + + for (const [jobId, job] of this.jobs.entries()) { + // Only clean up completed, failed, or cancelled jobs + if (job.status === "completed" || job.status === "failed" || job.status === "cancelled") { + const age = now - job.startTime; + if (age > this.jobRetentionMs) { + this.jobs.delete(jobId); + removedCount++; + } + } + } + + if (removedCount > 0) { + logger.debug({ + msg: "Cleaned up old reranking jobs", + removedCount, + remainingJobs: this.jobs.size, + }); + } + } + + /** + * Stop cleanup interval and clear all jobs. + * Should be called when shutting down. + */ + destroy(): void { + if (this.cleanupInterval) { + clearInterval(this.cleanupInterval); + } + this.jobs.clear(); + } +} + +/** + * Example usage with WebSocket integration: + * + * ```typescript + * // In search route handler: + * const asyncReranker = new AsyncReranker(reranker); + * + * if (params.asyncRerank) { + * // Return RRF results immediately + * const rrfResults = await performRRFFusion(denseResults, sparseResults); + * res.json({ + * results: rrfResults, + * rerankJobId: null, // Will be set after starting job + * }); + * + * // Start background reranking + * const { jobId, cancel } = asyncReranker.startAsync({ + * query, + * candidates: rrfResults, + * topK, + * onComplete: (reranked) => { + * // Push refined results via WebSocket + * wsServer.emit(sessionId, 'rerank-complete', { + * jobId, + * results: reranked, + * }); + * }, + * onError: (error) => { + * wsServer.emit(sessionId, 'rerank-error', { + * jobId, + * error: error.message, + * }); + * }, + * }); + * + * // Store cancel function if user leaves + * sessionCancelFunctions.set(sessionId, cancel); + * } + * ``` + */ diff --git a/packages/search/src/services/base-embedder.ts b/packages/search/src/services/base-embedder.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e1af935b0be55e68472801af1ce61ad39a9e239 --- /dev/null +++ b/packages/search/src/services/base-embedder.ts @@ -0,0 +1,365 @@ +/** + * Base Embedder - Abstract base class for all embedding implementations. + * + * This class extracts common patterns from TextEmbedder, CodeEmbedder, + * ColBERTEmbedder, and SpladeEmbedder to eliminate code duplication. + * + * Common patterns extracted: + * - Singleton instance management with lazy loading + * - Input validation + * - Vector normalization + * - Retry logic integration + * - Model preloading capability + * + * @module @engram/search/services/base-embedder + */ + +import { type RetryOptions, withRetry } from "@engram/common"; +import type { Logger } from "@engram/logger"; + +/** Supported dtype options for model loading */ +export type EmbedderDtype = "fp32" | "fp16" | "q8" | "q4"; + +/** Supported device options (matches transformers.js devices) */ +export type EmbedderDevice = "cpu" | "cuda" | "webgpu"; + +/** + * Base configuration for all embedders. + */ +export interface EmbedderConfig { + /** Model identifier (HuggingFace model name) */ + model: string; + /** Output embedding dimensions */ + dimensions: number; + /** Maximum input tokens (optional, for validation) */ + maxTokens?: number; + /** Batch size for batch operations */ + batchSize?: number; + /** Model precision (default: fp32 on CPU, fp16 on GPU) */ + dtype?: EmbedderDtype; + /** Device to run on (default: auto-detect CUDA on Linux x64 with GPU) */ + device?: EmbedderDevice; +} + +/** + * Detect if running in NVIDIA GPU environment. + * Checks for CUDA indicators commonly found in GPU instances. + * + * CUDA support in onnxruntime-node requires: + * - Linux x64 platform + * - CUDA 12.x installed + * - NVIDIA GPU with drivers + * + * @see https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html + */ +function detectCudaEnvironment(): boolean { + // Explicit env var override + if (process.env.EMBEDDER_DEVICE === "cuda") return true; + if (process.env.EMBEDDER_DEVICE === "cpu") return false; + + // Must be Linux x64 for CUDA support in onnxruntime-node + if (process.platform !== "linux" || process.arch !== "x64") { + return false; + } + + // Check for NVIDIA CUDA environment variables + if (process.env.CUDA_VISIBLE_DEVICES !== undefined) return true; + if (process.env.NVIDIA_VISIBLE_DEVICES !== undefined) return true; + + // Check for Cloud Run GPU environment + if (process.env.CLOUD_RUN_JOB && process.env.NVIDIA_DRIVER_CAPABILITIES) return true; + + // Check for common NVIDIA driver indicators + if (process.env.NVIDIA_DRIVER_CAPABILITIES) return true; + + return false; +} + +/** + * Get default device based on environment. + * Override with EMBEDDER_DEVICE env var (cpu, cuda, or webgpu). + * + * Auto-detection: + * - Linux x64 with NVIDIA GPU -> cuda + * - Otherwise -> cpu + */ +export function getDefaultDevice(): EmbedderDevice { + const envDevice = process.env.EMBEDDER_DEVICE as EmbedderDevice | undefined; + if (envDevice && ["cpu", "cuda", "webgpu"].includes(envDevice)) { + return envDevice; + } + return detectCudaEnvironment() ? "cuda" : "cpu"; +} + +/** + * Get default dtype based on environment. + * Override with EMBEDDER_DTYPE env var. + * Defaults to fp16 on CUDA (faster), fp32 on CPU (most compatible). + */ +export function getDefaultDtype(): EmbedderDtype { + const envDtype = process.env.EMBEDDER_DTYPE as EmbedderDtype | undefined; + if (envDtype && ["fp32", "fp16", "q8", "q4"].includes(envDtype)) { + return envDtype; + } + // Use fp16 on CUDA for speed, fp32 on CPU for compatibility + return detectCudaEnvironment() ? "fp16" : "fp32"; +} + +/** + * Options for embedding operations. + */ +export interface EmbedOptions { + /** Whether to normalize the output vector */ + normalize?: boolean; + /** Pooling strategy */ + pooling?: "mean" | "cls" | "none"; + /** Prefix to prepend to input (e.g., "passage:", "query:") */ + prefix?: string; +} + +/** + * Sparse vector format compatible with Qdrant. + */ +export interface SparseVector { + indices: number[]; + values: number[]; +} + +/** + * Abstract base class for embedding implementations. + * + * Subclasses must implement: + * - `loadModel()`: Initialize the model instance + * - `embed()`: Generate embeddings for a single input + * + * Subclasses may override: + * - `embedBatch()`: Optimized batch embedding (default: sequential) + * - `preload()`: Pre-warm the model (default: calls loadModel) + * + * @template TConfig - Configuration type extending EmbedderConfig + * @template TOutput - Output type (number[] for dense, Float32Array[] for multi-vector, SparseVector for sparse) + */ +export abstract class BaseEmbedder< + TConfig extends EmbedderConfig = EmbedderConfig, + TOutput = number[], +> { + protected config: TConfig; + protected logger?: Logger; + + constructor(config: TConfig, logger?: Logger) { + this.config = config; + this.logger = logger; + } + + /** + * Generate embeddings for a single input. + * Must be implemented by subclasses. + */ + abstract embed(text: string): Promise; + + /** + * Load/initialize the model. + * Called lazily on first use or explicitly via preload(). + */ + protected abstract loadModel(): Promise; + + /** + * Generate embeddings for multiple inputs. + * Default implementation processes sequentially. + * Subclasses can override for optimized batch processing. + */ + async embedBatch(texts: string[]): Promise { + const results: TOutput[] = []; + for (const text of texts) { + results.push(await this.embed(text)); + } + return results; + } + + /** + * Pre-load the model for faster first embedding. + * Useful for warming up during application startup. + */ + async preload(): Promise { + await this.loadModel(); + } + + /** + * Execute a function with retry logic and exponential backoff. + * Wraps @engram/common withRetry for embedder-specific defaults. + */ + protected async withRetry(fn: () => Promise, options?: RetryOptions): Promise { + return withRetry(fn, { + maxRetries: 3, + initialDelayMs: 1000, + maxDelayMs: 10000, + onRetry: (error, attempt, delayMs) => { + this.logger?.warn({ + msg: "Embedding retry", + attempt, + delayMs, + error: error instanceof Error ? error.message : String(error), + }); + }, + ...options, + }); + } + + /** + * Validate input text before embedding. + * Throws on empty input, warns on potential token limit exceeded. + */ + protected validateInput(text: string): void { + if (!text || text.trim().length === 0) { + throw new Error("Input text cannot be empty"); + } + // Rough estimate: 1 token ~= 4 characters for English text + if (this.config.maxTokens && text.length > this.config.maxTokens * 4) { + this.logger?.warn({ + msg: "Input may exceed token limit", + inputLength: text.length, + maxTokens: this.config.maxTokens, + estimatedTokens: Math.ceil(text.length / 4), + }); + } + } + + /** + * L2 normalize a vector for cosine similarity. + * Returns the original vector if magnitude is zero. + */ + protected normalizeVector(vector: number[]): number[] { + const magnitude = Math.sqrt(vector.reduce((sum, v) => sum + v * v, 0)); + return magnitude > 0 ? vector.map((v) => v / magnitude) : vector; + } + + /** + * L2 normalize a Float32Array in place for efficiency. + * Returns the same array mutated. + */ + protected normalizeFloat32Array(vector: Float32Array): Float32Array { + let sumSquares = 0; + for (let i = 0; i < vector.length; i++) { + sumSquares += vector[i] * vector[i]; + } + const magnitude = Math.sqrt(sumSquares); + if (magnitude > 0) { + for (let i = 0; i < vector.length; i++) { + vector[i] /= magnitude; + } + } + return vector; + } + + /** + * Average multiple embeddings into one and normalize. + * Used for combining chunk embeddings (e.g., in CodeEmbedder). + */ + protected averageEmbeddings(embeddings: number[][]): number[] { + if (embeddings.length === 0) return []; + if (embeddings.length === 1) return embeddings[0]; + + const dim = embeddings[0].length; + const avg = new Array(dim).fill(0); + + for (const emb of embeddings) { + for (let i = 0; i < dim; i++) { + avg[i] += emb[i]; + } + } + + // Average + for (let i = 0; i < dim; i++) { + avg[i] /= embeddings.length; + } + + // L2 normalize + return this.normalizeVector(avg); + } +} + +/** + * Abstract base class for dense embedders using HuggingFace pipeline. + * Provides singleton pattern for model instance management. + * + * @template TConfig - Configuration type extending EmbedderConfig + */ +export abstract class BasePipelineEmbedder< + TConfig extends EmbedderConfig = EmbedderConfig, +> extends BaseEmbedder { + /** + * Type definition for HuggingFace feature extraction function. + */ + protected static extractorType: ( + text: string, + opts: { pooling: string; normalize: boolean }, + ) => Promise<{ data: Float32Array }>; + + /** + * Get the singleton model instance. + * Must be implemented by subclasses to manage their specific singleton. + */ + protected abstract getInstance(): Promise; + + /** + * Call the embedding API with the configured options. + */ + protected async callEmbeddingAPI(text: string, options: EmbedOptions = {}): Promise { + const extractor = await this.getInstance(); + const pooling = options.pooling ?? "mean"; + const normalize = options.normalize ?? true; + const input = options.prefix ? `${options.prefix} ${text}` : text; + + const output = await extractor(input, { pooling, normalize }); + return Array.from(output.data); + } +} + +/** + * Abstract base class for multi-vector embedders (e.g., ColBERT). + * Returns token-level embeddings instead of pooled single vectors. + * + * @template TConfig - Configuration type extending EmbedderConfig + */ +export abstract class BaseMultiVectorEmbedder< + TConfig extends EmbedderConfig = EmbedderConfig, +> extends BaseEmbedder { + /** Token embedding dimension (e.g., 128 for ColBERT) */ + protected tokenDimension: number; + + constructor(config: TConfig, tokenDimension: number, logger?: Logger) { + super(config, logger); + this.tokenDimension = tokenDimension; + } + + /** + * Split a flat Float32Array into per-token embeddings. + */ + protected splitIntoTokenEmbeddings(data: Float32Array): Float32Array[] { + const numTokens = data.length / this.tokenDimension; + const tokenEmbeddings: Float32Array[] = []; + + for (let i = 0; i < numTokens; i++) { + const start = i * this.tokenDimension; + const end = start + this.tokenDimension; + tokenEmbeddings.push(data.slice(start, end) as Float32Array); + } + + return tokenEmbeddings; + } +} + +/** + * Abstract base class for sparse embedders (e.g., SPLADE). + * Returns sparse vectors with indices and values. + * + * @template TConfig - Configuration type extending EmbedderConfig + */ +export abstract class BaseSparseEmbedder< + TConfig extends EmbedderConfig = EmbedderConfig, +> extends BaseEmbedder { + /** + * Check if the model is loaded and ready. + */ + abstract isReady(): boolean; +} diff --git a/packages/search/src/services/batch-indexer.test.ts b/packages/search/src/services/batch-indexer.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d70c8c9611baecd2bd28ef25b7f77eca3ecff0e --- /dev/null +++ b/packages/search/src/services/batch-indexer.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from "vitest"; +import { BatchIndexer } from "./batch-indexer"; +import type { SearchIndexer } from "./indexer"; + +describe("BatchIndexer", () => { + it("should buffer items and flush on limit", async () => { + const mockIndexNode = vi.fn(async () => {}); + const mockIndexer = { + indexNode: mockIndexNode, + } as unknown as SearchIndexer; + + const batcher = new BatchIndexer(mockIndexer, { batchSize: 2 }); + + // Add 1 - buffer + batcher.add({ id: "1" } as any); + expect(mockIndexNode).not.toHaveBeenCalled(); + + // Add 2 - flush + batcher.add({ id: "2" } as any); + + // Wait for p-queue (async processing) + // Since we didn't mock p-queue, it runs immediately or on microtask + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(mockIndexNode).toHaveBeenCalledTimes(2); + }); + + it("should flush on timeout", async () => { + const mockIndexNode = vi.fn(async () => {}); + const mockIndexer = { + indexNode: mockIndexNode, + } as unknown as SearchIndexer; + + // Short interval + const batcher = new BatchIndexer(mockIndexer, { batchSize: 10, flushInterval: 50 }); + + batcher.add({ id: "1" } as any); + expect(mockIndexNode).not.toHaveBeenCalled(); + + await new Promise((resolve) => setTimeout(resolve, 100)); + + expect(mockIndexNode).toHaveBeenCalledTimes(1); + }); + + it("should flush on shutdown", async () => { + const mockIndexNode = vi.fn(async () => {}); + const mockIndexer = { + indexNode: mockIndexNode, + } as unknown as SearchIndexer; + + const batcher = new BatchIndexer(mockIndexer, { batchSize: 10 }); + + batcher.add({ id: "1" } as any); + + await batcher.shutdown(); + + expect(mockIndexNode).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/search/src/services/batch-indexer.ts b/packages/search/src/services/batch-indexer.ts new file mode 100644 index 0000000000000000000000000000000000000000..e2dc77376e793d7e3ac43d7a7025d86abf95a225 --- /dev/null +++ b/packages/search/src/services/batch-indexer.ts @@ -0,0 +1,63 @@ +import PQueue from "p-queue"; +import type { IndexableNode, SearchIndexer } from "./indexer"; + +export class BatchIndexer { + private queue: PQueue; + private buffer: IndexableNode[] = []; + private batchSize: number; + private flushInterval: number; + private timer: NodeJS.Timeout | null = null; + + constructor( + private indexer: SearchIndexer, + options: { batchSize?: number; concurrency?: number; flushInterval?: number } = {}, + ) { + this.batchSize = options.batchSize || 32; + this.flushInterval = options.flushInterval || 5000; // 5 seconds + this.queue = new PQueue({ concurrency: options.concurrency || 4 }); + } + + public add(node: IndexableNode) { + this.buffer.push(node); + if (this.buffer.length >= this.batchSize) { + // Fire-and-forget with explicit error handling to prevent unhandled rejections + void this.flush().catch((err) => { + console.error("[BatchIndexer] Background flush failed:", err); + }); + } else if (!this.timer) { + this.timer = setTimeout(() => { + void this.flush().catch((err) => { + console.error("[BatchIndexer] Scheduled flush failed:", err); + }); + }, this.flushInterval); + } + } + + private async flush() { + if (this.buffer.length === 0) return; + + // Swap buffer + const batch = [...this.buffer]; + this.buffer = []; + + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + + await this.queue.add(async () => { + console.log(`[BatchIndexer] Processing batch of ${batch.length} items`); + // TODO: Implement bulk indexNode in Indexer for efficiency + // For V1, we iterate in parallel up to Qdrant limits (handled by indexNode or queue here) + // Actually, Qdrant supports batch upsert. We should extend Indexer to support batching. + // But for now, we just map. + await Promise.all(batch.map((node) => this.indexer.indexNode(node))); + }); + } + + public async shutdown() { + if (this.timer) clearTimeout(this.timer); + await this.flush(); + await this.queue.onIdle(); + } +} diff --git a/packages/search/src/services/batched-reranker.test.ts b/packages/search/src/services/batched-reranker.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..333c595a43ca6df073d92efb9d2a22661693dafa --- /dev/null +++ b/packages/search/src/services/batched-reranker.test.ts @@ -0,0 +1,264 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BatchedReranker, type DocumentCandidate } from "./batched-reranker"; + +// Mock the transformers pipeline +vi.mock("@huggingface/transformers", () => ({ + pipeline: vi.fn().mockResolvedValue( + vi.fn().mockImplementation(async (input: { text: string; text_pair: string }) => { + // Simulate scoring based on content length (just for testing) + const score = Math.min(1, input.text_pair.length / 100); + return [{ label: "LABEL_0", score }]; + }), + ), +})); + +describe("BatchedReranker", () => { + let reranker: BatchedReranker; + + beforeEach(() => { + reranker = new BatchedReranker({ + model: "test-model", + maxBatchSize: 4, + maxConcurrency: 2, + }); + }); + + afterEach(() => { + BatchedReranker.unloadAll(); + vi.clearAllMocks(); + }); + + describe("constructor", () => { + it("should use default options when none provided", () => { + const defaultReranker = new BatchedReranker(); + expect(defaultReranker.getModel()).toContain("MiniLM"); + }); + + it("should use provided options", () => { + const customReranker = new BatchedReranker({ + model: "custom-model", + }); + expect(customReranker.getModel()).toBe("custom-model"); + }); + }); + + describe("rerank()", () => { + it("should return empty array for empty documents", async () => { + const results = await reranker.rerank("test query", []); + expect(results).toEqual([]); + }); + + it("should rerank documents and return top K", async () => { + const documents: DocumentCandidate[] = [ + { id: "1", content: "short" }, + { id: "2", content: "a much longer document with more content" }, + { id: "3", content: "medium length content here" }, + ]; + + const results = await reranker.rerank("test query", documents, 2); + + expect(results).toHaveLength(2); + // Results should be sorted by score descending + expect(results[0].score).toBeGreaterThanOrEqual(results[1].score); + }); + + it("should preserve original document IDs", async () => { + const documents: DocumentCandidate[] = [ + { id: "doc-a", content: "first document" }, + { id: "doc-b", content: "second document" }, + ]; + + const results = await reranker.rerank("test query", documents); + + const ids = results.map((r) => r.id); + expect(ids).toContain("doc-a"); + expect(ids).toContain("doc-b"); + }); + + it("should include originalIndex in results", async () => { + const documents: DocumentCandidate[] = [ + { id: "1", content: "first" }, + { id: "2", content: "second" }, + ]; + + const results = await reranker.rerank("test query", documents); + + // Each result should have an originalIndex + for (const result of results) { + expect(typeof result.originalIndex).toBe("number"); + expect(result.originalIndex).toBeGreaterThanOrEqual(0); + } + }); + + it("should preserve original scores when provided", async () => { + const documents: DocumentCandidate[] = [ + { id: "1", content: "document one", score: 0.95 }, + { id: "2", content: "document two", score: 0.85 }, + ]; + + const results = await reranker.rerank("test query", documents); + + for (const result of results) { + expect(result.originalScore).toBeDefined(); + expect([0.95, 0.85]).toContain(result.originalScore); + } + }); + + it("should handle large document sets with batching", async () => { + const documents: DocumentCandidate[] = Array.from({ length: 20 }, (_, i) => ({ + id: `doc-${i}`, + content: `Document content ${i} with some text`, + })); + + const results = await reranker.rerank("test query", documents, 10); + + expect(results).toHaveLength(10); + }); + + it("should normalize scores to 0-1 range", async () => { + const documents: DocumentCandidate[] = [{ id: "1", content: "test document" }]; + + const results = await reranker.rerank("test query", documents); + + expect(results[0].score).toBeGreaterThanOrEqual(0); + expect(results[0].score).toBeLessThanOrEqual(1); + }); + }); + + describe("forTier()", () => { + it("should create reranker for fast tier", () => { + const fastReranker = BatchedReranker.forTier("fast"); + expect(fastReranker.getModel()).toContain("MiniLM"); + }); + + it("should create reranker for accurate tier", () => { + const accurateReranker = BatchedReranker.forTier("accurate"); + expect(accurateReranker.getModel()).toContain("bge-reranker"); + }); + + it("should create reranker for code tier", () => { + const codeReranker = BatchedReranker.forTier("code"); + expect(codeReranker.getModel()).toContain("jina"); + }); + }); + + describe("warmup()", () => { + it("should preload the model", async () => { + await reranker.warmup(); + // Second call should be instant (cached) + const start = Date.now(); + await reranker.warmup(); + const elapsed = Date.now() - start; + expect(elapsed).toBeLessThan(50); // Should be near-instant + }); + }); + + describe("unloadModel()", () => { + it("should unload a specific model", async () => { + await reranker.warmup(); + BatchedReranker.unloadModel("test-model", "q8"); + // Model should be unloaded (no direct way to verify, but shouldn't throw) + }); + }); + + describe("unloadAll()", () => { + it("should unload all models", async () => { + await reranker.warmup(); + BatchedReranker.unloadAll(); + // Should complete without error + }); + }); + + describe("concurrency control", () => { + it("should respect maxConcurrency limit", async () => { + let concurrentCount = 0; + let maxConcurrent = 0; + + // Create a mock that tracks concurrent executions + const { pipeline } = await import("@huggingface/transformers"); + (pipeline as any).mockResolvedValue( + vi.fn().mockImplementation(async (_input: { text: string; text_pair: string }) => { + concurrentCount++; + maxConcurrent = Math.max(maxConcurrent, concurrentCount); + // Simulate some async work + await new Promise((resolve) => setTimeout(resolve, 10)); + concurrentCount--; + return [{ label: "LABEL_0", score: 0.5 }]; + }), + ); + + const limitedReranker = new BatchedReranker({ + model: "test-model", + maxBatchSize: 2, + maxConcurrency: 2, + }); + + // Create enough documents to require multiple batches + const documents: DocumentCandidate[] = Array.from({ length: 10 }, (_, i) => ({ + id: `doc-${i}`, + content: `Document ${i}`, + })); + + await limitedReranker.rerank("test query", documents); + + // Should never exceed maxConcurrency (2 concurrent batches) + expect(maxConcurrent).toBeLessThanOrEqual(2); + }); + + it("should process all batches even with concurrency limit", async () => { + const processedBatches: number[] = []; + + const { pipeline } = await import("@huggingface/transformers"); + (pipeline as any).mockResolvedValue( + vi.fn().mockImplementation(async (_input: { text: string; text_pair: string }) => { + processedBatches.push(Date.now()); + await new Promise((resolve) => setTimeout(resolve, 5)); + return [{ label: "LABEL_0", score: 0.5 }]; + }), + ); + + const limitedReranker = new BatchedReranker({ + model: "test-model", + maxBatchSize: 2, + maxConcurrency: 1, // Only 1 concurrent batch + }); + + const documents: DocumentCandidate[] = Array.from({ length: 8 }, (_, i) => ({ + id: `doc-${i}`, + content: `Document ${i}`, + })); + + const results = await limitedReranker.rerank("test query", documents); + + // All documents should be processed + expect(results).toHaveLength(8); + }); + + it("should handle rapid promise completion without resource leaks", async () => { + const { pipeline } = await import("@huggingface/transformers"); + (pipeline as any).mockResolvedValue( + vi.fn().mockImplementation(async () => { + // Instant completion to stress test promise cleanup + return [{ label: "LABEL_0", score: 0.5 }]; + }), + ); + + const rapidReranker = new BatchedReranker({ + model: "test-model", + maxBatchSize: 1, + maxConcurrency: 3, + }); + + const documents: DocumentCandidate[] = Array.from({ length: 20 }, (_, i) => ({ + id: `doc-${i}`, + content: `Document ${i}`, + })); + + // Should complete without hanging (previous bug would cause infinite loop) + // Request all 20 results + const results = await rapidReranker.rerank("test query", documents, 20); + + expect(results).toHaveLength(20); + }); + }); +}); diff --git a/packages/search/src/services/batched-reranker.ts b/packages/search/src/services/batched-reranker.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0da247f641e36e9f810bcd7b1e6a6cbbfcccdfc --- /dev/null +++ b/packages/search/src/services/batched-reranker.ts @@ -0,0 +1,545 @@ +import { createLogger } from "@engram/logger"; +import { pipeline } from "@huggingface/transformers"; +import { RERANK_CONFIG } from "../config"; +import type { RerankerTier } from "../models/schema"; +import { recordRerankMetrics } from "./reranker-metrics"; + +export interface DocumentCandidate { + id: string | number; + content: string; + /** Original score from retrieval (RRF/dense/sparse) */ + score?: number; +} + +export interface BatchedRerankResult { + id: string | number; + /** Cross-encoder relevance score (0-1) */ + score: number; + /** Original position before reranking */ + originalIndex: number; + /** Original retrieval score */ + originalScore?: number; +} + +export interface BatchedRerankerOptions { + /** Model identifier */ + model?: string; + /** Maximum documents per batch */ + maxBatchSize?: number; + /** Maximum concurrent batches */ + maxConcurrency?: number; + /** Quantization level */ + quantization?: "fp16" | "q8"; + /** Enable query-document pair caching */ + cacheEnabled?: boolean; + /** Idle timeout in milliseconds before unloading model (default: 5 minutes) */ + idleTimeoutMs?: number; +} + +interface ClassifierOutput { + label: string; + score: number; +} + +type ClassifierFn = (input: { text: string; text_pair: string }) => Promise; + +/** + * BatchedReranker processes documents in parallel batches for efficiency. + * + * Key optimizations: + * - Dynamic batching based on document count + * - Concurrent batch processing with p-limit pattern + * - Singleton model instances per tier + * - Score normalization to 0-1 range + * - Lazy model loading with idle unload to prevent OOM + */ +export class BatchedReranker { + private static instances: Map = new Map(); + private static loadingPromises: Map> = new Map(); + private static idleTimers: Map = new Map(); + private static lastAccessTimes: Map = new Map(); + + private model: string; + private maxBatchSize: number; + private maxConcurrency: number; + private quantization: "fp16" | "q8"; + private cacheEnabled: boolean; + private logger = createLogger({ component: "BatchedReranker" }); + private tier?: RerankerTier; + private idleTimeoutMs: number; + + constructor(options: BatchedRerankerOptions = {}) { + this.model = options.model ?? RERANK_CONFIG.tiers.fast.model; + this.maxBatchSize = options.maxBatchSize ?? 16; + this.maxConcurrency = options.maxConcurrency ?? 4; + this.quantization = options.quantization ?? "q8"; + this.cacheEnabled = options.cacheEnabled ?? false; + this.idleTimeoutMs = options.idleTimeoutMs ?? 5 * 60 * 1000; // Default 5 minutes + } + + /** + * Get or create a singleton pipeline instance for the model. + * Implements lazy loading - model is only loaded on first use. + */ + private async getInstance(): Promise { + const key = `${this.model}:${this.quantization}`; + + // Update last access time + BatchedReranker.lastAccessTimes.set(key, Date.now()); + + // Reset idle timer on access + this.resetIdleTimer(key); + + // Return existing instance + if (BatchedReranker.instances.has(key)) { + this.logger.debug({ + msg: "Using cached model instance", + model: this.model, + quantization: this.quantization, + }); + const cached = BatchedReranker.instances.get(key); + if (cached) return cached; + } + + // Return existing loading promise to avoid duplicate loads + if (BatchedReranker.loadingPromises.has(key)) { + this.logger.debug({ + msg: "Waiting for model to load", + model: this.model, + quantization: this.quantization, + }); + const loading = BatchedReranker.loadingPromises.get(key); + if (loading) return loading; + } + + // Create new loading promise (lazy loading) + this.logger.info({ + msg: "Loading model (lazy initialization)", + model: this.model, + quantization: this.quantization, + }); + + const loadStartTime = Date.now(); + + const loadingPromise = (async () => { + const pipelineInstance = await pipeline("text-classification", this.model, { + dtype: this.quantization === "q8" ? "q8" : "fp16", + }); + + // Wrap the pipeline as a classifier function + const classifier: ClassifierFn = async (input) => { + const result = await (pipelineInstance as unknown as ClassifierFn)(input); + return result; + }; + + BatchedReranker.instances.set(key, classifier); + BatchedReranker.loadingPromises.delete(key); + + const loadTime = Date.now() - loadStartTime; + + this.logger.info({ + msg: "Model loaded successfully", + model: this.model, + quantization: this.quantization, + loadTimeMs: loadTime, + }); + + return classifier; + })(); + + BatchedReranker.loadingPromises.set(key, loadingPromise); + return loadingPromise; + } + + /** + * Rerank documents by relevance to the query. + * + * @param query - The search query + * @param documents - Candidate documents to rerank + * @param topK - Number of top results to return + * @returns Reranked results sorted by relevance score + */ + async rerank( + query: string, + documents: DocumentCandidate[], + topK: number = 10, + ): Promise { + if (documents.length === 0) { + return []; + } + + const startTime = Date.now(); + const candidateCount = documents.length; + const tierLabel = this.tier ?? "unknown"; + + this.logger.info({ + msg: "Rerank started", + tier: tierLabel, + model: this.model, + candidateCount, + topK, + queryLength: query.length, + }); + + try { + const classifier = await this.getInstance(); + + // Split into batches + const batches = this.createBatches(documents); + + // Process batches with concurrency limit + const batchResults = await this.processBatchesConcurrently(classifier, query, batches); + + // Flatten and merge results + const allResults: BatchedRerankResult[] = []; + let globalIndex = 0; + + for (const batchResult of batchResults) { + for (const result of batchResult) { + allResults.push({ + ...result, + originalIndex: globalIndex++, + }); + } + } + + // Sort by score descending and take top K + allResults.sort((a, b) => b.score - a.score); + const topResults = allResults.slice(0, topK); + + // Calculate score statistics + const scores = topResults.map((r) => r.score); + const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length; + const maxScore = Math.max(...scores); + const minScore = Math.min(...scores); + + // Calculate score improvement if original scores exist + let scoreImprovement: number | undefined; + const hasOriginalScores = topResults.every((r) => r.originalScore !== undefined); + if (hasOriginalScores) { + const originalAvg = + topResults.reduce((sum, r) => sum + (r.originalScore ?? 0), 0) / topResults.length; + scoreImprovement = avgScore - originalAvg; + } + + const latencyMs = Date.now() - startTime; + const latencySeconds = latencyMs / 1000; + + this.logger.info({ + msg: "Rerank completed", + tier: tierLabel, + model: this.model, + candidateCount, + topK, + latencyMs, + avgScore: avgScore.toFixed(3), + maxScore: maxScore.toFixed(3), + minScore: minScore.toFixed(3), + scoreImprovement: scoreImprovement?.toFixed(3), + }); + + // Record metrics + recordRerankMetrics({ + tier: tierLabel, + model: this.model, + latencySeconds, + candidateCount, + scoreImprovement, + status: "success", + }); + + return topResults; + } catch (error) { + const latencyMs = Date.now() - startTime; + const latencySeconds = latencyMs / 1000; + + this.logger.error({ + msg: "Rerank failed", + tier: tierLabel, + model: this.model, + candidateCount, + latencyMs, + error: error instanceof Error ? error.message : String(error), + }); + + // Record failure metrics + recordRerankMetrics({ + tier: tierLabel, + model: this.model, + latencySeconds, + candidateCount, + status: "failure", + }); + + throw error; + } + } + + /** + * Split documents into batches for parallel processing. + */ + private createBatches(documents: DocumentCandidate[]): DocumentCandidate[][] { + const batches: DocumentCandidate[][] = []; + + for (let i = 0; i < documents.length; i += this.maxBatchSize) { + batches.push(documents.slice(i, i + this.maxBatchSize)); + } + + return batches; + } + + /** + * Process batches with concurrency limit using Promise pooling. + * Uses proper promise tracking with self-removal pattern. + */ + private async processBatchesConcurrently( + classifier: ClassifierFn, + query: string, + batches: DocumentCandidate[][], + ): Promise { + const results: BatchedRerankResult[][] = []; + const executing = new Set>(); + + for (const batch of batches) { + // Create promise that removes itself from executing set when done + const promise = this.processBatch(classifier, query, batch) + .then((result) => { + results.push(result); + }) + .finally(() => { + executing.delete(promise); + }); + + executing.add(promise); + + // If we've hit max concurrency, wait for one to complete + if (executing.size >= this.maxConcurrency) { + await Promise.race(executing); + } + } + + // Wait for remaining batches + if (executing.size > 0) { + await Promise.all(executing); + } + + return results; + } + + /** + * Process a single batch of documents. + */ + private async processBatch( + classifier: ClassifierFn, + query: string, + batch: DocumentCandidate[], + ): Promise { + const results: BatchedRerankResult[] = []; + + // Process each document in the batch + // Note: Some models support batch inference, but text-classification + // pipeline with pairs may need sequential processing + for (let i = 0; i < batch.length; i++) { + const doc = batch[i]; + + try { + const output = await classifier({ + text: query, + text_pair: doc.content, + }); + + // Extract score from classifier output + const score = this.extractScore(output); + + results.push({ + id: doc.id, + score, + originalIndex: i, + originalScore: doc.score, + }); + } catch (error) { + // On error, assign minimum score to push to bottom + console.warn(`[BatchedReranker] Failed to score document ${doc.id}:`, error); + results.push({ + id: doc.id, + score: 0, + originalIndex: i, + originalScore: doc.score, + }); + } + } + + return results; + } + + /** + * Extract normalized score from classifier output. + * Cross-encoders may output logits or probabilities. + */ + private extractScore(output: ClassifierOutput[]): number { + if (!output || output.length === 0) { + return 0; + } + + // BGE and similar rerankers output a single score + // Some models output [{ label: 'LABEL_0', score: 0.99 }] + // Others might output probabilities for positive class + const score = output[0].score; + + // Normalize to 0-1 range if needed + // Most cross-encoders output sigmoid scores already in 0-1 + return Math.max(0, Math.min(1, score)); + } + + /** + * Get the model name for this reranker. + */ + getModel(): string { + return this.model; + } + + /** + * Create a BatchedReranker for a specific tier. + */ + static forTier(tier: RerankerTier): BatchedReranker { + const config = RERANK_CONFIG.tiers[tier]; + const reranker = new BatchedReranker({ + model: config.model, + maxBatchSize: config.batchSize ?? 16, + quantization: "q8", + }); + reranker.tier = tier; + return reranker; + } + + /** + * Preload a model to avoid cold start latency. + */ + async warmup(): Promise { + await this.getInstance(); + } + + /** + * Unload model from memory. + */ + static unloadModel(model: string, quantization: "fp16" | "q8" = "q8"): void { + const key = `${model}:${quantization}`; + BatchedReranker.instances.delete(key); + } + + /** + * Unload all models from memory. + */ + static unloadAll(): void { + // Clear all idle timers + for (const timer of BatchedReranker.idleTimers.values()) { + clearTimeout(timer); + } + BatchedReranker.idleTimers.clear(); + BatchedReranker.lastAccessTimes.clear(); + BatchedReranker.instances.clear(); + } + + /** + * Reset idle timer for a model to prevent premature unloading. + * Called on each access to the model. + */ + private resetIdleTimer(key: string): void { + // Clear existing timer + const existingTimer = BatchedReranker.idleTimers.get(key); + if (existingTimer) { + clearTimeout(existingTimer); + } + + // Set new timer to unload after idle timeout + const timer = setTimeout(() => { + this.unloadIfIdle(key); + }, this.idleTimeoutMs); + + BatchedReranker.idleTimers.set(key, timer); + } + + /** + * Unload a model if it has been idle for the configured timeout. + * Logs model lifecycle events. + */ + private unloadIfIdle(key: string): void { + const lastAccess = BatchedReranker.lastAccessTimes.get(key); + const now = Date.now(); + + if (!lastAccess) { + // No access recorded, safe to unload + this.performUnload(key); + return; + } + + const idleTime = now - lastAccess; + + if (idleTime >= this.idleTimeoutMs) { + // Model has been idle long enough, unload it + this.performUnload(key); + } else { + // Model was accessed recently, reschedule unload + const remainingTime = this.idleTimeoutMs - idleTime; + this.logger.debug({ + msg: "Model still in use, rescheduling unload", + model: this.model, + idleTimeMs: idleTime, + remainingTimeMs: remainingTime, + }); + + const timer = setTimeout(() => { + this.unloadIfIdle(key); + }, remainingTime); + + BatchedReranker.idleTimers.set(key, timer); + } + } + + /** + * Perform the actual model unload and cleanup. + */ + private performUnload(key: string): void { + const wasLoaded = BatchedReranker.instances.has(key); + + if (wasLoaded) { + BatchedReranker.instances.delete(key); + BatchedReranker.lastAccessTimes.delete(key); + BatchedReranker.idleTimers.delete(key); + + this.logger.info({ + msg: "Model unloaded due to idle timeout", + model: this.model, + quantization: this.quantization, + idleTimeoutMs: this.idleTimeoutMs, + }); + } + } + + /** + * Get model load status for monitoring. + */ + static getLoadedModels(): Array<{ + key: string; + lastAccessTime: number | undefined; + idleTimeMs: number; + }> { + const now = Date.now(); + const loaded: Array<{ + key: string; + lastAccessTime: number | undefined; + idleTimeMs: number; + }> = []; + + for (const key of BatchedReranker.instances.keys()) { + const lastAccess = BatchedReranker.lastAccessTimes.get(key); + loaded.push({ + key, + lastAccessTime: lastAccess, + idleTimeMs: lastAccess ? now - lastAccess : 0, + }); + } + + return loaded; + } +} diff --git a/packages/search/src/services/cache-metrics.ts b/packages/search/src/services/cache-metrics.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c30eae8aeb65ec62215464865955865b0238504 --- /dev/null +++ b/packages/search/src/services/cache-metrics.ts @@ -0,0 +1,208 @@ +import { Counter, Gauge } from "prom-client"; + +/** + * Prometheus metrics for caching observability. + * + * These metrics enable monitoring of: + * - Cache hit/miss rates + * - Cache eviction frequency + * - Cache size and utilization + * - Cache performance by type (embedding vs query) + */ + +// ============================================================================= +// Embedding Cache Metrics +// ============================================================================= + +/** + * Embedding cache hits counter + * Tracks successful cache lookups for document embeddings + */ +export const embeddingCacheHits = new Counter({ + name: "engram_embedding_cache_hits_total", + help: "Total embedding cache hits", +}); + +/** + * Embedding cache misses counter + * Tracks failed cache lookups for document embeddings + */ +export const embeddingCacheMisses = new Counter({ + name: "engram_embedding_cache_misses_total", + help: "Total embedding cache misses", +}); + +/** + * Embedding cache evictions counter + * Tracks LRU evictions when cache size limit is reached + */ +export const embeddingCacheEvictions = new Counter({ + name: "engram_embedding_cache_evictions_total", + help: "Total embedding cache evictions", +}); + +/** + * Embedding cache size gauge + * Tracks current cache size in bytes + */ +export const embeddingCacheSize = new Gauge({ + name: "engram_embedding_cache_size_bytes", + help: "Current embedding cache size in bytes", +}); + +/** + * Embedding cache entry count gauge + * Tracks number of cached embeddings + */ +export const embeddingCacheCount = new Gauge({ + name: "engram_embedding_cache_entries_count", + help: "Current number of cached embeddings", +}); + +/** + * Embedding cache hit rate gauge + * Computed metric showing cache effectiveness (0-1) + */ +export const embeddingCacheHitRate = new Gauge({ + name: "engram_embedding_cache_hit_rate", + help: "Embedding cache hit rate (hits / total requests)", +}); + +// ============================================================================= +// Query Cache Metrics +// ============================================================================= + +/** + * Query cache hits counter + * Tracks successful cache lookups for reranked query results + */ +export const queryCacheHits = new Counter({ + name: "engram_query_cache_hits_total", + help: "Total query cache hits", +}); + +/** + * Query cache misses counter + * Tracks failed cache lookups for reranked query results + */ +export const queryCacheMisses = new Counter({ + name: "engram_query_cache_misses_total", + help: "Total query cache misses", +}); + +/** + * Query cache hit rate gauge + * Computed metric showing cache effectiveness (0-1) + * Target: 30%+ hit rate + */ +export const queryCacheHitRate = new Gauge({ + name: "engram_query_cache_hit_rate", + help: "Query cache hit rate (hits / total requests)", +}); + +/** + * Query cache errors counter + * Tracks Redis connection/operation errors + * Used to monitor graceful degradation + */ +export const queryCacheErrors = new Counter({ + name: "engram_query_cache_errors_total", + help: "Total query cache errors (Redis failures)", +}); + +// ============================================================================= +// Helper Functions +// ============================================================================= + +/** + * Compute hit rate from hits and misses. + * Returns 0 if no requests have been made. + */ +export function computeHitRate(hits: number, misses: number): number { + const total = hits + misses; + return total > 0 ? hits / total : 0; +} + +/** + * Update embedding cache metrics from cache stats. + * Should be called periodically or after cache operations. + */ +export function updateEmbeddingCacheMetrics(stats: { + hits: number; + misses: number; + evictions: number; + size: number; + count: number; +}): void { + // Set gauges + embeddingCacheSize.set(stats.size); + embeddingCacheCount.set(stats.count); + + // Compute and set hit rate + const hitRate = computeHitRate(stats.hits, stats.misses); + embeddingCacheHitRate.set(hitRate); + + // Note: Counters (hits, misses, evictions) are incremented + // directly in EmbeddingCache, not here +} + +/** + * Update query cache metrics from cache stats. + * Should be called periodically or after cache operations. + */ +export function updateQueryCacheMetrics(stats: { hits: number; misses: number }): void { + // Compute and set hit rate + const hitRate = computeHitRate(stats.hits, stats.misses); + queryCacheHitRate.set(hitRate); + + // Note: Counters (hits, misses, errors) are incremented + // directly in QueryCache, not here +} + +/** + * Record embedding cache hit. + * Call this from EmbeddingCache.get() on successful lookup. + */ +export function recordEmbeddingCacheHit(): void { + embeddingCacheHits.inc(); +} + +/** + * Record embedding cache miss. + * Call this from EmbeddingCache.get() on failed lookup. + */ +export function recordEmbeddingCacheMiss(): void { + embeddingCacheMisses.inc(); +} + +/** + * Record embedding cache eviction. + * Call this from EmbeddingCache when LRU eviction occurs. + */ +export function recordEmbeddingCacheEviction(): void { + embeddingCacheEvictions.inc(); +} + +/** + * Record query cache hit. + * Call this from QueryCache.get() on successful lookup. + */ +export function recordQueryCacheHit(): void { + queryCacheHits.inc(); +} + +/** + * Record query cache miss. + * Call this from QueryCache.get() on failed lookup. + */ +export function recordQueryCacheMiss(): void { + queryCacheMisses.inc(); +} + +/** + * Record query cache error. + * Call this from QueryCache when Redis operations fail. + */ +export function recordQueryCacheError(): void { + queryCacheErrors.inc(); +} diff --git a/packages/search/src/services/classifier.test.ts b/packages/search/src/services/classifier.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0dcf1695819e79970602c706c87890b47f4829f --- /dev/null +++ b/packages/search/src/services/classifier.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; +import { QueryClassifier, SearchStrategy } from "./classifier"; + +describe("QueryClassifier", () => { + const classifier = new QueryClassifier(); + + it("should classify quoted strings as sparse", () => { + const result = classifier.classify('Find "exact phrase"'); + expect(result.strategy).toBe(SearchStrategy.Sparse); + expect(result.alpha).toBeLessThan(0.5); + }); + + it("should classify code-like syntax as hybrid leaning sparse", () => { + const result = classifier.classify("console.log('hello')"); + expect(result.strategy).toBe(SearchStrategy.Hybrid); + expect(result.alpha).toBe(0.3); + }); + + it("should classify natural language as hybrid leaning dense", () => { + const result = classifier.classify("how to implement login"); + expect(result.strategy).toBe(SearchStrategy.Hybrid); + expect(result.alpha).toBe(0.7); + }); +}); diff --git a/packages/search/src/services/classifier.ts b/packages/search/src/services/classifier.ts new file mode 100644 index 0000000000000000000000000000000000000000..b07e6ae515edd63a4b847add91215c63dda27adc --- /dev/null +++ b/packages/search/src/services/classifier.ts @@ -0,0 +1,124 @@ +export enum SearchStrategy { + Sparse = "sparse", + Dense = "dense", + Hybrid = "hybrid", +} + +/** Query complexity level for reranker routing */ +export type QueryComplexity = "simple" | "moderate" | "complex"; + +/** Features extracted from a query for classification */ +export interface QueryFeatures { + length: number; + wordCount: number; + hasQuotes: boolean; + hasOperators: boolean; + hasCode: boolean; + isQuestion: boolean; + hasAgentic: boolean; +} + +export class QueryClassifier { + classify(query: string): { strategy: SearchStrategy; alpha: number } { + // Heuristic: + // 1. Quoted strings imply exact match intent -> Sparse + // 2. Code-like patterns (camelCase, snake_case with parens) -> Sparse/Hybrid + // 3. Natural language -> Dense/Hybrid + + const quoted = query.match(/"([^"]*)"/g); + if (quoted && quoted.length > 0) { + // Strong signal for exact match + return { strategy: SearchStrategy.Sparse, alpha: 0.1 }; // Alpha 0.1 = mostly sparse (if using reciprocal rank fusion where 0 is sparse, 1 is dense. Convention varies.) + // Let's assume alpha is weight for Dense. So 0.1 means 10% dense, 90% sparse. + } + + // Simple code detection + const hasCodeSyntax = /[a-zA-Z0-9_]+\(.*\)|[a-zA-Z0-9_]+\.[a-zA-Z0-9_]+/.test(query); + if (hasCodeSyntax) { + return { strategy: SearchStrategy.Hybrid, alpha: 0.3 }; // Lean towards sparse + } + + // Default: Hybrid leaning dense + return { strategy: SearchStrategy.Hybrid, alpha: 0.7 }; + } + + /** + * Extract features from a query for complexity analysis. + */ + extractFeatures(query: string): QueryFeatures { + return { + length: query.length, + wordCount: query.split(/\s+/).filter((w) => w.length > 0).length, + hasQuotes: /"[^"]+"/.test(query), + hasOperators: /\b(AND|OR|NOT)\b|\+|-/.test(query), + hasCode: /[a-zA-Z]+\.[a-zA-Z]+\(|function\s|class\s|=>|import\s|export\s/.test(query), + isQuestion: /^(what|how|why|when|where|who|which|can|does|is|are)\b/i.test(query), + hasAgentic: /\b(tool|function|call|execute|invoke|run|api|endpoint)\b/i.test(query), + }; + } + + /** + * Classify query complexity for reranker tier selection. + * Used by RerankerRouter to choose between fast/accurate/code tiers. + * + * Scoring: + * - simple: Basic queries, use fast reranker + * - moderate: Medium complexity, use accurate reranker + * - complex: High complexity or code queries, use code/accurate reranker + */ + classifyComplexity(query: string): { + complexity: QueryComplexity; + features: QueryFeatures; + score: number; + } { + const features = this.extractFeatures(query); + + let score = 0; + + // Length-based scoring + if (features.length > 100) score += 3; + else if (features.length > 50) score += 2; + else if (features.length > 25) score += 1; + + // Word count scoring + if (features.wordCount > 12) score += 2; + else if (features.wordCount > 8) score += 1; + + // Feature-based scoring + if (features.hasQuotes) score += 1; + if (features.hasOperators) score += 2; + if (features.hasCode) score += 3; + if (features.isQuestion) score += 1; + if (features.hasAgentic) score += 2; + + // Determine complexity level + let complexity: QueryComplexity; + if (score >= 5) { + complexity = "complex"; + } else if (score >= 2) { + complexity = "moderate"; + } else { + complexity = "simple"; + } + + return { complexity, features, score }; + } + + /** + * Check if query contains code patterns. + * Used for routing to code-specialized reranker. + */ + isCodeQuery(query: string): boolean { + const features = this.extractFeatures(query); + return features.hasCode; + } + + /** + * Check if query is agentic/tool-related. + * May benefit from more accurate reranking. + */ + isAgenticQuery(query: string): boolean { + const features = this.extractFeatures(query); + return features.hasAgentic; + } +} diff --git a/packages/search/src/services/code-embedder.test.ts b/packages/search/src/services/code-embedder.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..eda8ce5d4977af6f1e28d842735f19b0d46439e7 --- /dev/null +++ b/packages/search/src/services/code-embedder.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it, vi } from "vitest"; +import { CodeEmbedder } from "./code-embedder"; + +const { mockPipeline, mockExtractor } = vi.hoisted(() => { + const mockExtractor = vi.fn(async (_input: string) => { + return { + data: new Float32Array([0.9, 0.8, 0.7]), + }; + }); + + const mockPipeline = vi.fn(async (task: string, _model: string) => { + if (task === "feature-extraction") { + return mockExtractor; + } + throw new Error("Unknown task"); + }); + + return { mockPipeline, mockExtractor }; +}); + +vi.mock("@huggingface/transformers", () => ({ + pipeline: mockPipeline, +})); + +describe("CodeEmbedder", () => { + it("should embed code with nomic model", async () => { + const embedder = new CodeEmbedder(); + const code = "function test() { return true; }"; + const vector = await embedder.embed(code); + + expect(mockPipeline).toHaveBeenCalledWith( + "feature-extraction", + expect.stringContaining("nomic-embed-text"), + expect.objectContaining({ dtype: expect.any(String) }), + ); + expect(vector[0]).toBeCloseTo(0.9); + }); + + it("should use search_document prefix for embedding", async () => { + mockExtractor.mockClear(); + const embedder = new CodeEmbedder(); + await embedder.embed("const x = 1;"); + + expect(mockExtractor).toHaveBeenCalledWith( + expect.stringContaining("search_document:"), + expect.any(Object), + ); + }); + + it("should use search_query prefix for queries", async () => { + mockExtractor.mockClear(); + const embedder = new CodeEmbedder(); + await embedder.embedQuery("find authentication function"); + + expect(mockExtractor).toHaveBeenCalledWith( + expect.stringContaining("search_query:"), + expect.any(Object), + ); + }); + + it("should chunk large code files", async () => { + mockExtractor.mockClear(); + const embedder = new CodeEmbedder(); + // Create code larger than CHUNK_SIZE (6000 chars) + const largeCode = "function test() {\n".repeat(500); // ~9000 chars + await embedder.embed(largeCode); + + // Should have made multiple calls (chunks) + expect(mockExtractor.mock.calls.length).toBeGreaterThan(1); + }); + + it("should average embeddings for chunked code", async () => { + const embedder = new CodeEmbedder(); + const largeCode = "x".repeat(10000); + const vector = await embedder.embed(largeCode); + + // Result should be normalized (L2 norm close to 1) + const norm = Math.sqrt(vector.reduce((sum, v) => sum + v * v, 0)); + expect(norm).toBeCloseTo(1, 1); + }); +}); diff --git a/packages/search/src/services/code-embedder.ts b/packages/search/src/services/code-embedder.ts new file mode 100644 index 0000000000000000000000000000000000000000..6908502fa0d981994a265cea14edf6a92e203080 --- /dev/null +++ b/packages/search/src/services/code-embedder.ts @@ -0,0 +1,148 @@ +import { pipeline } from "@huggingface/transformers"; +import { + BasePipelineEmbedder, + type EmbedderConfig, + getDefaultDevice, + getDefaultDtype, +} from "./base-embedder"; + +/** + * Configuration for CodeEmbedder. + */ +export interface CodeEmbedderConfig extends EmbedderConfig { + /** Characters per chunk (default: 6000, ~1500 tokens) */ + chunkSize?: number; + /** Overlap between chunks for context continuity */ + chunkOverlap?: number; + /** Maximum chunks to process per file */ + maxChunks?: number; + /** Task prefix for documents (default: "search_document:") */ + documentPrefix?: string; + /** Task prefix for queries (default: "search_query:") */ + queryPrefix?: string; +} + +const DEFAULT_CONFIG: CodeEmbedderConfig = { + model: "Xenova/nomic-embed-text-v1", + dimensions: 768, + maxTokens: 8192, + chunkSize: 6000, + chunkOverlap: 500, + maxChunks: 5, + documentPrefix: "search_document:", + queryPrefix: "search_query:", +}; + +type ExtractorFn = ( + text: string, + opts: { pooling: string; normalize: boolean }, +) => Promise<{ data: Float32Array }>; + +/** + * Code-specific embedding using nomic-embed-text-v1. + * Extends BasePipelineEmbedder for common functionality. + * + * Features: + * - 8192 token context (using safe 6k char chunks) + * - Task prefix support for better retrieval + * - Chunking with overlap for large files + * - Automatic embedding averaging for chunked content + */ +export class CodeEmbedder extends BasePipelineEmbedder { + private static instance: unknown = null; + + constructor(config: Partial = {}) { + super({ ...DEFAULT_CONFIG, ...config }); + } + + /** + * Get or create singleton pipeline instance. + */ + protected async getInstance(): Promise { + if (!CodeEmbedder.instance) { + CodeEmbedder.instance = await pipeline("feature-extraction", this.config.model, { + dtype: this.config.dtype ?? getDefaultDtype(), + device: this.config.device ?? getDefaultDevice(), + }); + } + return CodeEmbedder.instance as ExtractorFn; + } + + /** + * Load the model (for preloading). + */ + protected async loadModel(): Promise { + await this.getInstance(); + } + + /** + * Embed code content for storage/indexing. + * Uses 'search_document:' prefix for retrieval optimization. + * Large files are chunked and averaged. + */ + async embed(code: string): Promise { + const chunks = this.chunkCode(code); + + if (chunks.length === 1) { + return this.embedSingle(`${this.config.documentPrefix} ${chunks[0]}`); + } + + // Multiple chunks: embed each and average + const embeddings = await Promise.all( + chunks.map((chunk) => this.embedSingle(`${this.config.documentPrefix} ${chunk}`)), + ); + + return this.averageEmbeddings(embeddings); + } + + /** + * Embed a code query for searching. + * Uses 'search_query:' prefix for retrieval optimization. + */ + async embedQuery(query: string): Promise { + return this.embedSingle(`${this.config.queryPrefix} ${query}`); + } + + /** + * Embed a single text chunk. + */ + private async embedSingle(text: string): Promise { + const extractor = await this.getInstance(); + const output = await extractor(text, { pooling: "mean", normalize: true }); + return Array.from(output.data); + } + + /** + * Split code into overlapping chunks for large files. + * Tries to split at natural boundaries (newlines). + */ + private chunkCode(code: string): string[] { + const { chunkSize = 6000, chunkOverlap = 500, maxChunks = 5 } = this.config; + + if (code.length <= chunkSize) { + return [code]; + } + + const chunks: string[] = []; + let start = 0; + + while (start < code.length && chunks.length < maxChunks) { + let end = Math.min(start + chunkSize, code.length); + + // Try to find a natural break point (newline) near the end + if (end < code.length) { + const lastNewline = code.lastIndexOf("\n", end); + if (lastNewline > start + chunkSize * 0.5) { + end = lastNewline + 1; + } + } + + chunks.push(code.slice(start, end)); + + // Move start with overlap, but ensure progress + start = Math.max(start + 1, end - chunkOverlap); + } + + return chunks; + } +} diff --git a/packages/search/src/services/colbert-embedder.test.ts b/packages/search/src/services/colbert-embedder.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..aface50ba713b6dbbefdd360a95d12a8f6ae0f1c --- /dev/null +++ b/packages/search/src/services/colbert-embedder.test.ts @@ -0,0 +1,215 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { ColBERTEmbedder } from "./colbert-embedder"; + +// Mock the feature extraction pipeline for ColBERT +const { mockExtractor, mockPipeline } = vi.hoisted(() => { + const mockExtractor = vi.fn( + async (_input: string, _opts: { pooling: string; normalize: boolean }) => { + // Simulate token-level embeddings: 5 tokens x 128 dimensions + const numTokens = 5; + const tokenDim = 128; + const totalSize = numTokens * tokenDim; + const data = new Float32Array(totalSize); + + // Fill with mock normalized embeddings + for (let i = 0; i < totalSize; i++) { + data[i] = (i % tokenDim) / tokenDim; // Normalized values [0, 1) + } + + return { + data, + dims: [numTokens, tokenDim], + }; + }, + ); + + const mockPipeline = vi.fn(async (task: string, model: string, _options?: unknown) => { + if (task === "feature-extraction" && model === "Xenova/colbertv2.0") { + return mockExtractor; + } + throw new Error(`Unknown task or model: ${task}, ${model}`); + }); + + return { mockExtractor, mockPipeline }; +}); + +vi.mock("@huggingface/transformers", () => ({ + pipeline: mockPipeline, +})); + +describe("ColBERTEmbedder", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Reset singleton instance + (ColBERTEmbedder as any).instance = undefined; + }); + + describe("getInstance", () => { + it("should create singleton instance", async () => { + const instance1 = await ColBERTEmbedder.getInstance(); + const instance2 = await ColBERTEmbedder.getInstance(); + + expect(instance1).toBe(instance2); + expect(mockPipeline).toHaveBeenCalledTimes(1); + expect(mockPipeline).toHaveBeenCalledWith("feature-extraction", "Xenova/colbertv2.0", { + dtype: "q8", + }); + }); + + it("should load model with quantization", async () => { + await ColBERTEmbedder.getInstance(); + + expect(mockPipeline).toHaveBeenCalledWith("feature-extraction", "Xenova/colbertv2.0", { + dtype: "q8", + }); + }); + }); + + describe("encodeDocument", () => { + it("should encode document into token-level embeddings", async () => { + const embedder = new ColBERTEmbedder(); + const tokenEmbeddings = await embedder.encodeDocument("hello world test"); + + expect(tokenEmbeddings).toBeInstanceOf(Array); + expect(tokenEmbeddings.length).toBe(5); // Mock returns 5 tokens + + // Check each token embedding + for (const token of tokenEmbeddings) { + expect(token).toBeInstanceOf(Float32Array); + expect(token.length).toBe(128); // ColBERT v2 token dimension + } + }); + + it("should use passage prefix for documents", async () => { + const embedder = new ColBERTEmbedder(); + await embedder.encodeDocument("test document"); + + expect(mockExtractor).toHaveBeenCalledWith("[D] test document", { + pooling: "none", + normalize: true, + }); + }); + + it("should normalize embeddings", async () => { + const embedder = new ColBERTEmbedder(); + await embedder.encodeDocument("test"); + + expect(mockExtractor).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ normalize: true }), + ); + }); + + it("should use no pooling for token-level embeddings", async () => { + const embedder = new ColBERTEmbedder(); + await embedder.encodeDocument("test"); + + expect(mockExtractor).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ pooling: "none" }), + ); + }); + + it("should return 128-dimensional token embeddings", async () => { + const embedder = new ColBERTEmbedder(); + const tokenEmbeddings = await embedder.encodeDocument("test"); + + for (const token of tokenEmbeddings) { + expect(token.length).toBe(128); + } + }); + }); + + describe("encodeQuery", () => { + it("should encode query into token-level embeddings", async () => { + const embedder = new ColBERTEmbedder(); + const tokenEmbeddings = await embedder.encodeQuery("search query"); + + expect(tokenEmbeddings).toBeInstanceOf(Array); + expect(tokenEmbeddings.length).toBe(5); // Mock returns 5 tokens + + // Check each token embedding + for (const token of tokenEmbeddings) { + expect(token).toBeInstanceOf(Float32Array); + expect(token.length).toBe(128); + } + }); + + it("should use query prefix", async () => { + const embedder = new ColBERTEmbedder(); + await embedder.encodeQuery("search term"); + + expect(mockExtractor).toHaveBeenCalledWith("[Q] search term", { + pooling: "none", + normalize: true, + }); + }); + + it("should use same model instance as documents", async () => { + const embedder = new ColBERTEmbedder(); + await embedder.encodeDocument("doc"); + await embedder.encodeQuery("query"); + + // Should only load model once (singleton) + expect(mockPipeline).toHaveBeenCalledTimes(1); + }); + }); + + describe("preload", () => { + it("should preload model instance", async () => { + const embedder = new ColBERTEmbedder(); + await embedder.preload(); + + expect(mockPipeline).toHaveBeenCalledTimes(1); + expect(mockPipeline).toHaveBeenCalledWith("feature-extraction", "Xenova/colbertv2.0", { + dtype: "q8", + }); + }); + + it("should allow subsequent calls to use cached instance", async () => { + const embedder = new ColBERTEmbedder(); + await embedder.preload(); + await embedder.encodeDocument("test"); + + // Only one pipeline call (preload) + expect(mockPipeline).toHaveBeenCalledTimes(1); + }); + }); + + describe("token embedding structure", () => { + it("should split flat array into per-token embeddings", async () => { + const embedder = new ColBERTEmbedder(); + const tokenEmbeddings = await embedder.encodeDocument("test"); + + // Verify each token has distinct values based on position + expect(tokenEmbeddings.length).toBeGreaterThan(0); + + // Check that tokens have values based on their position in the flat array + const firstToken = tokenEmbeddings[0]; + const secondToken = tokenEmbeddings[1]; + + // Based on our mock: first token starts at index 0, second at 128 + // Values are (i % 128) / 128, so first token has values [0/128, 1/128, 2/128, ...] + // Second token has values [128/128=0, 129/128, 130/128, ...] which wraps due to modulo + expect(firstToken).toBeInstanceOf(Float32Array); + expect(secondToken).toBeInstanceOf(Float32Array); + expect(firstToken.length).toBe(128); + expect(secondToken.length).toBe(128); + }); + + it("should handle correct token dimension math", async () => { + const embedder = new ColBERTEmbedder(); + const tokenEmbeddings = await embedder.encodeDocument("test"); + + // Total elements = num_tokens * 128 + // Should get 5 tokens from mock (5 * 128 = 640 total elements) + expect(tokenEmbeddings.length).toBe(5); + + let totalElements = 0; + for (const token of tokenEmbeddings) { + totalElements += token.length; + } + expect(totalElements).toBe(640); // 5 * 128 + }); + }); +}); diff --git a/packages/search/src/services/colbert-embedder.ts b/packages/search/src/services/colbert-embedder.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc57629ad1b43853e453e4c9b2470f3d70d84c96 --- /dev/null +++ b/packages/search/src/services/colbert-embedder.ts @@ -0,0 +1,133 @@ +import { pipeline } from "@huggingface/transformers"; +import { BaseMultiVectorEmbedder, type EmbedderConfig } from "./base-embedder"; + +/** + * Configuration for ColBERTEmbedder. + */ +export interface ColBERTEmbedderConfig extends EmbedderConfig { + /** Token embedding dimension (default: 128) */ + tokenDimension?: number; + /** Model quantization type */ + dtype?: "fp32" | "fp16" | "q8" | "q4"; + /** Prefix for passages */ + passagePrefix?: string; + /** Prefix for queries */ + queryPrefix?: string; +} + +const DEFAULT_CONFIG: ColBERTEmbedderConfig = { + // Use Xenova/colbertv2.0 which has proper ONNX support with quantized models + // See: https://huggingface.co/Xenova/colbertv2.0/tree/main/onnx + // Available: model.onnx (436MB), model_fp16.onnx (218MB), model_q8/int8 (110MB), model_q4 (149MB) + model: "Xenova/colbertv2.0", + dimensions: 128, // Token-level dimension + tokenDimension: 128, + dtype: "q8", // Use int8 quantized model (110MB) for good balance of speed/accuracy + // ColBERT v2 uses [Q]/[D] prefixes for query/document + passagePrefix: "[D]", + queryPrefix: "[Q]", +}; + +type ExtractorFn = ( + text: string, + opts: { pooling: string; normalize: boolean }, +) => Promise<{ data: Float32Array }>; + +/** + * ColBERTEmbedder generates token-level embeddings for late interaction reranking. + * Extends BaseMultiVectorEmbedder for multi-vector output. + * + * Model: Xenova/colbertv2.0 (ONNX-optimized version of ColBERT v2) + * - Token dimension: 128 + * - Late interaction via MaxSim scoring + * - 180x fewer FLOPs than cross-encoders at k=10 + * - Properly optimized ONNX weights with quantization support + * + * Architecture: + * 1. Documents: Pre-computed token embeddings stored in Qdrant multivector field + * 2. Queries: Token embeddings computed at search time + * 3. Scoring: MaxSim algorithm between query and document tokens + */ +export class ColBERTEmbedder extends BaseMultiVectorEmbedder { + private static instance: unknown = null; + + constructor(config: Partial = {}) { + const mergedConfig = { ...DEFAULT_CONFIG, ...config }; + super(mergedConfig, mergedConfig.tokenDimension ?? 128); + } + + /** + * Get or create singleton pipeline instance. + * Uses lazy loading - model is only loaded on first use. + */ + static async getInstance(): Promise { + if (!ColBERTEmbedder.instance) { + console.log(`[ColBERTEmbedder] Loading model ${DEFAULT_CONFIG.model}...`); + ColBERTEmbedder.instance = await pipeline("feature-extraction", DEFAULT_CONFIG.model, { + dtype: DEFAULT_CONFIG.dtype, + }); + console.log("[ColBERTEmbedder] Model loaded successfully"); + } + return ColBERTEmbedder.instance as ExtractorFn; + } + + /** + * Load the model (for preloading). + */ + protected async loadModel(): Promise { + await ColBERTEmbedder.getInstance(); + } + + /** + * Encode document into token-level embeddings (128d per token). + * These embeddings are pre-computed at index time and stored in Qdrant. + * + * @param content - Document text to encode + * @returns Array of token embeddings (each token is 128d vector) + */ + async embed(content: string): Promise { + return this.encodeDocument(content); + } + + /** + * Encode document into token-level embeddings (128d per token). + * These embeddings are pre-computed at index time and stored in Qdrant. + * + * @param content - Document text to encode + * @returns Array of token embeddings (each token is 128d vector) + */ + async encodeDocument(content: string): Promise { + const extractor = await ColBERTEmbedder.getInstance(); + + // ColBERT uses token-level embeddings (no pooling) + // Returns shape: [num_tokens, 128] + const output = await extractor(`${this.config.passagePrefix} ${content}`, { + pooling: "none", // Token-level embeddings + normalize: true, + }); + + // Split flat array into per-token embeddings + return this.splitIntoTokenEmbeddings(output.data); + } + + /** + * Encode query for MaxSim scoring. + * Computed at search time for each query. + * + * @param query - Query text to encode + * @returns Array of token embeddings (each token is 128d vector) + */ + async encodeQuery(query: string): Promise { + const extractor = await ColBERTEmbedder.getInstance(); + + // ColBERT uses token-level embeddings (no pooling) + // Returns shape: [num_tokens, 128] + const output = await extractor(`${this.config.queryPrefix} ${query}`, { + pooling: "none", // Token-level embeddings + normalize: true, + }); + + // Split flat array into per-token embeddings + return this.splitIntoTokenEmbeddings(output.data); + } +} diff --git a/packages/search/src/services/colbert-reranker.test.ts b/packages/search/src/services/colbert-reranker.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea7ffdf176de60ab2d460fbd2707de31616f46c4 --- /dev/null +++ b/packages/search/src/services/colbert-reranker.test.ts @@ -0,0 +1,310 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { ColBERTEmbedder } from "./colbert-embedder"; +import { type CachedDocumentCandidate, ColBERTReranker } from "./colbert-reranker"; + +// Mock logger +vi.mock("@engram/logger", () => ({ + createLogger: () => ({ + info: vi.fn(), + debug: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }), +})); + +describe("ColBERTReranker", () => { + let mockEmbedder: ColBERTEmbedder; + let reranker: ColBERTReranker; + + beforeEach(() => { + // Create mock embedder + mockEmbedder = { + encodeQuery: vi.fn(async (_query: string) => { + // Return 3 query tokens x 128d (normalized) + return [ + new Float32Array(128).fill(0.1), + new Float32Array(128).fill(0.2), + new Float32Array(128).fill(0.3), + ]; + }), + encodeDocument: vi.fn(async (_content: string) => { + // Return 5 document tokens x 128d (normalized) + return [ + new Float32Array(128).fill(0.15), + new Float32Array(128).fill(0.25), + new Float32Array(128).fill(0.35), + new Float32Array(128).fill(0.05), + new Float32Array(128).fill(0.45), + ]; + }), + preload: vi.fn(async () => {}), + } as unknown as ColBERTEmbedder; + + reranker = new ColBERTReranker(mockEmbedder); + }); + + describe("rerank", () => { + it("should return empty array for empty candidates", async () => { + const results = await reranker.rerank("query", [], 10); + expect(results).toEqual([]); + }); + + it("should encode query tokens", async () => { + const candidates: CachedDocumentCandidate[] = [ + { + id: "1", + content: "test document", + colbertEmbeddings: [new Float32Array(128).fill(0.1)], + score: 0.8, + }, + ]; + + await reranker.rerank("test query", candidates, 10); + + expect(mockEmbedder.encodeQuery).toHaveBeenCalledWith("test query"); + }); + + it("should use cached embeddings when available", async () => { + const cachedEmbeddings = [new Float32Array(128).fill(0.1), new Float32Array(128).fill(0.2)]; + + const candidates: CachedDocumentCandidate[] = [ + { + id: "1", + content: "test document", + colbertEmbeddings: cachedEmbeddings, + score: 0.8, + }, + ]; + + await reranker.rerank("query", candidates, 10); + + // Should NOT call encodeDocument since embeddings are cached + expect(mockEmbedder.encodeDocument).not.toHaveBeenCalled(); + }); + + it("should compute embeddings on-the-fly when not cached", async () => { + const candidates: CachedDocumentCandidate[] = [ + { + id: "1", + content: "test document", + score: 0.8, + }, + ]; + + await reranker.rerank("query", candidates, 10); + + // Should call encodeDocument for missing embeddings + expect(mockEmbedder.encodeDocument).toHaveBeenCalledWith("test document"); + }); + + it("should return results sorted by score descending", async () => { + // Mock embedder to return predictable scores + mockEmbedder.encodeQuery = vi.fn(async () => [new Float32Array(128).fill(1.0)]); + + mockEmbedder.encodeDocument = vi + .fn() + .mockResolvedValueOnce([new Float32Array(128).fill(0.5)]) // doc1: low score + .mockResolvedValueOnce([new Float32Array(128).fill(0.9)]) // doc2: high score + .mockResolvedValueOnce([new Float32Array(128).fill(0.7)]); // doc3: medium score + + const candidates: CachedDocumentCandidate[] = [ + { id: "1", content: "doc1", score: 0.1 }, + { id: "2", content: "doc2", score: 0.2 }, + { id: "3", content: "doc3", score: 0.3 }, + ]; + + const results = await reranker.rerank("query", candidates, 3); + + // Should be sorted by ColBERT score (highest first) + expect(results[0].id).toBe("2"); // highest score (0.9 * 128) + expect(results[1].id).toBe("3"); // medium score (0.7 * 128) + expect(results[2].id).toBe("1"); // lowest score (0.5 * 128) + + // Scores should be descending + expect(results[0].score).toBeGreaterThan(results[1].score); + expect(results[1].score).toBeGreaterThan(results[2].score); + }); + + it("should limit results to topK", async () => { + const candidates: CachedDocumentCandidate[] = [ + { id: "1", content: "doc1", colbertEmbeddings: [new Float32Array(128).fill(0.1)] }, + { id: "2", content: "doc2", colbertEmbeddings: [new Float32Array(128).fill(0.2)] }, + { id: "3", content: "doc3", colbertEmbeddings: [new Float32Array(128).fill(0.3)] }, + { id: "4", content: "doc4", colbertEmbeddings: [new Float32Array(128).fill(0.4)] }, + { id: "5", content: "doc5", colbertEmbeddings: [new Float32Array(128).fill(0.5)] }, + ]; + + const results = await reranker.rerank("query", candidates, 3); + + expect(results).toHaveLength(3); + }); + + it("should preserve original index", async () => { + const candidates: CachedDocumentCandidate[] = [ + { id: "1", content: "doc1", colbertEmbeddings: [new Float32Array(128).fill(0.1)] }, + { id: "2", content: "doc2", colbertEmbeddings: [new Float32Array(128).fill(0.2)] }, + ]; + + const results = await reranker.rerank("query", candidates, 10); + + // Should have original indices (0-based) + expect(results.some((r) => r.originalIndex === 0)).toBe(true); + expect(results.some((r) => r.originalIndex === 1)).toBe(true); + }); + + it("should preserve original scores", async () => { + const candidates: CachedDocumentCandidate[] = [ + { + id: "1", + content: "doc1", + colbertEmbeddings: [new Float32Array(128).fill(0.1)], + score: 0.85, + }, + { + id: "2", + content: "doc2", + colbertEmbeddings: [new Float32Array(128).fill(0.2)], + score: 0.92, + }, + ]; + + const results = await reranker.rerank("query", candidates, 10); + + // Should preserve original retrieval scores + expect(results.some((r) => r.originalScore === 0.85)).toBe(true); + expect(results.some((r) => r.originalScore === 0.92)).toBe(true); + }); + + it("should handle errors gracefully and assign zero score", async () => { + mockEmbedder.encodeDocument = vi + .fn() + .mockResolvedValueOnce([new Float32Array(128).fill(0.5)]) + .mockRejectedValueOnce(new Error("Encoding failed")); + + const candidates: CachedDocumentCandidate[] = [ + { id: "1", content: "doc1" }, + { id: "2", content: "doc2" }, + ]; + + const results = await reranker.rerank("query", candidates, 10); + + expect(results).toHaveLength(2); + + // Failed document should have score 0 + const failedDoc = results.find((r) => r.id === "2"); + expect(failedDoc?.score).toBe(0); + }); + + it("should throw on critical errors", async () => { + mockEmbedder.encodeQuery = vi.fn().mockRejectedValue(new Error("Query encoding failed")); + + const candidates: CachedDocumentCandidate[] = [ + { id: "1", content: "doc1", colbertEmbeddings: [new Float32Array(128).fill(0.1)] }, + ]; + + await expect(reranker.rerank("query", candidates, 10)).rejects.toThrow(); + }); + }); + + describe("MaxSim scoring", () => { + it("should compute MaxSim score correctly", async () => { + // Create embedder with predictable embeddings + mockEmbedder.encodeQuery = vi.fn(async () => [ + // Query token 1: all 0.5 + new Float32Array(128).fill(0.5), + ]); + + mockEmbedder.encodeDocument = vi.fn(async () => [ + // Doc token 1: all 0.5 (perfect match) + new Float32Array(128).fill(0.5), + // Doc token 2: all 0.3 (lower match) + new Float32Array(128).fill(0.3), + ]); + + const candidates: CachedDocumentCandidate[] = [{ id: "1", content: "doc1" }]; + + const results = await reranker.rerank("query", candidates, 1); + + // MaxSim: for query token, max similarity is with doc token 1 + // Cosine similarity (normalized): dot(0.5, 0.5) * 128 = 0.25 * 128 = 32 + expect(results[0].score).toBeCloseTo(32, 1); + }); + + it("should sum max scores across all query tokens", async () => { + // 2 query tokens - normalized vectors where each element is the same value + mockEmbedder.encodeQuery = vi.fn(async () => [ + new Float32Array(128).fill(0.5), + new Float32Array(128).fill(0.6), + ]); + + // 2 document tokens + mockEmbedder.encodeDocument = vi.fn(async () => [ + new Float32Array(128).fill(0.5), + new Float32Array(128).fill(0.6), + ]); + + const candidates: CachedDocumentCandidate[] = [{ id: "1", content: "doc1" }]; + + const results = await reranker.rerank("query", candidates, 1); + + // For normalized vectors filled with constant value v: + // dot(v, v) = v * v * 128 + // Query token 1 (0.5) best matches doc token 1 (0.5): 0.5 * 0.5 * 128 = 32 + // But it could also match doc token 2 (0.6): 0.5 * 0.6 * 128 = 38.4 (this is max) + // Query token 2 (0.6) best matches doc token 2 (0.6): 0.6 * 0.6 * 128 = 46.08 (this is max) + // Total: 38.4 + 46.08 = 84.48 + expect(results[0].score).toBeCloseTo(84.48, 1); + }); + + it("should find maximum similarity for each query token", async () => { + // Single query token + mockEmbedder.encodeQuery = vi.fn(async () => [new Float32Array(128).fill(0.8)]); + + // Three document tokens with varying similarity + mockEmbedder.encodeDocument = vi.fn(async () => [ + new Float32Array(128).fill(0.2), // Low similarity + new Float32Array(128).fill(0.8), // High similarity (should be chosen) + new Float32Array(128).fill(0.5), // Medium similarity + ]); + + const candidates: CachedDocumentCandidate[] = [{ id: "1", content: "doc1" }]; + + const results = await reranker.rerank("query", candidates, 1); + + // Should choose max similarity: dot(0.8, 0.8) * 128 = 0.64 * 128 = 81.92 + expect(results[0].score).toBeCloseTo(81.92, 1); + }); + }); + + describe("warmup", () => { + it("should preload the embedder model", async () => { + await reranker.warmup(); + + expect(mockEmbedder.preload).toHaveBeenCalled(); + }); + }); + + describe("BatchedRerankResult compatibility", () => { + it("should return results compatible with BatchedRerankResult interface", async () => { + const candidates: CachedDocumentCandidate[] = [ + { + id: "1", + content: "doc1", + colbertEmbeddings: [new Float32Array(128).fill(0.1)], + score: 0.8, + }, + ]; + + const results = await reranker.rerank("query", candidates, 10); + + expect(results[0]).toHaveProperty("id"); + expect(results[0]).toHaveProperty("score"); + expect(results[0]).toHaveProperty("originalIndex"); + expect(results[0]).toHaveProperty("originalScore"); + + expect(typeof results[0].id).toBe("string"); + expect(typeof results[0].score).toBe("number"); + expect(typeof results[0].originalIndex).toBe("number"); + }); + }); +}); diff --git a/packages/search/src/services/colbert-reranker.ts b/packages/search/src/services/colbert-reranker.ts new file mode 100644 index 0000000000000000000000000000000000000000..653ede7efb1e19bff23c42c6a1348f68a1d84d1f --- /dev/null +++ b/packages/search/src/services/colbert-reranker.ts @@ -0,0 +1,232 @@ +import { createLogger } from "@engram/logger"; +import type { BatchedRerankResult } from "./batched-reranker"; +import type { ColBERTEmbedder } from "./colbert-embedder"; + +/** + * CachedDocumentCandidate extends the base DocumentCandidate with optional + * pre-computed ColBERT embeddings for efficiency. + */ +export interface CachedDocumentCandidate { + id: string | number; + content: string; + /** Pre-computed token embeddings from Qdrant multivector field */ + colbertEmbeddings?: Float32Array[]; + /** Original retrieval score (RRF/dense/sparse) */ + score?: number; +} + +/** + * ColBERTReranker implements late interaction reranking using MaxSim algorithm. + * + * Late Interaction Architecture: + * 1. Documents: Token embeddings pre-computed at index time + * 2. Queries: Token embeddings computed at search time + * 3. Scoring: MaxSim algorithm - for each query token, find max similarity + * with all document tokens, then sum these max scores + * + * Performance: + * - ~20ms for 30 docs (with precomputed embeddings) + * - 180x fewer FLOPs than cross-encoders at k=10 + * - Billion-scale efficiency via precomputation + * + * Model: jinaai/jina-colbert-v2 (559M, 89 languages, 128d tokens) + */ +export class ColBERTReranker { + private logger = createLogger({ component: "ColBERTReranker" }); + + constructor(private embedder: ColBERTEmbedder) {} + + /** + * Rerank documents using MaxSim late interaction scoring. + * + * MaxSim Algorithm: + * 1. For each query token vector q_i: + * - Compute cosine similarity with every document token d_j + * - Keep only the maximum similarity: max_j(sim(q_i, d_j)) + * 2. Sum all query token max scores: score = Σ_i max_j(sim(q_i, d_j)) + * + * @param query - Search query text + * @param candidates - Documents to rerank (with optional cached embeddings) + * @param topK - Number of top results to return + * @returns Reranked results sorted by MaxSim score + */ + async rerank( + query: string, + candidates: CachedDocumentCandidate[], + topK: number = 10, + ): Promise { + if (candidates.length === 0) { + return []; + } + + const startTime = Date.now(); + + this.logger.info({ + msg: "ColBERT rerank started", + candidateCount: candidates.length, + topK, + queryLength: query.length, + }); + + try { + // Encode query tokens + const queryTokens = await this.embedder.encodeQuery(query); + + this.logger.debug({ + msg: "Query tokens encoded", + queryTokenCount: queryTokens.length, + }); + + // Score all candidates + const results: BatchedRerankResult[] = []; + + for (let i = 0; i < candidates.length; i++) { + const candidate = candidates[i]; + + try { + // Get or compute document token embeddings + let docTokens: Float32Array[]; + + if (candidate.colbertEmbeddings) { + // Use cached embeddings from Qdrant + docTokens = candidate.colbertEmbeddings; + } else { + // Compute embeddings on-the-fly (slower path) + this.logger.debug({ + msg: "Computing embeddings on-the-fly for document", + docId: candidate.id, + }); + docTokens = await this.embedder.encodeDocument(candidate.content); + } + + // Compute MaxSim score + const maxSimScore = this.computeMaxSim(queryTokens, docTokens); + + results.push({ + id: candidate.id, + score: maxSimScore, + originalIndex: i, + originalScore: candidate.score, + }); + } catch (error) { + // On error, assign minimum score to push to bottom + this.logger.warn({ + msg: "Failed to score document", + docId: candidate.id, + error: error instanceof Error ? error.message : String(error), + }); + + results.push({ + id: candidate.id, + score: 0, + originalIndex: i, + originalScore: candidate.score, + }); + } + } + + // Sort by score descending and take top K + results.sort((a, b) => b.score - a.score); + const topResults = results.slice(0, topK); + + // Calculate statistics + const scores = topResults.map((r) => r.score); + const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length; + const maxScore = Math.max(...scores); + const minScore = Math.min(...scores); + + // Calculate score improvement if original scores exist + let scoreImprovement: number | undefined; + const hasOriginalScores = topResults.every((r) => r.originalScore !== undefined); + if (hasOriginalScores) { + const originalAvg = + topResults.reduce((sum, r) => sum + (r.originalScore ?? 0), 0) / topResults.length; + scoreImprovement = avgScore - originalAvg; + } + + const latencyMs = Date.now() - startTime; + + this.logger.info({ + msg: "ColBERT rerank completed", + candidateCount: candidates.length, + topK, + latencyMs, + avgScore: avgScore.toFixed(3), + maxScore: maxScore.toFixed(3), + minScore: minScore.toFixed(3), + scoreImprovement: scoreImprovement?.toFixed(3), + }); + + return topResults; + } catch (error) { + const latencyMs = Date.now() - startTime; + + this.logger.error({ + msg: "ColBERT rerank failed", + candidateCount: candidates.length, + latencyMs, + error: error instanceof Error ? error.message : String(error), + }); + + throw error; + } + } + + /** + * Compute MaxSim score between query and document tokens. + * + * MaxSim Algorithm: + * - For each query token: find max cosine similarity with all doc tokens + * - Sum all query token max scores + * + * @param queryTokens - Query token embeddings (q x 128) + * @param docTokens - Document token embeddings (d x 128) + * @returns MaxSim relevance score + */ + private computeMaxSim(queryTokens: Float32Array[], docTokens: Float32Array[]): number { + let totalScore = 0; + + // For each query token + for (const queryToken of queryTokens) { + let maxSim = -Infinity; + + // Find maximum similarity with all document tokens + for (const docToken of docTokens) { + const sim = this.cosineSimilarity(queryToken, docToken); + if (sim > maxSim) { + maxSim = sim; + } + } + + // Sum the max similarity for this query token + totalScore += maxSim; + } + + return totalScore; + } + + /** + * Compute cosine similarity between two normalized vectors. + * Since ColBERT embeddings are normalized, this is just the dot product. + * + * @param a - First vector (normalized) + * @param b - Second vector (normalized) + * @returns Cosine similarity [-1, 1] + */ + private cosineSimilarity(a: Float32Array, b: Float32Array): number { + let dotProduct = 0; + + for (let i = 0; i < a.length; i++) { + dotProduct += a[i] * b[i]; + } + + return dotProduct; + } + + /** + * Preload the ColBERT model for faster first use. + */ + async warmup(): Promise { + await this.embedder.preload(); + } +} diff --git a/packages/search/src/services/deduplicator.test.ts b/packages/search/src/services/deduplicator.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..92de0081521d94861db728eaaa699aeee25c1164 --- /dev/null +++ b/packages/search/src/services/deduplicator.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it, vi } from "vitest"; +import { Deduplicator } from "./deduplicator"; + +// Mock dependencies +vi.mock("./text-embedder", () => { + return { + TextEmbedder: class { + async embed(_text: string) { + return [0.1, 0.2, 0.3]; + } + }, + }; +}); + +vi.mock("@qdrant/js-client-rest", () => { + return { + QdrantClient: class { + async query(_collection: string, params: any) { + if (params.score_threshold && params.score_threshold > 0.9) { + // Simulate finding a duplicate if thresholds match logic + return { points: [{ id: "existing-uuid", score: 0.96 }] }; + } + return { points: [] }; + } + }, + }; +}); + +describe("Deduplicator", () => { + it("should return existing ID if duplicate found", async () => { + const deduplicator = new Deduplicator(); + const result = await deduplicator.findDuplicate("some existing content"); + expect(result).toBe("existing-uuid"); + }); +}); diff --git a/packages/search/src/services/deduplicator.ts b/packages/search/src/services/deduplicator.ts new file mode 100644 index 0000000000000000000000000000000000000000..df9dd2675dd84259500f8966802fb2de79bba319 --- /dev/null +++ b/packages/search/src/services/deduplicator.ts @@ -0,0 +1,46 @@ +import { QdrantClient } from "@qdrant/js-client-rest"; +import { TextEmbedder } from "./text-embedder"; + +export class Deduplicator { + private client: QdrantClient; + private textEmbedder: TextEmbedder; + private collectionName = "engram_memory"; + // Threshold for considering content "duplicate" + // 0.95 is usually very close for high-dimensional embeddings + private threshold = 0.95; + + constructor(url: string = "http://localhost:6333") { + this.client = new QdrantClient({ url }); + this.textEmbedder = new TextEmbedder(); + } + + /** + * Checks if semantically identical content exists. + * @param content The text content to check. + * @param vectorName The named vector to search against (default: text_dense). + * @returns The ID of the existing document if found, or null. + */ + async findDuplicate( + content: string, + vectorName: "text_dense" | "code_dense" = "text_dense", + ): Promise { + const vector = await this.textEmbedder.embed(content); + + // Use query API with named vector specification + const results = await this.client.query(this.collectionName, { + query: vector, + using: vectorName, + limit: 1, + score_threshold: this.threshold, + with_payload: true, + }); + + if (results.points.length > 0) { + // Double check? For now, trust the vector similarity. + // We could compare exact string if payload allows. + return results.points[0].id as string; + } + + return null; + } +} diff --git a/packages/search/src/services/embedder-factory.test.ts b/packages/search/src/services/embedder-factory.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9209a21ae54eb21d9c789a6039af530feb64cf89 --- /dev/null +++ b/packages/search/src/services/embedder-factory.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from "vitest"; +import { + ConfigurableTextEmbedder, + createEmbedder, + getModelConfig, + listModels, + MODEL_CONFIGS, +} from "./embedder-factory"; + +describe("EmbedderFactory", () => { + describe("MODEL_CONFIGS", () => { + it("should have configurations for all supported models", () => { + const models = [ + "e5-small", + "e5-base", + "e5-large", + "gte-base", + "gte-large", + "bge-small", + "bge-base", + "bge-large", + ]; + + for (const model of models) { + expect(MODEL_CONFIGS[model as keyof typeof MODEL_CONFIGS]).toBeDefined(); + } + }); + + it("should have correct dimensions for each model family", () => { + // E5 family + expect(MODEL_CONFIGS["e5-small"].dimensions).toBe(384); + expect(MODEL_CONFIGS["e5-base"].dimensions).toBe(768); + expect(MODEL_CONFIGS["e5-large"].dimensions).toBe(1024); + + // GTE family + expect(MODEL_CONFIGS["gte-base"].dimensions).toBe(768); + expect(MODEL_CONFIGS["gte-large"].dimensions).toBe(1024); + + // BGE family + expect(MODEL_CONFIGS["bge-small"].dimensions).toBe(384); + expect(MODEL_CONFIGS["bge-base"].dimensions).toBe(768); + expect(MODEL_CONFIGS["bge-large"].dimensions).toBe(1024); + }); + + it("should have query/passage prefixes for E5 models", () => { + expect(MODEL_CONFIGS["e5-small"].queryPrefix).toBe("query:"); + expect(MODEL_CONFIGS["e5-small"].passagePrefix).toBe("passage:"); + }); + + it("should have empty prefixes for GTE models", () => { + expect(MODEL_CONFIGS["gte-large"].queryPrefix).toBe(""); + expect(MODEL_CONFIGS["gte-large"].passagePrefix).toBe(""); + }); + + it("should have instruction prefix for BGE models", () => { + expect(MODEL_CONFIGS["bge-large"].queryPrefix).toContain("Represent this sentence"); + }); + }); + + describe("getModelConfig", () => { + it("should return config for valid model", () => { + const config = getModelConfig("gte-large"); + + expect(config.dimensions).toBe(1024); + expect(config.hfModel).toBe("Xenova/gte-large"); + }); + + it("should throw for unknown model", () => { + expect(() => getModelConfig("unknown-model" as any)).toThrow("Unknown model"); + }); + }); + + describe("listModels", () => { + it("should return all supported models", () => { + const models = listModels(); + + expect(models).toContain("e5-small"); + expect(models).toContain("gte-large"); + expect(models).toContain("bge-base"); + expect(models.length).toBe(8); + }); + }); + + describe("createEmbedder", () => { + it("should create embedder with correct dimensions", () => { + const embedder = createEmbedder({ model: "gte-large" }); + + expect(embedder.dimensions).toBe(1024); + }); + + it("should create embedder without sparse by default", () => { + const embedder = createEmbedder({ model: "e5-small" }); + + expect(embedder.hasSparse()).toBe(false); + }); + + it("should create embedder with sparse when requested", () => { + const embedder = createEmbedder({ model: "e5-small", sparse: true }); + + expect(embedder.hasSparse()).toBe(true); + }); + + it("should throw for unknown model", () => { + expect(() => createEmbedder({ model: "unknown" as any })).toThrow("Unknown model"); + }); + }); + + describe("ConfigurableTextEmbedder", () => { + it("should expose model name", () => { + const embedder = new ConfigurableTextEmbedder({ model: "gte-large" }); + + expect(embedder.modelName).toBe("Xenova/gte-large"); + }); + + it("should throw when accessing sparse without enabling", async () => { + const embedder = new ConfigurableTextEmbedder({ model: "e5-small" }); + + await expect(embedder.embedSparse("test")).rejects.toThrow("Sparse embeddings not enabled"); + }); + + // Note: Actual embedding tests would require mocking the transformers pipeline + // These tests focus on configuration and factory logic + }); +}); diff --git a/packages/search/src/services/embedder-factory.ts b/packages/search/src/services/embedder-factory.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bb8b6887cb9b756bc81616d848c38fae57d553f --- /dev/null +++ b/packages/search/src/services/embedder-factory.ts @@ -0,0 +1,293 @@ +import { pipeline } from "@huggingface/transformers"; +import { + BasePipelineEmbedder, + type EmbedderConfig, + getDefaultDevice, + getDefaultDtype, +} from "./base-embedder"; +import { SpladeEmbedder } from "./splade-embedder"; + +/** + * Supported embedding model identifiers. + */ +export type EmbeddingModel = + | "e5-small" + | "e5-base" + | "e5-large" + | "gte-base" + | "gte-large" + | "bge-small" + | "bge-base" + | "bge-large"; + +/** + * Model configuration with HuggingFace model ID and settings. + */ +export interface ModelConfig { + /** HuggingFace model identifier */ + hfModel: string; + /** Embedding dimensions */ + dimensions: number; + /** Prefix for query embeddings */ + queryPrefix: string; + /** Prefix for passage embeddings */ + passagePrefix: string; + /** Maximum tokens */ + maxTokens: number; +} + +/** + * Configuration for creating embedders. + */ +export interface EmbedderFactoryConfig { + /** Model to use */ + model: EmbeddingModel; + /** Whether to include sparse embeddings */ + sparse?: boolean; +} + +/** + * Model configurations for supported embedding models. + */ +export const MODEL_CONFIGS: Record = { + "e5-small": { + hfModel: "Xenova/multilingual-e5-small", + dimensions: 384, + queryPrefix: "query:", + passagePrefix: "passage:", + maxTokens: 512, + }, + "e5-base": { + hfModel: "Xenova/multilingual-e5-base", + dimensions: 768, + queryPrefix: "query:", + passagePrefix: "passage:", + maxTokens: 512, + }, + "e5-large": { + hfModel: "Xenova/multilingual-e5-large", + dimensions: 1024, + queryPrefix: "query:", + passagePrefix: "passage:", + maxTokens: 512, + }, + "gte-base": { + hfModel: "Xenova/gte-base", + dimensions: 768, + queryPrefix: "", + passagePrefix: "", + maxTokens: 512, + }, + "gte-large": { + hfModel: "Xenova/gte-large", + dimensions: 1024, + queryPrefix: "", + passagePrefix: "", + maxTokens: 512, + }, + "bge-small": { + hfModel: "Xenova/bge-small-en-v1.5", + dimensions: 384, + queryPrefix: "Represent this sentence for searching relevant passages:", + passagePrefix: "", + maxTokens: 512, + }, + "bge-base": { + hfModel: "Xenova/bge-base-en-v1.5", + dimensions: 768, + queryPrefix: "Represent this sentence for searching relevant passages:", + passagePrefix: "", + maxTokens: 512, + }, + "bge-large": { + hfModel: "Xenova/bge-large-en-v1.5", + dimensions: 1024, + queryPrefix: "Represent this sentence for searching relevant passages:", + passagePrefix: "", + maxTokens: 512, + }, +}; + +type ExtractorFn = ( + text: string, + opts: { pooling: string; normalize: boolean }, +) => Promise<{ data: Float32Array }>; + +/** + * Configurable text embedder supporting multiple models. + * + * Features: + * - Support for E5, GTE, and BGE model families + * - Configuration-based model selection + * - Optional sparse embeddings via SPLADE + * + * @example + * ```typescript + * const embedder = createEmbedder({ model: "gte-large" }); + * const vector = await embedder.embedQuery("What is machine learning?"); + * // Returns 1024-dimensional vector + * ``` + */ +export class ConfigurableTextEmbedder extends BasePipelineEmbedder { + private static instances = new Map(); + private sparseEmbedder?: SpladeEmbedder; + private modelConfig: ModelConfig; + private includeSparse: boolean; + + constructor(config: EmbedderFactoryConfig) { + const modelConfig = MODEL_CONFIGS[config.model]; + if (!modelConfig) { + throw new Error( + `Unknown model: ${config.model}. Supported: ${Object.keys(MODEL_CONFIGS).join(", ")}`, + ); + } + + super({ + model: modelConfig.hfModel, + dimensions: modelConfig.dimensions, + maxTokens: modelConfig.maxTokens, + }); + + this.modelConfig = modelConfig; + this.includeSparse = config.sparse ?? false; + + if (this.includeSparse) { + this.sparseEmbedder = new SpladeEmbedder(); + } + } + + /** + * Get embedding dimensions for this model. + */ + get dimensions(): number { + return this.modelConfig.dimensions; + } + + /** + * Get the model identifier. + */ + get modelName(): string { + return this.modelConfig.hfModel; + } + + /** + * Get or create singleton pipeline instance for this model. + */ + protected async getInstance(): Promise { + const key = this.modelConfig.hfModel; + if (!ConfigurableTextEmbedder.instances.has(key)) { + ConfigurableTextEmbedder.instances.set( + key, + await pipeline("feature-extraction", this.modelConfig.hfModel, { + dtype: this.config.dtype ?? getDefaultDtype(), + device: this.config.device ?? getDefaultDevice(), + }), + ); + } + return ConfigurableTextEmbedder.instances.get(key) as ExtractorFn; + } + + /** + * Load the model (for preloading). + */ + protected async loadModel(): Promise { + await this.getInstance(); + if (this.sparseEmbedder) { + await this.sparseEmbedder.preload(); + } + } + + /** + * Embed document (passage) for storage/indexing. + */ + async embed(text: string): Promise { + return this.callEmbeddingAPI(text, { + prefix: this.modelConfig.passagePrefix, + pooling: "mean", + normalize: true, + }); + } + + /** + * Embed query for searching. + */ + async embedQuery(text: string): Promise { + return this.callEmbeddingAPI(text, { + prefix: this.modelConfig.queryPrefix, + pooling: "mean", + normalize: true, + }); + } + + /** + * Generate sparse vector using SPLADE. + * Only available if sparse=true was passed to constructor. + */ + async embedSparse(text: string): Promise<{ indices: number[]; values: number[] }> { + if (!this.sparseEmbedder) { + throw new Error("Sparse embeddings not enabled. Pass sparse: true to constructor."); + } + return this.sparseEmbedder.embed(text); + } + + /** + * Generate sparse vector for queries. + * Only available if sparse=true was passed to constructor. + */ + async embedSparseQuery(text: string): Promise<{ indices: number[]; values: number[] }> { + if (!this.sparseEmbedder) { + throw new Error("Sparse embeddings not enabled. Pass sparse: true to constructor."); + } + return this.sparseEmbedder.embedQuery(text); + } + + /** + * Preload the SPLADE model. + */ + async preloadSparse(): Promise { + if (this.sparseEmbedder) { + await this.sparseEmbedder.preload(); + } + } + + /** + * Check if sparse embeddings are available. + */ + hasSparse(): boolean { + return this.includeSparse; + } +} + +/** + * Create an embedder with the specified configuration. + * + * @example + * ```typescript + * // E5-small (default, 384d) + * const embedder = createEmbedder({ model: "e5-small" }); + * + * // GTE-large (1024d) with sparse + * const embedder = createEmbedder({ model: "gte-large", sparse: true }); + * ``` + */ +export function createEmbedder(config: EmbedderFactoryConfig): ConfigurableTextEmbedder { + return new ConfigurableTextEmbedder(config); +} + +/** + * Get model configuration without creating an embedder. + */ +export function getModelConfig(model: EmbeddingModel): ModelConfig { + const config = MODEL_CONFIGS[model]; + if (!config) { + throw new Error(`Unknown model: ${model}`); + } + return config; +} + +/** + * List all supported embedding models. + */ +export function listModels(): EmbeddingModel[] { + return Object.keys(MODEL_CONFIGS) as EmbeddingModel[]; +} diff --git a/packages/search/src/services/embedding-cache.test.ts b/packages/search/src/services/embedding-cache.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f00cdc95875b5fce86032e9ae857d6bf5086abe --- /dev/null +++ b/packages/search/src/services/embedding-cache.test.ts @@ -0,0 +1,294 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { EmbeddingCache } from "./embedding-cache"; + +describe("EmbeddingCache", () => { + let cache: EmbeddingCache; + + beforeEach(() => { + cache = new EmbeddingCache({ + maxSizeBytes: 1024, // 1KB for testing + ttlMs: 1000, // 1 second for testing + }); + }); + + describe("constructor", () => { + it("should use default options when none provided", () => { + const defaultCache = new EmbeddingCache(); + const stats = defaultCache.getStats(); + expect(stats.count).toBe(0); + }); + + it("should use provided options", () => { + const customCache = new EmbeddingCache({ + maxSizeBytes: 2048, + ttlMs: 5000, + }); + expect(customCache.getMetrics().maxSize).toBe(2048); + }); + }); + + describe("set() and get()", () => { + it("should cache embeddings", () => { + const embeddings = [new Float32Array([0.1, 0.2, 0.3])]; + cache.set("doc1", embeddings); + + const retrieved = cache.get("doc1"); + expect(retrieved).toEqual(embeddings); + }); + + it("should return null for non-existent entries", () => { + const result = cache.get("non-existent"); + expect(result).toBeNull(); + }); + + it("should update existing entries", () => { + const embeddings1 = [new Float32Array([0.1, 0.2])]; + const embeddings2 = [new Float32Array([0.3, 0.4])]; + + cache.set("doc1", embeddings1); + cache.set("doc1", embeddings2); + + const retrieved = cache.get("doc1"); + expect(retrieved).toEqual(embeddings2); + }); + + it("should handle multiple Float32Arrays", () => { + const embeddings = [ + new Float32Array([0.1, 0.2]), + new Float32Array([0.3, 0.4]), + new Float32Array([0.5, 0.6]), + ]; + + cache.set("doc1", embeddings); + const retrieved = cache.get("doc1"); + + expect(retrieved).toHaveLength(3); + expect(retrieved).toEqual(embeddings); + }); + }); + + describe("TTL expiration", () => { + it("should expire entries after TTL", async () => { + vi.useFakeTimers(); + + const embeddings = [new Float32Array([0.1, 0.2])]; + cache.set("doc1", embeddings); + + // Should be available immediately + expect(cache.get("doc1")).toEqual(embeddings); + + // Advance time past TTL + vi.advanceTimersByTime(1100); + + // Should be expired now + expect(cache.get("doc1")).toBeNull(); + + vi.useRealTimers(); + }); + + it("should not expire entries within TTL", async () => { + vi.useFakeTimers(); + + const embeddings = [new Float32Array([0.1, 0.2])]; + cache.set("doc1", embeddings); + + // Advance time but stay within TTL + vi.advanceTimersByTime(500); + + // Should still be available + expect(cache.get("doc1")).toEqual(embeddings); + + vi.useRealTimers(); + }); + }); + + describe("LRU eviction", () => { + it("should evict oldest entries when size limit is reached", () => { + // Each Float32Array element is 4 bytes + // 256 elements * 4 bytes = 1024 bytes (max size) + const large = [new Float32Array(256)]; + + cache.set("doc1", large); + expect(cache.get("doc1")).not.toBeNull(); + + // Adding another large entry should evict doc1 + cache.set("doc2", large); + + expect(cache.get("doc1")).toBeNull(); + expect(cache.get("doc2")).not.toBeNull(); + }); + + it("should track access order correctly", () => { + const small = [new Float32Array(50)]; // 200 bytes + + cache.set("doc1", small); + cache.set("doc2", small); + cache.set("doc3", small); + + // Access doc1 to make it most recently used + cache.get("doc1"); + + // Add more entries to trigger eviction + cache.set("doc4", small); + cache.set("doc5", small); + cache.set("doc6", small); + + // doc1 should still be present (recently accessed) + // doc2 should be evicted (least recently used) + expect(cache.get("doc1")).not.toBeNull(); + expect(cache.get("doc2")).toBeNull(); + }); + + it("should evict multiple entries if needed", () => { + const medium = [new Float32Array(100)]; // 400 bytes + const large = [new Float32Array(250)]; // 1000 bytes + + cache.set("doc1", medium); + cache.set("doc2", medium); + + // Adding large entry should evict both previous entries + cache.set("doc3", large); + + expect(cache.get("doc1")).toBeNull(); + expect(cache.get("doc2")).toBeNull(); + expect(cache.get("doc3")).not.toBeNull(); + }); + }); + + describe("invalidate()", () => { + it("should remove specific entry", () => { + const embeddings = [new Float32Array([0.1, 0.2])]; + + cache.set("doc1", embeddings); + expect(cache.get("doc1")).not.toBeNull(); + + cache.invalidate("doc1"); + expect(cache.get("doc1")).toBeNull(); + }); + + it("should handle invalidating non-existent entries", () => { + expect(() => cache.invalidate("non-existent")).not.toThrow(); + }); + }); + + describe("clear()", () => { + it("should clear all entries", () => { + const embeddings = [new Float32Array([0.1, 0.2])]; + + cache.set("doc1", embeddings); + cache.set("doc2", embeddings); + cache.set("doc3", embeddings); + + expect(cache.getStats().count).toBe(3); + + cache.clear(); + + expect(cache.getStats().count).toBe(0); + expect(cache.get("doc1")).toBeNull(); + expect(cache.get("doc2")).toBeNull(); + expect(cache.get("doc3")).toBeNull(); + }); + + it("should reset metrics", () => { + const embeddings = [new Float32Array([0.1, 0.2])]; + + cache.set("doc1", embeddings); + cache.get("doc1"); + cache.get("non-existent"); + + cache.clear(); + + const metrics = cache.getMetrics(); + expect(metrics.hits).toBe(0); + expect(metrics.misses).toBe(0); + expect(metrics.evictions).toBe(0); + }); + }); + + describe("getStats()", () => { + it("should return correct statistics", () => { + const embeddings = [new Float32Array([0.1, 0.2, 0.3])]; // 12 bytes + + cache.set("doc1", embeddings); + cache.set("doc2", embeddings); + + const stats = cache.getStats(); + expect(stats.count).toBe(2); + expect(stats.size).toBe(24); // 2 * 12 bytes + }); + + it("should calculate hit rate correctly", () => { + const embeddings = [new Float32Array([0.1, 0.2])]; + + cache.set("doc1", embeddings); + + cache.get("doc1"); // hit + cache.get("doc1"); // hit + cache.get("non-existent"); // miss + cache.get("non-existent"); // miss + + const stats = cache.getStats(); + expect(stats.hitRate).toBe(0.5); // 2 hits / 4 total + }); + + it("should return 0 hit rate when no accesses", () => { + const stats = cache.getStats(); + expect(stats.hitRate).toBe(0); + }); + }); + + describe("getMetrics()", () => { + it("should return detailed metrics", () => { + const embeddings = [new Float32Array([0.1, 0.2])]; + + cache.set("doc1", embeddings); + cache.get("doc1"); // hit + cache.get("non-existent"); // miss + + const metrics = cache.getMetrics(); + + expect(metrics.hits).toBe(1); + expect(metrics.misses).toBe(1); + expect(metrics.evictions).toBe(0); + expect(metrics.count).toBe(1); + expect(metrics.size).toBeGreaterThan(0); + expect(metrics.maxSize).toBe(1024); + expect(metrics.hitRate).toBe(0.5); + }); + + it("should track evictions", () => { + const large = [new Float32Array(256)]; // 1024 bytes + + cache.set("doc1", large); + cache.set("doc2", large); // Should evict doc1 + + const metrics = cache.getMetrics(); + expect(metrics.evictions).toBe(1); + }); + }); + + describe("size calculation", () => { + it("should calculate size correctly for Float32Array", () => { + // Float32Array uses 4 bytes per element + const embeddings = [new Float32Array(10)]; // 40 bytes + + cache.set("doc1", embeddings); + + const stats = cache.getStats(); + expect(stats.size).toBe(40); + }); + + it("should sum sizes for multiple arrays", () => { + const embeddings = [ + new Float32Array(10), // 40 bytes + new Float32Array(5), // 20 bytes + new Float32Array(15), // 60 bytes + ]; + + cache.set("doc1", embeddings); + + const stats = cache.getStats(); + expect(stats.size).toBe(120); + }); + }); +}); diff --git a/packages/search/src/services/embedding-cache.ts b/packages/search/src/services/embedding-cache.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea92e3736db4a453398905154263d17bc80f4d79 --- /dev/null +++ b/packages/search/src/services/embedding-cache.ts @@ -0,0 +1,258 @@ +import { createLogger } from "@engram/logger"; +import { RERANK_CONFIG } from "../config"; +import { + computeHitRate, + embeddingCacheCount, + embeddingCacheHitRate, + embeddingCacheSize, + recordEmbeddingCacheEviction, + recordEmbeddingCacheHit, + recordEmbeddingCacheMiss, +} from "./cache-metrics"; + +export interface EmbeddingCacheOptions { + maxSizeBytes?: number; // Default: 1GB (1024 * 1024 * 1024) + ttlMs?: number; // Default: 1 hour (3600000) +} + +export interface CachedEmbedding { + id: string; + embeddings: Float32Array[]; + sizeBytes: number; + createdAt: number; + lastAccessedAt: number; +} + +interface CacheEntry { + embeddings: Float32Array[]; + sizeBytes: number; + createdAt: number; + lastAccessedAt: number; +} + +/** + * In-memory LRU cache for ColBERT document embeddings. + * + * Features: + * - LRU eviction when size limit is reached (O(1) operations) + * - TTL-based expiration (default: 1 hour) + * - Size tracking in bytes + * - Hit rate metrics + * + * Implementation uses Map's insertion order for O(1) LRU operations: + * - On access: delete and re-insert to move to end + * - On eviction: iterate from start (oldest entries) + * + * This cache prevents redundant re-encoding of frequently accessed documents, + * significantly improving reranking performance for repeated queries. + */ +export class EmbeddingCache { + private cache: Map = new Map(); + // Note: We now use Map's insertion order for LRU tracking (O(1) operations) + // instead of maintaining a separate array (O(n) indexOf/splice) + private currentSizeBytes = 0; + private readonly maxSizeBytes: number; + private readonly ttlMs: number; + private hits = 0; + private misses = 0; + private evictions = 0; + private logger = createLogger({ component: "EmbeddingCache" }); + + constructor(options?: EmbeddingCacheOptions) { + this.maxSizeBytes = options?.maxSizeBytes ?? RERANK_CONFIG.cache.maxCacheSize; + this.ttlMs = options?.ttlMs ?? RERANK_CONFIG.cache.documentRepresentationTTL * 1000; + + this.logger.info({ + msg: "EmbeddingCache initialized", + maxSizeBytes: this.maxSizeBytes, + ttlMs: this.ttlMs, + }); + } + + /** + * Get cached embedding, returns null if not found or expired. + */ + get(documentId: string): Float32Array[] | null { + const entry = this.cache.get(documentId); + + if (!entry) { + this.misses++; + recordEmbeddingCacheMiss(); + this.updateMetrics(); + return null; + } + + // Check if entry has expired + const now = Date.now(); + if (now - entry.createdAt > this.ttlMs) { + // Entry expired, remove it + this.remove(documentId); + this.misses++; + recordEmbeddingCacheMiss(); + this.updateMetrics(); + return null; + } + + // Update access time and LRU order + entry.lastAccessedAt = now; + this.updateAccessOrder(documentId); + + this.hits++; + recordEmbeddingCacheHit(); + this.updateMetrics(); + return entry.embeddings; + } + + /** + * Store embedding in cache. + * Evicts oldest entries if size limit is exceeded. + */ + set(documentId: string, embeddings: Float32Array[]): void { + // Calculate size of embeddings + const sizeBytes = this.calculateSize(embeddings); + + // Check if already cached (update scenario) + const existing = this.cache.get(documentId); + if (existing) { + // Update existing entry + this.currentSizeBytes -= existing.sizeBytes; + this.currentSizeBytes += sizeBytes; + + existing.embeddings = embeddings; + existing.sizeBytes = sizeBytes; + existing.lastAccessedAt = Date.now(); + + this.updateAccessOrder(documentId); + return; + } + + // Evict if necessary to make room (O(1) per eviction using Map iteration) + while (this.currentSizeBytes + sizeBytes > this.maxSizeBytes && this.cache.size > 0) { + const oldestId = this.getOldestKey(); + if (oldestId) { + this.remove(oldestId); + this.evictions++; + recordEmbeddingCacheEviction(); + } else { + break; + } + } + + // Add new entry + const now = Date.now(); + this.cache.set(documentId, { + embeddings, + sizeBytes, + createdAt: now, + lastAccessedAt: now, + }); + + // No need to track accessOrder separately - Map maintains insertion order + this.currentSizeBytes += sizeBytes; + this.updateMetrics(); + } + + /** + * Invalidate specific document (on update). + */ + invalidate(documentId: string): void { + this.remove(documentId); + } + + /** + * Clear entire cache. + */ + clear(): void { + this.cache.clear(); + this.currentSizeBytes = 0; + this.hits = 0; + this.misses = 0; + this.evictions = 0; + + this.logger.info({ msg: "Cache cleared" }); + } + + /** + * Get cache statistics. + */ + getStats(): { size: number; count: number; hitRate: number } { + const total = this.hits + this.misses; + const hitRate = total > 0 ? this.hits / total : 0; + + return { + size: this.currentSizeBytes, + count: this.cache.size, + hitRate, + }; + } + + /** + * Get detailed metrics for monitoring. + */ + getMetrics() { + const stats = this.getStats(); + return { + hits: this.hits, + misses: this.misses, + evictions: this.evictions, + maxSize: this.maxSizeBytes, + ...stats, + }; + } + + /** + * Remove an entry from the cache. + * O(1) operation using Map's delete. + */ + private remove(documentId: string): void { + const entry = this.cache.get(documentId); + if (!entry) return; + + this.cache.delete(documentId); + this.currentSizeBytes -= entry.sizeBytes; + // No need to update accessOrder - we use Map's insertion order + } + + /** + * Update LRU access order. + * O(1) operation: delete and re-insert to move to end of Map's iteration order. + */ + private updateAccessOrder(documentId: string): void { + const entry = this.cache.get(documentId); + if (entry) { + // Delete and re-insert to move to end of Map's insertion order + this.cache.delete(documentId); + this.cache.set(documentId, entry); + } + } + + /** + * Get the oldest entry key (first in Map's iteration order). + * O(1) operation using Map.keys().next(). + */ + private getOldestKey(): string | undefined { + return this.cache.keys().next().value; + } + + /** + * Calculate size of embeddings in bytes. + * Float32Array uses 4 bytes per element. + */ + private calculateSize(embeddings: Float32Array[]): number { + let totalBytes = 0; + for (const embedding of embeddings) { + totalBytes += embedding.length * 4; // 4 bytes per float32 + } + return totalBytes; + } + + /** + * Update Prometheus metrics with current cache state. + */ + private updateMetrics(): void { + embeddingCacheSize.set(this.currentSizeBytes); + embeddingCacheCount.set(this.cache.size); + const hitRate = computeHitRate(this.hits, this.misses); + embeddingCacheHitRate.set(hitRate); + } +} diff --git a/packages/search/src/services/fusion-predictor.test.ts b/packages/search/src/services/fusion-predictor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8786263a88956364be25482e3d7eea4e6b079e83 --- /dev/null +++ b/packages/search/src/services/fusion-predictor.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from "vitest"; +import { FusionWeightPredictor } from "./fusion-predictor"; +import { QueryFeatureExtractor } from "./query-features"; + +describe("FusionWeightPredictor", () => { + describe("fallback behavior", () => { + it("should return fallback weights when model is not available", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + fallbackWeights: { dense: 0.5, sparse: 0.3, rerank: 0.2 }, + }); + + const extractor = new QueryFeatureExtractor(); + const features = extractor.extract("Who is the CEO of Microsoft?"); + const weights = await predictor.predict(features); + + // Should use fallback since model doesn't exist + expect(weights).toBeDefined(); + expect(weights.dense).toBeGreaterThan(0); + expect(weights.sparse).toBeGreaterThan(0); + expect(weights.rerank).toBeGreaterThanOrEqual(0); + }); + + it("should return weights that sum close to 1", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + }); + + const extractor = new QueryFeatureExtractor(); + const features = extractor.extract("List all TypeScript features"); + const weights = await predictor.predict(features); + + const sum = weights.dense + weights.sparse + weights.rerank; + expect(sum).toBeCloseTo(1.0, 1); + }); + + it("should favor sparse for queries with specific terms", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + }); + + const extractor = new QueryFeatureExtractor(); + const features = extractor.extract("error TS2345 TypeScript version 5.0.0"); + const weights = await predictor.predict(features); + + // Specific terms (error codes, version numbers) favor sparse + expect(weights.sparse).toBeGreaterThanOrEqual(0.3); + }); + + it("should favor rerank for complex queries", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + }); + + const extractor = new QueryFeatureExtractor(); + const simpleFeatures = extractor.extract("What is X?"); + const complexFeatures = extractor.extract( + "Compare the implications of using Redux versus MobX for state management considering performance and developer experience", + ); + + const simpleWeights = await predictor.predict(simpleFeatures); + const complexWeights = await predictor.predict(complexFeatures); + + expect(complexWeights.rerank).toBeGreaterThanOrEqual(simpleWeights.rerank); + }); + + it("should favor dense for factoid questions", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + }); + + const extractor = new QueryFeatureExtractor(); + const features = extractor.extract("Who founded Apple?"); + const weights = await predictor.predict(features); + + // Factoid questions have reasonable dense weight (at least not zero) + // The exact weight depends on the fallback heuristics + expect(weights.dense).toBeGreaterThan(0); + expect(weights.dense + weights.sparse + weights.rerank).toBeCloseTo(1.0, 1); + }); + }); + + describe("predictFromQuery", () => { + it("should predict weights directly from query string", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + }); + + const weights = await predictor.predictFromQuery("What is machine learning?"); + + expect(weights).toBeDefined(); + expect(weights.dense).toBeDefined(); + expect(weights.sparse).toBeDefined(); + expect(weights.rerank).toBeDefined(); + }); + }); + + describe("isAvailable", () => { + it("should return false when model does not exist", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + }); + + const available = await predictor.isAvailable(); + expect(available).toBe(false); + }); + }); + + describe("close", () => { + it("should release resources without error", async () => { + const predictor = new FusionWeightPredictor({ + modelPath: "non-existent-model.onnx", + }); + + // Should not throw + await expect(predictor.close()).resolves.toBeUndefined(); + }); + }); +}); diff --git a/packages/search/src/services/fusion-predictor.ts b/packages/search/src/services/fusion-predictor.ts new file mode 100644 index 0000000000000000000000000000000000000000..3976ad338ea7d5a30450261fd17e1f0a2de5432e --- /dev/null +++ b/packages/search/src/services/fusion-predictor.ts @@ -0,0 +1,256 @@ +/** + * Fusion weight predictor using ONNX Runtime for inference. + * + * Uses a trained MLP model to predict optimal dense/sparse/rerank fusion weights + * from query features. The model is trained using grid search on LongMemEval data. + * + * @see scripts/train_fusion_mlp.py - Training script + * @see packages/benchmark/src/cli/commands/train-fusion.ts - Training data generation + * + * References: + * - Neural Rank Fusion: https://www.rohan-paul.com/p/neural-based-rank-fusion-for-multi + * - End-to-End Retrieval with ONNX: https://arxiv.org/html/2311.18503 + */ + +import { type FusionQueryFeatures, QueryFeatureExtractor } from "./query-features.js"; + +/** + * Predicted fusion weights for combining dense, sparse, and rerank scores. + */ +export interface FusionWeights { + /** Weight for dense (semantic) retrieval scores */ + dense: number; + /** Weight for sparse (keyword) retrieval scores */ + sparse: number; + /** Weight for reranker scores */ + rerank: number; +} + +/** + * Configuration for the fusion weight predictor. + */ +export interface FusionWeightPredictorConfig { + /** Path to the ONNX model file */ + modelPath?: string; + /** Whether to cache the ONNX session */ + cacheSession?: boolean; + /** Default weights to use when model is unavailable */ + fallbackWeights?: FusionWeights; +} + +const DEFAULT_CONFIG: Required = { + modelPath: "models/fusion_mlp.onnx", + cacheSession: true, + fallbackWeights: { dense: 0.4, sparse: 0.3, rerank: 0.3 }, +}; + +/** + * Predicts optimal fusion weights from query features using a trained MLP. + * + * The predictor uses ONNX Runtime for fast CPU inference. If the model + * is not available, it falls back to rule-based heuristics. + * + * @example + * ```typescript + * const predictor = new FusionWeightPredictor(); + * const weights = await predictor.predict(queryFeatures); + * // weights = { dense: 0.45, sparse: 0.35, rerank: 0.20 } + * ``` + */ +export class FusionWeightPredictor { + private config: Required; + private session: OrtSession | null = null; + private sessionPromise: Promise | null = null; + private ort: OrtModule | null = null; + + constructor(config: FusionWeightPredictorConfig = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + } + + /** + * Predict fusion weights from query features. + * + * @param features - Extracted query features + * @returns Predicted fusion weights (sum to 1) + */ + async predict(features: FusionQueryFeatures): Promise { + try { + const session = await this.getSession(); + if (!session || !this.ort) { + return this.fallback(features); + } + + // Convert features to normalized vector + const extractor = new QueryFeatureExtractor(); + const normalized = extractor.toNormalizedVector(features); + + // Create input tensor + const inputTensor = new this.ort.Tensor("float32", new Float32Array(normalized.vector), [ + 1, + normalized.vector.length, + ]); + + // Run inference + const results = await session.run({ features: inputTensor }); + const output = results.weights.data as Float32Array; + + // Apply softmax to get weights that sum to 1 + const weights = this.softmax(Array.from(output)); + + return { + dense: weights[0], + sparse: weights[1], + rerank: weights[2], + }; + } catch (error) { + console.warn("Fusion prediction failed, using fallback:", error); + return this.fallback(features); + } + } + + /** + * Predict weights directly from a query string. + * + * @param query - The query text + * @returns Predicted fusion weights + */ + async predictFromQuery(query: string): Promise { + const extractor = new QueryFeatureExtractor(); + const features = extractor.extract(query); + return this.predict(features); + } + + /** + * Rule-based fallback when model is unavailable. + */ + private fallback(features: FusionQueryFeatures): FusionWeights { + // Use getFusionHints from query-features module + let dense = 0.4; + let sparse = 0.3; + let rerank = 0.3; + + // Factoid queries benefit from dense (semantic) + if (features.questionType === "factoid") { + dense = 0.5; + sparse = 0.2; + rerank = 0.3; + } + + // Queries with specific terms benefit from sparse (keyword) + if (features.hasSpecificTerms || features.hasRareTerms) { + sparse = 0.4; + dense = 0.3; + rerank = 0.3; + } + + // Complex queries benefit more from reranking + if (features.complexity > 0.5) { + rerank = 0.4; + dense = 0.35; + sparse = 0.25; + } + + // Short keyword-like queries favor sparse + if (features.length <= 3 && !features.hasTemporal) { + sparse = 0.5; + dense = 0.25; + rerank = 0.25; + } + + return { dense, sparse, rerank }; + } + + /** + * Get or create the ONNX session. + */ + private async getSession(): Promise { + // Return cached session if available + if (this.session) { + return this.session; + } + + // Return existing promise if loading + if (this.sessionPromise) { + return this.sessionPromise; + } + + // Load the session + this.sessionPromise = this.loadSession(); + const session = await this.sessionPromise; + + if (this.config.cacheSession && session) { + this.session = session; + } + + return session; + } + + /** + * Load the ONNX model and create a session. + */ + private async loadSession(): Promise { + try { + // Dynamic import to avoid bundling ONNX Runtime in non-Node environments + this.ort = (await import("onnxruntime-node")) as OrtModule; + + const session = await this.ort.InferenceSession.create(this.config.modelPath, { + executionProviders: ["cpu"], + }); + + return session; + } catch (error) { + // Model not found or ONNX Runtime not available + console.warn(`Fusion model not available at ${this.config.modelPath}:`, error); + return null; + } + } + + /** + * Apply softmax to convert logits to probabilities. + */ + private softmax(arr: number[]): number[] { + const max = Math.max(...arr); + const exp = arr.map((x) => Math.exp(x - max)); + const sum = exp.reduce((a, b) => a + b, 0); + return exp.map((x) => x / sum); + } + + /** + * Check if the model is available. + */ + async isAvailable(): Promise { + try { + const session = await this.getSession(); + return session !== null; + } catch { + return false; + } + } + + /** + * Release resources. + */ + async close(): Promise { + if (this.session) { + // ONNX Runtime sessions don't have a close method, but we clear the reference + this.session = null; + } + this.sessionPromise = null; + } +} + +// Type definitions for ONNX Runtime (to avoid direct dependency issues) +interface OrtModule { + Tensor: new (type: string, data: Float32Array, dims: number[]) => OrtTensor; + InferenceSession: { + create(path: string, options?: { executionProviders: string[] }): Promise; + }; +} + +interface OrtSession { + run(feeds: Record): Promise>; +} + +interface OrtTensor { + data: Float32Array; +} diff --git a/packages/search/src/services/graceful-degradation.test.ts b/packages/search/src/services/graceful-degradation.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c255b41b7536a6ba88ecb7602859fc7d9845322 --- /dev/null +++ b/packages/search/src/services/graceful-degradation.test.ts @@ -0,0 +1,245 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mockQdrantClient = { + search: vi.fn(async () => [ + { id: "1", score: 0.9, payload: { content: "test doc 1" } }, + { id: "2", score: 0.8, payload: { content: "test doc 2" } }, + { id: "3", score: 0.7, payload: { content: "test doc 3" } }, + ]), + query: vi.fn(async () => ({ + points: [ + { id: "1", score: 0.9, payload: { content: "test doc 1" } }, + { id: "2", score: 0.8, payload: { content: "test doc 2" } }, + { id: "3", score: 0.7, payload: { content: "test doc 3" } }, + ], + })), +}; + +const mockEmbedder = { + embedQuery: vi.fn(async () => new Array(384).fill(0.1)), + embedSparseQuery: vi.fn(async () => ({ indices: [100, 200, 300], values: [0.5, 0.3, 0.2] })), +}; + +const mockCodeEmbedder = { + embedQuery: vi.fn(async () => new Array(768).fill(0.2)), +}; + +const mockClassifier = { + classify: vi.fn(() => ({ strategy: "dense", alpha: 1.0 })), +}; + +// Mock reranker that can simulate failures +const mockReranker = { + rerank: vi.fn(async () => { + // Default: successful reranking + return [ + { id: "3", score: 0.95, originalIndex: 2 }, + { id: "1", score: 0.92, originalIndex: 0 }, + { id: "2", score: 0.88, originalIndex: 1 }, + ]; + }), +}; + +vi.mock("@qdrant/js-client-rest", () => ({ + QdrantClient: vi.fn(() => mockQdrantClient), +})); + +vi.mock("./text-embedder", () => ({ + TextEmbedder: vi.fn(() => mockEmbedder), +})); + +vi.mock("./code-embedder", () => ({ + CodeEmbedder: vi.fn(() => mockCodeEmbedder), +})); + +vi.mock("./classifier", () => ({ + QueryClassifier: vi.fn(() => mockClassifier), +})); + +vi.mock("./reranker", () => ({ + Reranker: vi.fn(() => mockReranker), +})); + +// Import after mocking +const { SearchRetriever } = await import("./retriever"); + +describe("Graceful Degradation", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Reset reranker to successful behavior + mockReranker.rerank.mockImplementation(async () => [ + { id: "3", score: 0.95, originalIndex: 2 }, + { id: "1", score: 0.92, originalIndex: 0 }, + { id: "2", score: 0.88, originalIndex: 1 }, + ]); + }); + + it("should return results with degraded flag when reranker throws error", async () => { + const retriever = new SearchRetriever(); + + // Make reranker throw an error + mockReranker.rerank.mockRejectedValueOnce(new Error("Model failed to load")); + + const query = { + text: "test query", + strategy: "dense" as const, + rerank: true, + limit: 3, + }; + + const results = await retriever.search(query); + + // Should still return results (fallback to original) + expect(results).toHaveLength(3); + + // All results should have degraded flag + for (const result of results) { + expect(result.degraded).toBe(true); + expect(result.degradedReason).toContain("Model failed to load"); + } + + // Should preserve original scores + expect(results[0].score).toBe(0.9); + expect(results[1].score).toBe(0.8); + expect(results[2].score).toBe(0.7); + }); + + it("should return results with degraded flag when reranker times out", async () => { + const retriever = new SearchRetriever(); + + // Make reranker timeout (takes longer than 500ms timeout) + mockReranker.rerank.mockImplementationOnce( + () => + new Promise((resolve) => { + setTimeout(() => { + resolve([{ id: "1", score: 0.95, originalIndex: 0 }]); + }, 1000); // 1 second delay + }), + ); + + const query = { + text: "test query", + strategy: "dense" as const, + rerank: true, + limit: 3, + }; + + const results = await retriever.search(query); + + // Should still return results (fallback to original) + expect(results).toHaveLength(3); + + // All results should have degraded flag + for (const result of results) { + expect(result.degraded).toBe(true); + expect(result.degradedReason).toContain("Reranking timeout"); + } + }); + + it("should not set degraded flag when reranking succeeds", async () => { + const retriever = new SearchRetriever(); + + const query = { + text: "test query", + strategy: "dense" as const, + rerank: true, + limit: 3, + }; + + const results = await retriever.search(query); + + // Should return reranked results + expect(results).toHaveLength(3); + + // No degraded flags + for (const result of results) { + expect(result.degraded).toBeUndefined(); + expect(result.degradedReason).toBeUndefined(); + } + + // Should use reranker scores + expect(results[0].score).toBe(0.95); + expect(results[1].score).toBe(0.92); + expect(results[2].score).toBe(0.88); + }); + + it("should not set degraded flag when reranking is disabled", async () => { + const retriever = new SearchRetriever(); + + const query = { + text: "test query", + strategy: "dense" as const, + rerank: false, + limit: 3, + }; + + const results = await retriever.search(query); + + // Should return original results + expect(results).toHaveLength(3); + + // No degraded flags + for (const result of results) { + expect(result.degraded).toBeUndefined(); + expect(result.degradedReason).toBeUndefined(); + } + + // Reranker should not be called + expect(mockReranker.rerank).not.toHaveBeenCalled(); + }); + + it("should handle different error types gracefully", async () => { + const retriever = new SearchRetriever(); + + // Test with string error + mockReranker.rerank.mockRejectedValueOnce("String error"); + + const query1 = { + text: "test query", + strategy: "dense" as const, + rerank: true, + limit: 3, + }; + + const results1 = await retriever.search(query1); + expect(results1[0].degraded).toBe(true); + expect(results1[0].degradedReason).toContain("String error"); + + // Test with unknown error type + mockReranker.rerank.mockRejectedValueOnce({ custom: "error" }); + + const query2 = { + text: "test query", + strategy: "dense" as const, + rerank: true, + limit: 3, + }; + + const results2 = await retriever.search(query2); + expect(results2[0].degraded).toBe(true); + expect(results2[0].degradedReason).toBeDefined(); + }); + + it("should limit degraded results to requested limit", async () => { + const retriever = new SearchRetriever(); + + // Make reranker fail + mockReranker.rerank.mockRejectedValueOnce(new Error("Reranker failed")); + + const query = { + text: "test query", + strategy: "dense" as const, + rerank: true, + limit: 2, // Request only 2 results + }; + + const results = await retriever.search(query); + + // Should return exactly 2 results (respecting limit) + expect(results).toHaveLength(2); + + // Both should be degraded + expect(results[0].degraded).toBe(true); + expect(results[1].degraded).toBe(true); + }); +}); diff --git a/packages/search/src/services/hybrid-search.integration.test.ts b/packages/search/src/services/hybrid-search.integration.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a3c00cecfd82aff707d5b1ac4aee7a8f881a7e5 --- /dev/null +++ b/packages/search/src/services/hybrid-search.integration.test.ts @@ -0,0 +1,360 @@ +/** + * Integration test for Qdrant hybrid search with SPLADE sparse vectors. + * + * This test verifies: + * 1. SPLADE sparse vectors are correctly indexed in Qdrant + * 2. Sparse-only search works with the "sparse" named vector + * 3. Hybrid search (dense + sparse with RRF fusion) returns improved results + * 4. Synonym handling: SPLADE captures semantic relationships (e.g., "car" finds "automobile") + * 5. Vocabulary mismatch: SPLADE finds relevant docs even with different terminology + * + * REQUIREMENTS: + * - Qdrant running on localhost:6333 (use `bun infra:up`) + * - Run with: bun test src/services/hybrid-search.integration.test.ts + */ + +import { QdrantClient } from "@qdrant/js-client-rest"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { SpladeEmbedder } from "./splade-embedder"; +import { TextEmbedder } from "./text-embedder"; + +const TEST_COLLECTION = "hybrid_search_test"; + +// Test documents designed to verify synonym and vocabulary mismatch handling +const TEST_DOCUMENTS = [ + { + id: 1, + content: "The automobile industry is rapidly adopting electric vehicles for sustainability.", + // Should be found by query "car" via SPLADE term expansion + }, + { + id: 2, + content: "Machine learning algorithms process large datasets to find patterns.", + // Should be found by query "AI" via SPLADE semantic understanding + }, + { + id: 3, + content: "The physician prescribed medication for the patient's condition.", + // Should be found by query "doctor" via SPLADE synonym handling + }, + { + id: 4, + content: "Software engineers develop applications using programming languages.", + // Should be found by query "developer" or "coder" + }, + { + id: 5, + content: "The quick brown fox jumps over the lazy dog.", + // Control document - should NOT match semantic queries + }, +]; + +// Queries designed to test SPLADE's term expansion and synonym handling +const TEST_QUERIES = [ + { + query: "car electric vehicle", + expectedDocIds: [1], // Should find "automobile" doc + description: "Synonym: car → automobile", + }, + { + query: "artificial intelligence", + expectedDocIds: [2], // Should find "machine learning" doc + description: "Related concept: AI → machine learning", + }, + { + query: "doctor treatment", + expectedDocIds: [3], // Should find "physician" doc + description: "Synonym: doctor → physician", + }, + { + query: "developer coding", + expectedDocIds: [4], // Should find "software engineer" doc + description: "Related: developer → software engineer", + }, +]; + +describe("Hybrid Search Integration", () => { + let client: QdrantClient; + let spladeEmbedder: SpladeEmbedder; + let textEmbedder: TextEmbedder; + + beforeAll(async () => { + // Initialize clients and embedders + client = new QdrantClient({ url: "http://localhost:6333" }); + spladeEmbedder = new SpladeEmbedder(); + textEmbedder = new TextEmbedder(); + + // Wait for SPLADE model to load (first call is slow) + await spladeEmbedder.preload(); + + // Clean up and create test collection + try { + await client.deleteCollection(TEST_COLLECTION); + } catch { + // Collection may not exist + } + + await client.createCollection(TEST_COLLECTION, { + vectors: { + text_dense: { + size: 384, // e5-small dimensions + distance: "Cosine", + }, + }, + sparse_vectors: { + sparse: { + index: { + on_disk: false, + datatype: "float16", + }, + }, + }, + }); + + // Index test documents with both dense and sparse vectors + for (const doc of TEST_DOCUMENTS) { + const [denseVector, sparseVector] = await Promise.all([ + textEmbedder.embed(doc.content), + spladeEmbedder.embed(doc.content), + ]); + + await client.upsert(TEST_COLLECTION, { + points: [ + { + id: doc.id, + vector: { + text_dense: denseVector, + sparse: sparseVector, + }, + payload: { + content: doc.content, + }, + }, + ], + }); + } + + // Allow time for indexing + await new Promise((resolve) => setTimeout(resolve, 500)); + }, 120000); // 2 minute timeout for model loading + + afterAll(async () => { + // Cleanup + try { + await client.deleteCollection(TEST_COLLECTION); + } catch { + // Ignore cleanup errors + } + }); + + describe("Sparse Vector Search", () => { + it("should perform sparse-only search using SPLADE vectors", async () => { + const queryText = "automobile electric"; + const sparseQuery = await spladeEmbedder.embedQuery(queryText); + + const results = await client.query(TEST_COLLECTION, { + query: { + indices: sparseQuery.indices, + values: sparseQuery.values, + }, + using: "sparse", + limit: 5, + with_payload: true, + }); + + expect(results.points.length).toBeGreaterThan(0); + // The automobile/electric document should be in results + const hasExpectedDoc = results.points.some((p) => p.id === 1); + expect(hasExpectedDoc).toBe(true); + }); + + it("should return sparse vectors with correct format", async () => { + const sparseVector = await spladeEmbedder.embed("test query"); + + expect(sparseVector).toHaveProperty("indices"); + expect(sparseVector).toHaveProperty("values"); + expect(Array.isArray(sparseVector.indices)).toBe(true); + expect(Array.isArray(sparseVector.values)).toBe(true); + expect(sparseVector.indices.length).toBe(sparseVector.values.length); + + // Indices should be sorted (Qdrant requirement) + for (let i = 1; i < sparseVector.indices.length; i++) { + expect(sparseVector.indices[i]).toBeGreaterThan(sparseVector.indices[i - 1]); + } + + // Values should be positive + for (const val of sparseVector.values) { + expect(val).toBeGreaterThan(0); + } + }); + }); + + describe("Synonym Handling", () => { + for (const testCase of TEST_QUERIES) { + it(`should handle ${testCase.description}`, async () => { + const sparseQuery = await spladeEmbedder.embedQuery(testCase.query); + + const results = await client.query(TEST_COLLECTION, { + query: { + indices: sparseQuery.indices, + values: sparseQuery.values, + }, + using: "sparse", + limit: 5, + with_payload: true, + }); + + // Check if expected documents appear in top results + const topIds = results.points.slice(0, 3).map((p) => p.id); + const foundExpected = testCase.expectedDocIds.some((id) => topIds.includes(id)); + + // Log for debugging + console.log(`Query: "${testCase.query}"`); + console.log(`Top results: ${topIds.join(", ")}`); + console.log(`Expected: ${testCase.expectedDocIds.join(", ")}`); + console.log(`Found: ${foundExpected}`); + + expect(foundExpected).toBe(true); + }); + } + }); + + describe("Hybrid Search (Dense + Sparse with RRF)", () => { + it("should perform hybrid search using prefetch with RRF fusion", async () => { + const queryText = "car electric vehicle"; + + const [denseQuery, sparseQuery] = await Promise.all([ + textEmbedder.embedQuery(queryText), + spladeEmbedder.embedQuery(queryText), + ]); + + // Hybrid search using prefetch + RRF fusion + const results = await client.query(TEST_COLLECTION, { + prefetch: [ + { + query: denseQuery, + using: "text_dense", + limit: 10, + }, + { + query: { + indices: sparseQuery.indices, + values: sparseQuery.values, + }, + using: "sparse", + limit: 10, + }, + ], + query: { fusion: "rrf" }, + limit: 5, + with_payload: true, + }); + + expect(results.points.length).toBeGreaterThan(0); + + // Log results for analysis + console.log("\nHybrid search results for:", queryText); + for (const point of results.points) { + console.log(` ID: ${point.id}, Score: ${point.score?.toFixed(4)}`); + } + + // Automobile doc should be highly ranked + const topIds = results.points.slice(0, 3).map((p) => p.id); + expect(topIds).toContain(1); + }); + + it("should rank hybrid results better than dense-only for vocabulary mismatch", async () => { + const queryText = "doctor treatment"; // Query uses "doctor", doc has "physician" + + const [denseQuery, sparseQuery] = await Promise.all([ + textEmbedder.embedQuery(queryText), + spladeEmbedder.embedQuery(queryText), + ]); + + // Dense-only search + const denseResults = await client.query(TEST_COLLECTION, { + query: denseQuery, + using: "text_dense", + limit: 5, + with_payload: true, + }); + + // Hybrid search + const hybridResults = await client.query(TEST_COLLECTION, { + prefetch: [ + { + query: denseQuery, + using: "text_dense", + limit: 10, + }, + { + query: { + indices: sparseQuery.indices, + values: sparseQuery.values, + }, + using: "sparse", + limit: 10, + }, + ], + query: { fusion: "rrf" }, + limit: 5, + with_payload: true, + }); + + console.log("\nDense-only results for 'doctor treatment':"); + for (const point of denseResults.points.slice(0, 3)) { + console.log(` ID: ${point.id}, Score: ${point.score?.toFixed(4)}`); + } + + console.log("Hybrid results for 'doctor treatment':"); + for (const point of hybridResults.points.slice(0, 3)) { + console.log(` ID: ${point.id}, Score: ${point.score?.toFixed(4)}`); + } + + // Hybrid should find the physician doc (ID 3) in top results + const hybridTopIds = hybridResults.points.slice(0, 3).map((p) => p.id); + expect(hybridTopIds).toContain(3); + }); + }); + + describe("SPLADE Term Expansion Analysis", () => { + it("should show meaningful term expansion for domain concepts", async () => { + const queryText = "machine learning"; + const sparseVector = await spladeEmbedder.embed(queryText); + + console.log(`\nSPLADE vector for "${queryText}":`); + console.log(` Non-zero dimensions: ${sparseVector.indices.length}`); + console.log(` Sparsity: ${((1 - sparseVector.indices.length / 30522) * 100).toFixed(2)}%`); + console.log(` Top weight: ${Math.max(...sparseVector.values).toFixed(4)}`); + + // SPLADE should produce reasonably sparse vectors + expect(sparseVector.indices.length).toBeLessThan(1000); + expect(sparseVector.indices.length).toBeGreaterThan(10); + }); + + it("should produce different sparse vectors for semantically different queries", async () => { + const query1 = "car automobile vehicle"; + const query2 = "programming software code"; + + const [sparse1, sparse2] = await Promise.all([ + spladeEmbedder.embed(query1), + spladeEmbedder.embed(query2), + ]); + + // Calculate index overlap + const set1 = new Set(sparse1.indices); + const set2 = new Set(sparse2.indices); + const intersection = sparse1.indices.filter((i) => set2.has(i)); + const overlapRatio = intersection.length / Math.min(set1.size, set2.size); + + console.log(`\nIndex overlap between different domains:`); + console.log(` Query 1: "${query1}" (${set1.size} terms)`); + console.log(` Query 2: "${query2}" (${set2.size} terms)`); + console.log(` Overlap: ${intersection.length} terms (${(overlapRatio * 100).toFixed(1)}%)`); + + // Different domain queries should have limited overlap + // Note: BERT's vocabulary includes common subwords, so some overlap is expected + expect(overlapRatio).toBeLessThan(0.6); + }); + }); +}); diff --git a/packages/search/src/services/indexer.test.ts b/packages/search/src/services/indexer.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfde2d7b1087f53ab5020b0caa5abbb6aa683b21 --- /dev/null +++ b/packages/search/src/services/indexer.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from "vitest"; +import { SearchIndexer } from "./indexer"; + +const mockQdrantClient = { + upsert: vi.fn(async () => {}), +}; + +const mockEmbedder = { + embed: vi.fn(async () => new Array(384).fill(0.1)), + embedSparse: vi.fn(async () => ({ indices: [100, 200, 300], values: [0.5, 0.3, 0.2] })), +}; + +vi.mock("@qdrant/js-client-rest", () => ({ + QdrantClient: vi.fn().mockImplementation(() => mockQdrantClient), +})); + +vi.mock("./text-embedder", () => ({ + TextEmbedder: vi.fn().mockImplementation(() => ({ + embed: mockEmbedder.embed, + embedSparse: mockEmbedder.embedSparse, + })), +})); + +vi.mock("./code-embedder", () => ({ + CodeEmbedder: vi.fn().mockImplementation(() => ({ + embed: mockEmbedder.embed, + })), +})); + +describe("SearchIndexer", () => { + it("should index a thought node using text embedder", async () => { + const indexer = new SearchIndexer(); + const node = { + id: "node-1", + labels: ["Thought"], + content: "This is a thought", + session_id: "session-1", + }; + + await indexer.indexNode(node); + + expect(mockEmbedder.embed).toHaveBeenCalledWith("This is a thought"); + expect(mockQdrantClient.upsert).toHaveBeenCalled(); + const call = mockQdrantClient.upsert.mock.calls[0]; + expect(call[0]).toBe("engram_memory"); + expect(call[1].points[0].id).toBe("node-1"); + expect(call[1].points[0].payload.type).toBe("thought"); + }); + + it("should index a code node using code embedder", async () => { + const indexer = new SearchIndexer(); + const node = { + id: "node-2", + labels: ["DiffHunk"], + patch_content: "const x = 1;", + session_id: "session-1", + }; + + await indexer.indexNode(node); + + expect(mockEmbedder.embed).toHaveBeenCalledWith("const x = 1;"); + expect(mockQdrantClient.upsert).toHaveBeenCalled(); + const call = mockQdrantClient.upsert.mock.calls[mockQdrantClient.upsert.mock.calls.length - 1]; + expect(call[1].points[0].payload.type).toBe("code"); + }); +}); diff --git a/packages/search/src/services/indexer.ts b/packages/search/src/services/indexer.ts new file mode 100644 index 0000000000000000000000000000000000000000..f600f6314f49810ee70973559de15b64742b2a19 --- /dev/null +++ b/packages/search/src/services/indexer.ts @@ -0,0 +1,97 @@ +import { QdrantClient } from "@qdrant/js-client-rest"; +import { CodeEmbedder } from "./code-embedder"; +import { ColBERTEmbedder } from "./colbert-embedder"; +import { TextEmbedder } from "./text-embedder"; + +export interface IndexableNode { + id: string; + labels: string[]; + content?: string; // Thought content (legacy) + patch_content?: string; // DiffHunk content + session_id?: string; + file_path?: string; + timestamp?: number; // created_at / vt_start + // Properties bag from memory service + properties?: { + content?: string; + role?: string; + type?: string; + }; +} + +export class SearchIndexer { + private client: QdrantClient; + private textEmbedder: TextEmbedder; + private codeEmbedder: CodeEmbedder; + private colbertEmbedder: ColBERTEmbedder; + private collectionName = "engram_memory"; + + constructor(url: string = "http://localhost:6333") { + this.client = new QdrantClient({ url }); + this.textEmbedder = new TextEmbedder(); + this.codeEmbedder = new CodeEmbedder(); + this.colbertEmbedder = new ColBERTEmbedder(); + } + + async indexNode(node: IndexableNode) { + const isCode = node.labels.includes("DiffHunk") || node.labels.includes("CodeArtifact"); + // Support both direct content and properties.content (from memory service) + const content = isCode ? node.patch_content : node.content || node.properties?.content; + + if (!content || content.trim() === "") return; // Nothing to index + + // Generate sparse vector for hybrid search (BM25-based keyword matching) + const sparseVector = await this.textEmbedder.embedSparse(content); + + // Generate ColBERT token embeddings for late interaction reranking + const colbertEmbeddingsRaw = await this.colbertEmbedder.encodeDocument(content); + // Convert Float32Array[] to number[][] for Qdrant multivector compatibility + const colbertEmbeddings = colbertEmbeddingsRaw.map((token) => Array.from(token)); + + // Payload + const payload = { + content: content, + node_id: node.id, + session_id: node.session_id || "unknown", + type: isCode ? "code" : "thought", + timestamp: node.timestamp || Date.now(), + file_path: node.file_path, + }; + + // Generate vector and use the appropriate named vector field + // Code uses code_dense (768d nomic-embed-text-v1) + // Text uses text_dense (384d e5-small) + // Both use colbert multivector (128d per token, jina-colbert-v2) + if (isCode) { + const codeVector = await this.codeEmbedder.embed(content); + await this.client.upsert(this.collectionName, { + points: [ + { + id: node.id, + vector: { + code_dense: codeVector, + sparse: sparseVector, + colbert: colbertEmbeddings, + }, + payload, + }, + ], + }); + } else { + const textVector = await this.textEmbedder.embed(content); + await this.client.upsert(this.collectionName, { + points: [ + { + id: node.id, + vector: { + text_dense: textVector, + sparse: sparseVector, + colbert: colbertEmbeddings, + }, + payload, + }, + ], + }); + } + } +} diff --git a/packages/search/src/services/lazy-loading.test.ts b/packages/search/src/services/lazy-loading.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2cb9eb5f2b88a025403204ab56824c869cc1d060 --- /dev/null +++ b/packages/search/src/services/lazy-loading.test.ts @@ -0,0 +1,340 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { BatchedReranker } from "./batched-reranker"; + +// Mock the @huggingface/transformers pipeline +const { mockPipeline } = vi.hoisted(() => { + const mockPipeline = vi.fn(); + return { mockPipeline }; +}); + +vi.mock("@huggingface/transformers", () => ({ + pipeline: mockPipeline, +})); + +describe("Lazy Model Loading with Idle Unload", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllTimers(); + vi.clearAllMocks(); + + // Clear all static state + BatchedReranker.unloadAll(); + + // Setup mock pipeline to return a classifier function + mockPipeline.mockResolvedValue(async (_input: { text: string; text_pair: string }) => { + return [{ label: "LABEL_0", score: 0.95 }]; + }); + }); + + afterEach(() => { + BatchedReranker.unloadAll(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + describe("Lazy Loading", () => { + it("should not load model on construction", () => { + new BatchedReranker({ + model: "test-model", + }); + + // Pipeline should not be called yet + expect(mockPipeline).not.toHaveBeenCalled(); + }); + + it("should load model on first rerank call", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + idleTimeoutMs: 60000, + }); + + // Load model by calling rerank + await reranker.rerank("test query", [{ id: "1", content: "test doc" }], 1); + + // Pipeline should be called once + expect(mockPipeline).toHaveBeenCalledTimes(1); + expect(mockPipeline).toHaveBeenCalledWith("text-classification", "test-model", { + dtype: "q8", + }); + }); + + it("should reuse loaded model on subsequent calls", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + idleTimeoutMs: 60000, + }); + + // First call loads model + await reranker.rerank("query 1", [{ id: "1", content: "doc 1" }], 1); + + // Second call reuses model + await reranker.rerank("query 2", [{ id: "2", content: "doc 2" }], 1); + + // Pipeline should only be called once (model cached) + expect(mockPipeline).toHaveBeenCalledTimes(1); + }); + + it("should share model instances across reranker instances with same config", async () => { + const reranker1 = new BatchedReranker({ + model: "test-model", + quantization: "q8", + }); + + const reranker2 = new BatchedReranker({ + model: "test-model", + quantization: "q8", + }); + + // Both rerankers use same model + await reranker1.rerank("query", [{ id: "1", content: "doc" }], 1); + await reranker2.rerank("query", [{ id: "2", content: "doc" }], 1); + + // Pipeline should only be called once (shared instance) + expect(mockPipeline).toHaveBeenCalledTimes(1); + }); + + it("should load separate models for different configs", async () => { + const reranker1 = new BatchedReranker({ + model: "model-a", + }); + + const reranker2 = new BatchedReranker({ + model: "model-b", + }); + + // Different models + await reranker1.rerank("query", [{ id: "1", content: "doc" }], 1); + await reranker2.rerank("query", [{ id: "2", content: "doc" }], 1); + + // Pipeline should be called twice (different models) + expect(mockPipeline).toHaveBeenCalledTimes(2); + }); + }); + + describe("Idle Unload", () => { + it("should unload model after idle timeout", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + idleTimeoutMs: 5000, // 5 seconds + }); + + // Load model + await reranker.rerank("query", [{ id: "1", content: "doc" }], 1); + + // Model should be loaded + let loaded = BatchedReranker.getLoadedModels(); + expect(loaded.length).toBe(1); + expect(loaded[0].key).toBe("test-model:q8"); + + // Advance time past idle timeout + vi.advanceTimersByTime(6000); + + // Model should be unloaded + loaded = BatchedReranker.getLoadedModels(); + expect(loaded.length).toBe(0); + }); + + it("should reset idle timer on each rerank call", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + idleTimeoutMs: 5000, + }); + + // Load model + await reranker.rerank("query", [{ id: "1", content: "doc" }], 1); + + // Wait 3 seconds (less than timeout) + vi.advanceTimersByTime(3000); + + // Use model again (resets timer) + await reranker.rerank("query", [{ id: "2", content: "doc" }], 1); + + // Wait another 3 seconds (total 6s, but timer was reset) + vi.advanceTimersByTime(3000); + + // Model should still be loaded (timer was reset) + const loaded = BatchedReranker.getLoadedModels(); + expect(loaded.length).toBe(1); + }); + + it("should reload model if used after unload", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + idleTimeoutMs: 5000, + }); + + // First load + await reranker.rerank("query", [{ id: "1", content: "doc" }], 1); + expect(mockPipeline).toHaveBeenCalledTimes(1); + + // Unload after timeout + vi.advanceTimersByTime(6000); + + // Model should be unloaded + expect(BatchedReranker.getLoadedModels().length).toBe(0); + + // Use again - should reload + await reranker.rerank("query", [{ id: "2", content: "doc" }], 1); + + // Pipeline should be called again (model reloaded) + expect(mockPipeline).toHaveBeenCalledTimes(2); + }); + + it("should track idle time correctly", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + idleTimeoutMs: 10000, + }); + + // Load model + await reranker.rerank("query", [{ id: "1", content: "doc" }], 1); + + // Check idle time immediately + let loaded = BatchedReranker.getLoadedModels(); + expect(loaded[0].idleTimeMs).toBeLessThan(100); // Should be very small + + // Wait 2 seconds + vi.advanceTimersByTime(2000); + + // Check idle time again + loaded = BatchedReranker.getLoadedModels(); + expect(loaded[0].idleTimeMs).toBeGreaterThan(1900); + expect(loaded[0].idleTimeMs).toBeLessThan(2100); + }); + + it("should handle multiple models with different idle times", async () => { + const reranker1 = new BatchedReranker({ + model: "model-a", + idleTimeoutMs: 5000, + }); + + const reranker2 = new BatchedReranker({ + model: "model-b", + idleTimeoutMs: 10000, + }); + + // Load both models + await reranker1.rerank("query", [{ id: "1", content: "doc" }], 1); + await reranker2.rerank("query", [{ id: "2", content: "doc" }], 1); + + // Both should be loaded + expect(BatchedReranker.getLoadedModels().length).toBe(2); + + // Advance 6 seconds (model-a should unload, model-b should stay) + vi.advanceTimersByTime(6000); + + const loaded = BatchedReranker.getLoadedModels(); + expect(loaded.length).toBe(1); + expect(loaded[0].key).toBe("model-b:q8"); + + // Advance another 5 seconds (model-b should unload) + vi.advanceTimersByTime(5000); + + expect(BatchedReranker.getLoadedModels().length).toBe(0); + }); + }); + + describe("Manual Unload", () => { + it("should unload specific model manually", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + quantization: "q8", + }); + + // Load model + await reranker.rerank("query", [{ id: "1", content: "doc" }], 1); + + // Model should be loaded + expect(BatchedReranker.getLoadedModels().length).toBe(1); + + // Manual unload + BatchedReranker.unloadModel("test-model", "q8"); + + // Model should be unloaded + expect(BatchedReranker.getLoadedModels().length).toBe(0); + }); + + it("should unload all models manually", async () => { + const reranker1 = new BatchedReranker({ model: "model-a" }); + const reranker2 = new BatchedReranker({ model: "model-b" }); + + // Load both + await reranker1.rerank("query", [{ id: "1", content: "doc" }], 1); + await reranker2.rerank("query", [{ id: "2", content: "doc" }], 1); + + // Both loaded + expect(BatchedReranker.getLoadedModels().length).toBe(2); + + // Unload all + BatchedReranker.unloadAll(); + + // All unloaded + expect(BatchedReranker.getLoadedModels().length).toBe(0); + }); + + it("should clear idle timers when unloading all", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + idleTimeoutMs: 60000, + }); + + // Load model + await reranker.rerank("query", [{ id: "1", content: "doc" }], 1); + + // Unload all (should clear timers) + BatchedReranker.unloadAll(); + + // Advance time - should not throw or cause issues + vi.advanceTimersByTime(70000); + + // Model should stay unloaded + expect(BatchedReranker.getLoadedModels().length).toBe(0); + }); + }); + + describe("Warmup", () => { + it("should preload model with warmup", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + }); + + // Warmup (preload) + await reranker.warmup(); + + // Model should be loaded without calling rerank + expect(mockPipeline).toHaveBeenCalledTimes(1); + expect(BatchedReranker.getLoadedModels().length).toBe(1); + }); + }); + + describe("Concurrent Loading", () => { + it("should handle concurrent rerank calls during model load", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + }); + + // Make multiple concurrent calls + const promises = [ + reranker.rerank("query1", [{ id: "1", content: "doc1" }], 1), + reranker.rerank("query2", [{ id: "2", content: "doc2" }], 1), + reranker.rerank("query3", [{ id: "3", content: "doc3" }], 1), + ]; + + await Promise.all(promises); + + // Pipeline should only be called once (concurrent calls wait for same load) + expect(mockPipeline).toHaveBeenCalledTimes(1); + }); + }); + + describe("Default Idle Timeout", () => { + it("should use 5 minutes as default idle timeout", async () => { + const reranker = new BatchedReranker({ + model: "test-model", + }); + + // Check default timeout (5 minutes = 300000ms) + expect(reranker.idleTimeoutMs).toBe(5 * 60 * 1000); + }); + }); +}); diff --git a/packages/search/src/services/learned-fusion.test.ts b/packages/search/src/services/learned-fusion.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..59711ad31005333221a21e924c90a18b502ccba0 --- /dev/null +++ b/packages/search/src/services/learned-fusion.test.ts @@ -0,0 +1,259 @@ +import { describe, expect, it } from "vitest"; +import { adaptiveRRF, type FusionSearchResult, LearnedFusion } from "./learned-fusion"; + +describe("LearnedFusion", () => { + const makeDenseResults = (): FusionSearchResult[] => [ + { id: "doc1", content: "Document 1 about machine learning", score: 0.9 }, + { id: "doc2", content: "Document 2 about deep learning", score: 0.8 }, + { id: "doc3", content: "Document 3 about neural networks", score: 0.7 }, + ]; + + const makeSparseResults = (): FusionSearchResult[] => [ + { id: "doc2", content: "Document 2 about deep learning", score: 0.95 }, + { id: "doc4", content: "Document 4 about transformers", score: 0.85 }, + { id: "doc1", content: "Document 1 about machine learning", score: 0.75 }, + ]; + + describe("fuse", () => { + it("should combine dense and sparse results", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", // Will use fallback + }); + + const denseResults = makeDenseResults(); + const sparseResults = makeSparseResults(); + + const fused = await fusion.fuse("What is machine learning?", denseResults, sparseResults); + + // Should have results from both sets + expect(fused.length).toBeGreaterThan(0); + + // doc1 and doc2 appear in both, should be present + const ids = fused.map((r) => r.id); + expect(ids).toContain("doc1"); + expect(ids).toContain("doc2"); + }); + + it("should return results sorted by fused score", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", + }); + + const denseResults = makeDenseResults(); + const sparseResults = makeSparseResults(); + + const fused = await fusion.fuse("test query", denseResults, sparseResults); + + // Scores should be in descending order + for (let i = 1; i < fused.length; i++) { + expect(fused[i].score).toBeLessThanOrEqual(fused[i - 1].score); + } + }); + + it("should handle empty dense results", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", + }); + + const sparseResults = makeSparseResults(); + const fused = await fusion.fuse("test query", [], sparseResults); + + // Should still return sparse results + expect(fused.length).toBe(sparseResults.length); + }); + + it("should handle empty sparse results", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", + }); + + const denseResults = makeDenseResults(); + const fused = await fusion.fuse("test query", denseResults, []); + + // Should still return dense results + expect(fused.length).toBe(denseResults.length); + }); + + it("should handle rerank results when provided", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", + }); + + const denseResults = makeDenseResults(); + const sparseResults = makeSparseResults(); + const rerankResults: FusionSearchResult[] = [ + { id: "doc3", content: "Document 3", score: 0.99 }, // Rerank boosts doc3 + { id: "doc1", content: "Document 1", score: 0.95 }, + ]; + + const fused = await fusion.fuse("test query", denseResults, sparseResults, rerankResults); + + // Should include all documents + const ids = fused.map((r) => r.id); + expect(ids).toContain("doc1"); + expect(ids).toContain("doc3"); + }); + }); + + describe("fuseWithWeights", () => { + it("should apply explicit weights correctly", () => { + const fusion = new LearnedFusion({ + normalizeScores: false, // Disable normalization for predictable testing + }); + + const denseResults: FusionSearchResult[] = [{ id: "doc1", content: "Doc 1", score: 1.0 }]; + const sparseResults: FusionSearchResult[] = [{ id: "doc1", content: "Doc 1", score: 0.5 }]; + + const weights = { dense: 0.6, sparse: 0.4, rerank: 0.0 }; + const fused = fusion.fuseWithWeights(weights, denseResults, sparseResults); + + // Score should be 0.6 * 1.0 + 0.4 * 0.5 = 0.8 + expect(fused.length).toBe(1); + expect(fused[0].score).toBeCloseTo(0.8, 2); + }); + + it("should handle documents appearing in only one result set", () => { + const fusion = new LearnedFusion({ + normalizeScores: false, + }); + + const denseResults: FusionSearchResult[] = [{ id: "doc1", content: "Doc 1", score: 1.0 }]; + const sparseResults: FusionSearchResult[] = [{ id: "doc2", content: "Doc 2", score: 1.0 }]; + + const weights = { dense: 0.5, sparse: 0.5, rerank: 0.0 }; + const fused = fusion.fuseWithWeights(weights, denseResults, sparseResults); + + // Should have both documents + expect(fused.length).toBe(2); + + // doc1 only has dense score: 0.5 * 1.0 = 0.5 + // doc2 only has sparse score: 0.5 * 1.0 = 0.5 + const doc1 = fused.find((r) => r.id === "doc1"); + const doc2 = fused.find((r) => r.id === "doc2"); + expect(doc1?.score).toBeCloseTo(0.5, 2); + expect(doc2?.score).toBeCloseTo(0.5, 2); + }); + }); + + describe("getWeights", () => { + it("should return predicted weights for a query", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", + }); + + const weights = await fusion.getWeights("What is deep learning?"); + + expect(weights.dense).toBeDefined(); + expect(weights.sparse).toBeDefined(); + expect(weights.rerank).toBeDefined(); + + const sum = weights.dense + weights.sparse + weights.rerank; + expect(sum).toBeCloseTo(1.0, 1); + }); + }); + + describe("isModelAvailable", () => { + it("should return false when model does not exist", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", + }); + + const available = await fusion.isModelAvailable(); + expect(available).toBe(false); + }); + }); + + describe("score normalization", () => { + it("should normalize scores to 0-1 range by default", async () => { + const fusion = new LearnedFusion({ + modelPath: "non-existent-model.onnx", + normalizeScores: true, + }); + + // Results with varying score ranges + const denseResults: FusionSearchResult[] = [ + { id: "doc1", content: "Doc 1", score: 100 }, + { id: "doc2", content: "Doc 2", score: 50 }, + ]; + const sparseResults: FusionSearchResult[] = [ + { id: "doc1", content: "Doc 1", score: 0.9 }, + { id: "doc2", content: "Doc 2", score: 0.1 }, + ]; + + const fused = await fusion.fuse("test", denseResults, sparseResults); + + // All scores should be reasonable (not the raw 100 or 50) + for (const result of fused) { + expect(result.score).toBeLessThanOrEqual(1.5); // Allow some headroom + expect(result.score).toBeGreaterThanOrEqual(0); + } + }); + }); +}); + +describe("adaptiveRRF", () => { + it("should combine results using reciprocal rank fusion", () => { + const denseResults: FusionSearchResult[] = [ + { id: "doc1", content: "Doc 1", score: 0.9 }, + { id: "doc2", content: "Doc 2", score: 0.8 }, + ]; + const sparseResults: FusionSearchResult[] = [ + { id: "doc2", content: "Doc 2", score: 0.95 }, + { id: "doc3", content: "Doc 3", score: 0.85 }, + ]; + + const fused = adaptiveRRF("test query", denseResults, sparseResults); + + // Should contain all unique documents + const ids = fused.map((r) => r.id); + expect(ids).toContain("doc1"); + expect(ids).toContain("doc2"); + expect(ids).toContain("doc3"); + + // doc2 appears in both, should have higher RRF score + const doc2Index = ids.indexOf("doc2"); + expect(doc2Index).toBeLessThan(2); // Should be near the top + }); + + it("should return results sorted by RRF score", () => { + const denseResults: FusionSearchResult[] = [ + { id: "doc1", content: "Doc 1", score: 0.9 }, + { id: "doc2", content: "Doc 2", score: 0.8 }, + ]; + const sparseResults: FusionSearchResult[] = [ + { id: "doc2", content: "Doc 2", score: 0.95 }, + { id: "doc1", content: "Doc 1", score: 0.85 }, + ]; + + const fused = adaptiveRRF("test query", denseResults, sparseResults); + + // Results should be sorted by score (descending) + for (let i = 1; i < fused.length; i++) { + expect(fused[i].score).toBeLessThanOrEqual(fused[i - 1].score); + } + }); + + it("should use adaptive k values based on query characteristics", () => { + // Query with entities should affect sparse k value + const withEntities = adaptiveRRF( + "Tell me about Microsoft Azure", + [{ id: "doc1", content: "Doc 1", score: 0.9 }], + [{ id: "doc1", content: "Doc 1", score: 0.9 }], + ); + + const withoutEntities = adaptiveRRF( + "how to do something", + [{ id: "doc1", content: "Doc 1", score: 0.9 }], + [{ id: "doc1", content: "Doc 1", score: 0.9 }], + ); + + // Both should work without error + expect(withEntities.length).toBe(1); + expect(withoutEntities.length).toBe(1); + }); + + it("should handle empty result sets", () => { + const fused = adaptiveRRF("test", [], []); + expect(fused).toEqual([]); + }); +}); diff --git a/packages/search/src/services/learned-fusion.ts b/packages/search/src/services/learned-fusion.ts new file mode 100644 index 0000000000000000000000000000000000000000..44b72140c2d14ac908b605e2d02677cf2d12d1f0 --- /dev/null +++ b/packages/search/src/services/learned-fusion.ts @@ -0,0 +1,331 @@ +/** + * Learned fusion for combining dense, sparse, and rerank retrieval results. + * + * Uses a trained MLP to predict query-adaptive fusion weights, then applies + * weighted score combination to produce final rankings. + * + * @see docs/plans/retrieval-v2/06-learned-fusion.md + */ + +import { FusionWeightPredictor, type FusionWeights } from "./fusion-predictor.js"; +import { QueryFeatureExtractor } from "./query-features.js"; + +/** + * Search result with relevance score for fusion. + */ +export interface FusionSearchResult { + /** Document identifier */ + id: string; + /** Document content */ + content: string; + /** Relevance score (higher is better) */ + score: number; + /** Optional metadata */ + metadata?: Record; +} + +/** + * Configuration for learned fusion. + */ +export interface LearnedFusionConfig { + /** Path to the ONNX model file */ + modelPath?: string; + /** Whether to normalize scores before fusion */ + normalizeScores?: boolean; + /** Default weights to use when model is unavailable */ + fallbackWeights?: FusionWeights; +} + +const DEFAULT_CONFIG: Required = { + modelPath: "models/fusion_mlp.onnx", + normalizeScores: true, + fallbackWeights: { dense: 0.4, sparse: 0.3, rerank: 0.3 }, +}; + +/** + * Internal structure for tracking scores per document. + */ +interface FusedScore { + result: FusionSearchResult; + scores: { + dense?: number; + sparse?: number; + rerank?: number; + }; +} + +/** + * Performs learned fusion of dense, sparse, and rerank retrieval results. + * + * Unlike fixed RRF (k=60), this approach uses query-adaptive weights + * predicted by a trained MLP. This improves accuracy by 1-2% overall + * and reduces variance across different query types. + * + * @example + * ```typescript + * const fusion = new LearnedFusion(); + * + * const query = "Who founded Microsoft in 1975?"; + * const denseResults = await denseRetriever.search(query, 10); + * const sparseResults = await sparseRetriever.search(query, 10); + * const rerankResults = await reranker.rerank(query, candidates); + * + * const fusedResults = await fusion.fuse(query, denseResults, sparseResults, rerankResults); + * ``` + */ +export class LearnedFusion { + private featureExtractor: QueryFeatureExtractor; + private weightPredictor: FusionWeightPredictor; + private config: Required; + + constructor(config: LearnedFusionConfig = {}) { + this.config = { ...DEFAULT_CONFIG, ...config }; + this.featureExtractor = new QueryFeatureExtractor(); + this.weightPredictor = new FusionWeightPredictor({ + modelPath: this.config.modelPath, + fallbackWeights: this.config.fallbackWeights, + }); + } + + /** + * Fuse results from dense, sparse, and optional rerank stages. + * + * @param query - The search query + * @param denseResults - Results from dense (semantic) retrieval + * @param sparseResults - Results from sparse (keyword) retrieval + * @param rerankResults - Optional results from reranking stage + * @returns Fused and re-ranked results + */ + async fuse( + query: string, + denseResults: FusionSearchResult[], + sparseResults: FusionSearchResult[], + rerankResults?: FusionSearchResult[], + ): Promise { + // Extract query features and predict weights + const features = this.featureExtractor.extract(query); + const weights = await this.weightPredictor.predict(features); + + // Build score map across all result sets + const scoreMap = new Map(); + + // Normalize scores if configured + const normDense = this.config.normalizeScores + ? this.normalizeScores(denseResults) + : denseResults; + const normSparse = this.config.normalizeScores + ? this.normalizeScores(sparseResults) + : sparseResults; + const normRerank = rerankResults + ? this.config.normalizeScores + ? this.normalizeScores(rerankResults) + : rerankResults + : undefined; + + // Add dense scores + for (const result of normDense) { + const existing = scoreMap.get(result.id) ?? { result, scores: {} }; + existing.scores.dense = result.score; + scoreMap.set(result.id, existing); + } + + // Add sparse scores + for (const result of normSparse) { + const existing = scoreMap.get(result.id) ?? { result, scores: {} }; + existing.scores.sparse = result.score; + scoreMap.set(result.id, existing); + } + + // Add rerank scores (only for documents already retrieved) + if (normRerank) { + for (const result of normRerank) { + const existing = scoreMap.get(result.id); + if (existing) { + existing.scores.rerank = result.score; + } + } + } + + // Calculate weighted fusion scores + const fused = Array.from(scoreMap.values()).map(({ result, scores }) => { + // Apply weights with zero for missing scores + const finalScore = + (scores.dense ?? 0) * weights.dense + + (scores.sparse ?? 0) * weights.sparse + + (scores.rerank ?? 0) * weights.rerank; + + return { ...result, score: finalScore }; + }); + + // Sort by fused score (descending) + return fused.sort((a, b) => b.score - a.score); + } + + /** + * Fuse results with explicit weights (for testing or override). + * + * @param weights - Explicit fusion weights to use + * @param denseResults - Dense retrieval results + * @param sparseResults - Sparse retrieval results + * @param rerankResults - Optional rerank results + * @returns Fused results + */ + fuseWithWeights( + weights: FusionWeights, + denseResults: FusionSearchResult[], + sparseResults: FusionSearchResult[], + rerankResults?: FusionSearchResult[], + ): FusionSearchResult[] { + const scoreMap = new Map(); + + const normDense = this.config.normalizeScores + ? this.normalizeScores(denseResults) + : denseResults; + const normSparse = this.config.normalizeScores + ? this.normalizeScores(sparseResults) + : sparseResults; + const normRerank = rerankResults + ? this.config.normalizeScores + ? this.normalizeScores(rerankResults) + : rerankResults + : undefined; + + for (const result of normDense) { + const existing = scoreMap.get(result.id) ?? { result, scores: {} }; + existing.scores.dense = result.score; + scoreMap.set(result.id, existing); + } + + for (const result of normSparse) { + const existing = scoreMap.get(result.id) ?? { result, scores: {} }; + existing.scores.sparse = result.score; + scoreMap.set(result.id, existing); + } + + if (normRerank) { + for (const result of normRerank) { + const existing = scoreMap.get(result.id); + if (existing) { + existing.scores.rerank = result.score; + } + } + } + + const fused = Array.from(scoreMap.values()).map(({ result, scores }) => { + const finalScore = + (scores.dense ?? 0) * weights.dense + + (scores.sparse ?? 0) * weights.sparse + + (scores.rerank ?? 0) * weights.rerank; + + return { ...result, score: finalScore }; + }); + + return fused.sort((a, b) => b.score - a.score); + } + + /** + * Get the predicted weights for a query (useful for debugging). + * + * @param query - The search query + * @returns Predicted fusion weights + */ + async getWeights(query: string): Promise { + return this.weightPredictor.predictFromQuery(query); + } + + /** + * Check if the learned model is available. + */ + async isModelAvailable(): Promise { + return this.weightPredictor.isAvailable(); + } + + /** + * Normalize scores to 0-1 range using min-max normalization. + */ + private normalizeScores(results: FusionSearchResult[]): FusionSearchResult[] { + if (results.length === 0) return []; + + const scores = results.map((r) => r.score); + const min = Math.min(...scores); + const max = Math.max(...scores); + const range = max - min; + + if (range === 0) { + // All scores are the same, normalize to 0.5 + return results.map((r) => ({ ...r, score: 0.5 })); + } + + return results.map((r) => ({ + ...r, + score: (r.score - min) / range, + })); + } + + /** + * Release resources. + */ + async close(): Promise { + await this.weightPredictor.close(); + } +} + +/** + * Adaptive RRF as a simpler alternative to learned fusion. + * + * Adjusts the RRF k parameter based on query characteristics. + * Use this when the learned model is not available. + * + * @param query - The search query + * @param denseResults - Dense retrieval results + * @param sparseResults - Sparse retrieval results + * @returns RRF-fused results + */ +export function adaptiveRRF( + query: string, + denseResults: FusionSearchResult[], + sparseResults: FusionSearchResult[], +): FusionSearchResult[] { + // Determine k based on query characteristics + const hasEntities = /[A-Z][a-z]+/.test(query); + const isKeywordHeavy = query.split(" ").length <= 4; + + // Higher k = more weight to lower-ranked results + // Keyword queries benefit from sparse, use lower k for sparse + const kDense = 60; + const kSparse = hasEntities || isKeywordHeavy ? 30 : 60; + + // Build RRF score map + const scoreMap = new Map(); + + for (let rank = 0; rank < denseResults.length; rank++) { + const result = denseResults[rank]; + const rrfScore = 1 / (kDense + rank + 1); + + const existing = scoreMap.get(result.id); + if (existing) { + existing.rrfScore += rrfScore; + } else { + scoreMap.set(result.id, { result, rrfScore }); + } + } + + for (let rank = 0; rank < sparseResults.length; rank++) { + const result = sparseResults[rank]; + const rrfScore = 1 / (kSparse + rank + 1); + + const existing = scoreMap.get(result.id); + if (existing) { + existing.rrfScore += rrfScore; + } else { + scoreMap.set(result.id, { result, rrfScore }); + } + } + + // Sort by RRF score + const fused = Array.from(scoreMap.values()) + .sort((a, b) => b.rrfScore - a.rrfScore) + .map((s) => ({ ...s.result, score: s.rrfScore })); + + return fused; +} diff --git a/packages/search/src/services/llm-reranker.test.ts b/packages/search/src/services/llm-reranker.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..718b3209059ebac11d5f055fa6b321b2b89c2fc3 --- /dev/null +++ b/packages/search/src/services/llm-reranker.test.ts @@ -0,0 +1,377 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { DocumentCandidate } from "./batched-reranker"; + +// Mock generateObject from ai - must be defined before vi.mock for hoisting +const mockGenerateObject = vi.fn(); + +// Mock rate limiter - defined before vi.mock for hoisting +const mockRateLimiter = { + checkLimit: vi.fn(), + recordRequest: vi.fn(), +}; + +// Mock RateLimiter constructor +const MockRateLimiterClass = vi.fn(() => mockRateLimiter); + +// Mock rate limiter module +vi.mock("./rate-limiter", () => ({ + RateLimiter: MockRateLimiterClass, +})); + +// Mock logger +vi.mock("@engram/logger", () => ({ + createLogger: () => ({ + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }), +})); + +// Mock metrics +vi.mock("./reranker-metrics", () => ({ + recordRerankMetrics: vi.fn(), +})); + +// Mock AI SDK +vi.mock("ai", () => ({ + generateObject: mockGenerateObject, +})); + +// Mock Google provider +vi.mock("@ai-sdk/google", () => ({ + createGoogleGenerativeAI: vi.fn(() => vi.fn((model: string) => ({ modelId: model }))), +})); + +// Import after mocking +const { LLMListwiseReranker } = await import("./llm-reranker"); + +describe("LLMListwiseReranker", () => { + let reranker: InstanceType; + + const mockCandidates: DocumentCandidate[] = [ + { id: "1", content: "First document about OAuth2 authentication flow" }, + { id: "2", content: "Second document about API security best practices" }, + { id: "3", content: "Third document about implementing JWT tokens" }, + { id: "4", content: "Fourth document about OAuth2 implementation guide" }, + { id: "5", content: "Fifth document about REST API design" }, + ]; + + beforeEach(() => { + vi.clearAllMocks(); + + // Reset mock constructor implementations + MockRateLimiterClass.mockImplementation(() => mockRateLimiter); + + // Reset mock return values after clearing + mockRateLimiter.checkLimit.mockReturnValue({ + allowed: true, + remaining: 95, + resetAt: new Date(Date.now() + 3600000), + }); + + // Default mock for generateObject + mockGenerateObject.mockResolvedValue({ + object: { ranking: [3, 0, 2, 1, 4] }, + usage: { + inputTokens: 500, + outputTokens: 50, + totalTokens: 550, + }, + }); + + reranker = new LLMListwiseReranker({ + apiKey: "test-key", + model: "gemini-3-flash", + maxCandidates: 10, + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("constructor", () => { + it("should use default options when none provided", () => { + const defaultReranker = new LLMListwiseReranker(); + expect(defaultReranker).toBeDefined(); + }); + + it("should use provided options", () => { + const customReranker = new LLMListwiseReranker({ + model: "grok-2", + maxCandidates: 5, + systemPrompt: "Custom prompt", + }); + expect(customReranker).toBeDefined(); + }); + + it("should create default rate limiter if not provided", () => { + const reranker = new LLMListwiseReranker({ + enableRateLimiting: true, + }); + expect(reranker).toBeDefined(); + }); + + it("should skip rate limiter if disabled", () => { + const reranker = new LLMListwiseReranker({ + enableRateLimiting: false, + }); + expect(reranker).toBeDefined(); + }); + }); + + describe("rerank()", () => { + it("should return empty array for empty documents", async () => { + const results = await reranker.rerank("test query", [], 5); + expect(results).toEqual([]); + }); + + it("should successfully rerank documents", async () => { + // Mock LLM response with ranking + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [3, 0, 2, 1, 4] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const results = await reranker.rerank("How to implement OAuth2?", mockCandidates, 5); + + expect(results).toHaveLength(5); + expect(results[0].id).toBe("4"); // Index 3 -> doc 4 + expect(results[1].id).toBe("1"); // Index 0 -> doc 1 + expect(results[2].id).toBe("3"); // Index 2 -> doc 3 + + // Scores should decrease with rank + expect(results[0].score).toBeGreaterThan(results[1].score); + expect(results[1].score).toBeGreaterThan(results[2].score); + }); + + it("should limit candidates to maxCandidates", async () => { + const manyCandidates: DocumentCandidate[] = Array.from({ length: 20 }, (_, i) => ({ + id: `doc-${i}`, + content: `Document ${i} content`, + })); + + // Mock LLM response + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await reranker.rerank("test query", manyCandidates, 5); + + // Should call generateObject with prompt containing indices 0-9 + expect(mockGenerateObject).toHaveBeenCalledWith( + expect.objectContaining({ + prompt: expect.stringContaining("[9]"), + }), + ); + + // Should NOT contain [10] or higher + const callArgs = mockGenerateObject.mock.calls[0][0]; + expect(callArgs.prompt).not.toContain("[10]"); + }); + + it("should respect topK parameter", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [3, 0, 2, 1, 4] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const results = await reranker.rerank( + "test query", + mockCandidates, + 2, // Only top 2 + ); + + expect(results).toHaveLength(2); + expect(results[0].id).toBe("4"); + expect(results[1].id).toBe("1"); + }); + + it("should preserve original scores", async () => { + const candidatesWithScores: DocumentCandidate[] = [ + { id: "1", content: "First", score: 0.95 }, + { id: "2", content: "Second", score: 0.85 }, + { id: "3", content: "Third", score: 0.75 }, + ]; + + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [2, 0, 1] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const results = await reranker.rerank("test", candidatesWithScores, 3); + + expect(results[0].originalScore).toBe(0.75); // Doc 3 + expect(results[1].originalScore).toBe(0.95); // Doc 1 + expect(results[2].originalScore).toBe(0.85); // Doc 2 + }); + + it("should assign scores based on rank position", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [3, 0, 2, 1, 4] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const results = await reranker.rerank("test", mockCandidates, 5); + + // First result should have highest score (1.0) + expect(results[0].score).toBe(1.0); + + // Scores should decrease linearly + for (let i = 1; i < results.length; i++) { + expect(results[i].score).toBeLessThan(results[i - 1].score); + } + + // Last result should have lowest score + expect(results[results.length - 1].score).toBeGreaterThan(0); + }); + + it("should check rate limits", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 1, 2] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await reranker.rerank("test", mockCandidates, 3, "user-123"); + + expect(mockRateLimiter.checkLimit).toHaveBeenCalledWith("user-123", "llm"); + }); + + it("should record request after successful rerank", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 1, 2] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await reranker.rerank("test", mockCandidates, 3, "user-123"); + + expect(mockRateLimiter.recordRequest).toHaveBeenCalledWith( + "user-123", + "llm", + expect.any(Number), + ); + }); + + it("should fail if rate limit exceeded", async () => { + mockRateLimiter.checkLimit.mockReturnValueOnce({ + allowed: false, + remaining: 0, + resetAt: new Date(Date.now() + 3600000), + reason: "Rate limit exceeded: 100/100 requests", + }); + + await expect(reranker.rerank("test", mockCandidates, 3, "user-123")).rejects.toThrow( + "Rate limit exceeded", + ); + }); + + it("should validate ranking indices", async () => { + // Return invalid index + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 99, 1] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await expect(reranker.rerank("test", mockCandidates, 3)).rejects.toThrow( + "Invalid ranking index", + ); + }); + + it("should handle LLM errors gracefully", async () => { + mockGenerateObject.mockRejectedValueOnce(new Error("LLM API error")); + + await expect(reranker.rerank("test", mockCandidates, 3)).rejects.toThrow("LLM API error"); + }); + }); + + describe("getUsage()", () => { + it("should return usage statistics", async () => { + // Make a rerank call to accumulate usage + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 1, 2] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await reranker.rerank("test", mockCandidates.slice(0, 3), 3); + + const usage = reranker.getUsage(); + + expect(usage.totalTokens).toBe(550); + expect(usage.totalCostCents).toBeGreaterThan(0); + }); + }); + + describe("resetUsage()", () => { + it("should reset usage counters", async () => { + // Make a rerank call to accumulate usage + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 1, 2] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await reranker.rerank("test", mockCandidates.slice(0, 3), 3); + + reranker.resetUsage(); + + const usage = reranker.getUsage(); + expect(usage.totalTokens).toBe(0); + expect(usage.totalCostCents).toBe(0); + }); + }); + + describe("prompt generation", () => { + it("should include query in prompt", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 1] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const query = "How to implement OAuth2?"; + await reranker.rerank(query, mockCandidates.slice(0, 2), 2); + + expect(mockGenerateObject).toHaveBeenCalledWith( + expect.objectContaining({ + prompt: expect.stringContaining(query), + }), + ); + }); + + it("should include candidates in prompt", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0, 1] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await reranker.rerank("test", mockCandidates.slice(0, 2), 2); + + const callArgs = mockGenerateObject.mock.calls[0][0]; + + expect(callArgs.prompt).toContain("[0]"); + expect(callArgs.prompt).toContain("[1]"); + expect(callArgs.prompt).toContain("OAuth2"); + expect(callArgs.prompt).toContain("API security"); + }); + + it("should truncate long document content", async () => { + const longDoc: DocumentCandidate = { + id: "long", + content: "a".repeat(1000), + }; + + mockGenerateObject.mockResolvedValueOnce({ + object: { ranking: [0] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await reranker.rerank("test", [longDoc], 1); + + const callArgs = mockGenerateObject.mock.calls[0][0]; + + // Should be truncated to ~500 chars + expect(callArgs.prompt.length).toBeLessThan(1000); + expect(callArgs.prompt).toContain("..."); + }); + }); +}); diff --git a/packages/search/src/services/llm-reranker.ts b/packages/search/src/services/llm-reranker.ts new file mode 100644 index 0000000000000000000000000000000000000000..a57a805573cb85722588a40f731b8a5d8e2a23ed --- /dev/null +++ b/packages/search/src/services/llm-reranker.ts @@ -0,0 +1,392 @@ +import { createGoogleGenerativeAI } from "@ai-sdk/google"; +import { createLogger } from "@engram/logger"; +import { generateObject } from "ai"; +import { z } from "zod"; +import type { BatchedRerankResult, DocumentCandidate } from "./batched-reranker"; +import { RateLimiter } from "./rate-limiter"; +import { recordRerankMetrics } from "./reranker-metrics"; + +/** + * System prompt for LLM reranking. + * + * Instructs the model to act as a search relevance expert and rank documents + * by relevance to the query. + */ +const RERANK_SYSTEM_PROMPT = `You are a search relevance expert. Given a query and a list of candidate documents, rank them by relevance. + +Rules: +- Consider semantic relevance, not just keyword matching +- For code queries, prioritize functional correctness over style +- For technical queries, prioritize accuracy and completeness +- For conceptual queries, prioritize clarity and comprehensiveness +- Return ONLY a JSON array of document indices, most relevant first +- Example: [3, 1, 5, 2, 4] means doc 3 is most relevant, then doc 1, etc. +- The indices are 0-based and correspond to the order of candidates provided`; + +/** + * User prompt template for LLM reranking. + * + * Formats the query and candidates into a prompt for the model. + */ +function buildUserPrompt(query: string, candidates: DocumentCandidate[]): string { + const candidateList = candidates + .map((doc, idx) => { + const preview = doc.content.slice(0, 500); // First 500 chars + return `[${idx}] ${preview}${doc.content.length > 500 ? "..." : ""}`; + }) + .join("\n\n"); + + return `Query: ${query} + +Candidates: +${candidateList} + +Return the ranking as a JSON array of indices (0-based), most relevant first.`; +} + +/** + * Zod schema for validating LLM ranking output. + */ +const RankingSchema = z.object({ + ranking: z.array(z.number().int().nonnegative()), +}); + +export interface LLMRerankerOptions { + /** Model to use - defaults to gemini-3-flash */ + model?: string; + /** Maximum candidates to send to LLM (context efficiency) - defaults to 10 */ + maxCandidates?: number; + /** Custom system prompt for ranking instructions */ + systemPrompt?: string; + /** Google AI API key - defaults to GOOGLE_GENERATIVE_AI_API_KEY env var */ + apiKey?: string; + /** Enable rate limiting - defaults to true */ + enableRateLimiting?: boolean; + /** Rate limiter configuration */ + rateLimiter?: RateLimiter; +} + +/** + * LLM-based listwise reranker using Gemini for premium queries. + * + * Advantages over pointwise rerankers: + * - Sees all candidates in context + * - Can make relative comparisons + * - Better for complex reasoning queries + * + * Reserved for premium tier due to cost/latency. + * + * @example + * ```ts + * const reranker = new LLMListwiseReranker({ apiKey: "..." }); + * const results = await reranker.rerank( + * "How to implement OAuth2?", + * candidates, + * 5 + * ); + * ``` + */ +export class LLMListwiseReranker { + private google: ReturnType; + private model: string; + private maxCandidates: number; + private systemPrompt: string; + private logger = createLogger({ component: "LLMListwiseReranker" }); + private rateLimiter?: RateLimiter; + private enableRateLimiting: boolean; + private totalCostCents = 0; + private totalTokens = 0; + + constructor(options: LLMRerankerOptions = {}) { + this.model = options.model ?? "gemini-3-flash"; + this.maxCandidates = options.maxCandidates ?? 10; + this.systemPrompt = options.systemPrompt ?? RERANK_SYSTEM_PROMPT; + this.enableRateLimiting = options.enableRateLimiting ?? true; + + this.google = createGoogleGenerativeAI({ + apiKey: options.apiKey, + }); + + this.rateLimiter = options.rateLimiter; + + // Create default rate limiter if not provided and rate limiting is enabled + if (this.enableRateLimiting && !this.rateLimiter) { + this.rateLimiter = new RateLimiter(); + } + } + + /** + * Rerank documents using LLM listwise comparison. + * + * @param query - The search query + * @param candidates - Candidate documents to rerank + * @param topK - Number of top results to return + * @param userId - Optional user ID for rate limiting (defaults to "anonymous") + * @returns Reranked results sorted by relevance score + */ + async rerank( + query: string, + candidates: DocumentCandidate[], + topK: number = 10, + userId: string = "anonymous", + ): Promise { + if (candidates.length === 0) { + return []; + } + + const startTime = Date.now(); + const candidateCount = candidates.length; + + this.logger.info({ + msg: "LLM rerank started", + tier: "llm", + model: this.model, + candidateCount, + topK, + queryLength: query.length, + userId, + }); + + try { + // Check rate limit + if (this.enableRateLimiting && this.rateLimiter) { + const limitCheck = this.rateLimiter.checkLimit(userId, "llm"); + + if (!limitCheck.allowed) { + const error = new Error( + `Rate limit exceeded: ${limitCheck.reason ?? "Too many requests"}`, + ); + this.logger.warn({ + msg: "LLM rerank rate limited", + userId, + tier: "llm", + reason: limitCheck.reason, + resetAt: limitCheck.resetAt, + }); + throw error; + } + + this.logger.debug({ + msg: "Rate limit check passed", + userId, + remaining: limitCheck.remaining, + resetAt: limitCheck.resetAt, + }); + } + + // Limit candidates to maxCandidates for context efficiency + const limitedCandidates = candidates.slice(0, this.maxCandidates); + + if (limitedCandidates.length < candidates.length) { + this.logger.debug({ + msg: "Candidates limited for LLM context", + originalCount: candidates.length, + limitedCount: limitedCandidates.length, + maxCandidates: this.maxCandidates, + }); + } + + // Build prompt + const userPrompt = buildUserPrompt(query, limitedCandidates); + + // Call LLM to get ranking using AI SDK + const result = await generateObject({ + model: this.google(this.model), + schema: RankingSchema, + system: this.systemPrompt, + prompt: userPrompt, + }); + + const ranking = (result.object as { ranking: number[] }).ranking; + + // Track usage and cost + const usage = result.usage as + | { totalTokens?: number; inputTokens?: number; outputTokens?: number } + | undefined; + if (usage) { + this.totalTokens += usage.totalTokens ?? 0; + // Cost estimation for gemini-3-flash + // Input: $0.50/1M tokens, Output: $3.00/1M tokens + const inputTokens = usage.inputTokens ?? 0; + const outputTokens = usage.outputTokens ?? 0; + const costCents = (inputTokens / 1_000_000) * 50 + (outputTokens / 1_000_000) * 300; + this.totalCostCents += costCents; + } + + // Validate ranking indices + this.validateRanking(ranking, limitedCandidates.length); + + // Record request for rate limiting + if (this.enableRateLimiting && this.rateLimiter) { + this.rateLimiter.recordRequest(userId, "llm", this.totalCostCents); + } + + // Convert ranking to rerank results + const results = this.rankingToResults(ranking, limitedCandidates, topK); + + // Calculate metrics + const scores = results.map((r) => r.score); + const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length; + const maxScore = Math.max(...scores); + const minScore = Math.min(...scores); + + // Calculate score improvement if original scores exist + let scoreImprovement: number | undefined; + const hasOriginalScores = results.every((r) => r.originalScore !== undefined); + if (hasOriginalScores) { + const originalAvg = + results.reduce((sum, r) => sum + (r.originalScore ?? 0), 0) / results.length; + scoreImprovement = avgScore - originalAvg; + } + + const latencyMs = Date.now() - startTime; + const latencySeconds = latencyMs / 1000; + + this.logger.info({ + msg: "LLM rerank completed", + tier: "llm", + model: this.model, + candidateCount, + topK, + latencyMs, + avgScore: avgScore.toFixed(3), + maxScore: maxScore.toFixed(3), + minScore: minScore.toFixed(3), + scoreImprovement: scoreImprovement?.toFixed(3), + totalCostCents: this.totalCostCents.toFixed(4), + totalTokens: this.totalTokens, + }); + + // Record metrics + recordRerankMetrics({ + tier: "llm", + model: this.model, + latencySeconds, + candidateCount, + scoreImprovement, + status: "success", + }); + + return results; + } catch (error) { + const latencyMs = Date.now() - startTime; + const latencySeconds = latencyMs / 1000; + + this.logger.error({ + msg: "LLM rerank failed", + tier: "llm", + model: this.model, + candidateCount, + latencyMs, + error: error instanceof Error ? error.message : String(error), + }); + + // Record failure metrics + recordRerankMetrics({ + tier: "llm", + model: this.model, + latencySeconds, + candidateCount, + status: "failure", + }); + + throw error; + } + } + + /** + * Validate that ranking contains valid indices. + */ + private validateRanking(ranking: number[], candidateCount: number): void { + // Check all indices are valid + for (const idx of ranking) { + if (idx < 0 || idx >= candidateCount) { + throw new Error(`Invalid ranking index ${idx} (must be 0-${candidateCount - 1})`); + } + } + + // Check for duplicates + const uniqueIndices = new Set(ranking); + if (uniqueIndices.size !== ranking.length) { + this.logger.warn({ + msg: "Ranking contains duplicate indices", + ranking, + }); + } + + // Check if all candidates are included + if (ranking.length !== candidateCount) { + this.logger.warn({ + msg: "Ranking length does not match candidate count", + rankingLength: ranking.length, + candidateCount, + }); + } + } + + /** + * Convert LLM ranking to BatchedRerankResult format. + * + * Assigns scores based on position in ranking: + * - First position gets score 1.0 + * - Scores decrease linearly to 0.0 for last position + */ + private rankingToResults( + ranking: number[], + candidates: DocumentCandidate[], + topK: number, + ): BatchedRerankResult[] { + const results: BatchedRerankResult[] = []; + + // Take only top K from ranking + const topIndices = ranking.slice(0, topK); + + for (let rank = 0; rank < topIndices.length; rank++) { + const candidateIdx = topIndices[rank]; + const candidate = candidates[candidateIdx]; + + if (!candidate) { + this.logger.warn({ + msg: "Invalid candidate index in ranking", + candidateIdx, + candidateCount: candidates.length, + }); + continue; + } + + // Assign score based on position (1.0 for first, decreasing linearly) + // Score = 1.0 - (rank / totalRanked) + const score = 1.0 - rank / ranking.length; + + results.push({ + id: candidate.id, + score, + originalIndex: candidateIdx, + originalScore: candidate.score, + }); + } + + return results; + } + + /** + * Get usage statistics for this reranker instance. + */ + getUsage(): { + totalCostCents: number; + totalTokens: number; + } { + return { + totalCostCents: this.totalCostCents, + totalTokens: this.totalTokens, + }; + } + + /** + * Reset usage counters. + */ + resetUsage(): void { + this.totalCostCents = 0; + this.totalTokens = 0; + } +} diff --git a/packages/search/src/services/multi-query-retriever.test.ts b/packages/search/src/services/multi-query-retriever.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d205c0921d0e5e0929aea093be2a3d0ffd162eaa --- /dev/null +++ b/packages/search/src/services/multi-query-retriever.test.ts @@ -0,0 +1,480 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// Mock generateObject from ai - must be defined before vi.mock for hoisting +const mockGenerateObject = vi.fn(); + +// Mock logger +vi.mock("@engram/logger", () => ({ + createLogger: () => ({ + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }), +})); + +// Mock AI SDK +vi.mock("ai", () => ({ + generateObject: mockGenerateObject, +})); + +// Mock Google provider +vi.mock("@ai-sdk/google", () => ({ + createGoogleGenerativeAI: vi.fn(() => vi.fn((model: string) => ({ modelId: model }))), +})); + +// Import after mocking +const { MultiQueryRetriever } = await import("./multi-query-retriever"); + +describe("MultiQueryRetriever", () => { + let retriever: InstanceType; + let mockBaseRetriever: any; + + const mockSearchResults = [ + { id: "doc-1", score: 0.95, payload: { content: "OAuth2 guide" } }, + { id: "doc-2", score: 0.9, payload: { content: "JWT tokens" } }, + { id: "doc-3", score: 0.85, payload: { content: "API security" } }, + ]; + + beforeEach(() => { + vi.clearAllMocks(); + + // Create mock base retriever + mockBaseRetriever = { + search: vi.fn().mockResolvedValue(mockSearchResults), + }; + + // Default mock for generateObject + mockGenerateObject.mockResolvedValue({ + object: { + queries: [ + "OAuth2 authentication implementation", + "how to add OAuth login", + "authentication flow for web apps", + ], + }, + usage: { + inputTokens: 500, + outputTokens: 50, + totalTokens: 550, + }, + }); + + retriever = new MultiQueryRetriever({ + baseRetriever: mockBaseRetriever, + apiKey: "test-key", + config: { + numVariations: 3, + strategies: ["paraphrase", "keyword", "stepback"], + includeOriginal: true, + rrfK: 60, + }, + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("constructor", () => { + it("should use default config when none provided", () => { + const defaultRetriever = new MultiQueryRetriever({ + baseRetriever: mockBaseRetriever, + }); + expect(defaultRetriever.getConfig()).toEqual({ + numVariations: 3, + strategies: ["paraphrase", "keyword", "stepback"], + includeOriginal: true, + rrfK: 60, + }); + }); + + it("should use provided config options", () => { + const customRetriever = new MultiQueryRetriever({ + baseRetriever: mockBaseRetriever, + config: { + numVariations: 5, + strategies: ["paraphrase", "decompose"], + includeOriginal: false, + rrfK: 30, + }, + }); + + const config = customRetriever.getConfig(); + expect(config.numVariations).toBe(5); + expect(config.strategies).toEqual(["paraphrase", "decompose"]); + expect(config.includeOriginal).toBe(false); + expect(config.rrfK).toBe(30); + }); + }); + + describe("search()", () => { + it("should generate query variations and search with each", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { + queries: [ + "OAuth2 authentication implementation", + "how to add OAuth login", + "authentication flow for web apps", + ], + }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await retriever.search({ text: "How to implement OAuth2?", limit: 10 }); + + // Should call base retriever 4 times (original + 3 variations) + expect(mockBaseRetriever.search).toHaveBeenCalledTimes(4); + }); + + it("should include original query when configured", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["variation1", "variation2", "variation3"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await retriever.search({ text: "original query", limit: 10 }); + + // First call should be with original query + expect(mockBaseRetriever.search).toHaveBeenCalledWith( + expect.objectContaining({ text: "original query" }), + ); + }); + + it("should exclude original query when not configured", async () => { + const noOriginalRetriever = new MultiQueryRetriever({ + baseRetriever: mockBaseRetriever, + config: { includeOriginal: false, numVariations: 2 }, + }); + + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["variation1", "variation2"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await noOriginalRetriever.search({ text: "original query", limit: 10 }); + + // Should only call with variations (2 times), not with original + expect(mockBaseRetriever.search).toHaveBeenCalledTimes(2); + expect(mockBaseRetriever.search).not.toHaveBeenCalledWith( + expect.objectContaining({ text: "original query" }), + ); + }); + + it("should fuse results using RRF", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["variation1", "variation2"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + // Set up different results for each query + const results1 = [ + { id: "doc-1", score: 0.9, payload: { content: "A" } }, + { id: "doc-2", score: 0.8, payload: { content: "B" } }, + ]; + const results2 = [ + { id: "doc-3", score: 0.95, payload: { content: "C" } }, + { id: "doc-1", score: 0.85, payload: { content: "A" } }, // Duplicate + ]; + const results3 = [ + { id: "doc-1", score: 0.88, payload: { content: "A" } }, // Triple duplicate + { id: "doc-4", score: 0.75, payload: { content: "D" } }, + ]; + + mockBaseRetriever.search + .mockResolvedValueOnce(results1) // Original query + .mockResolvedValueOnce(results2) // Variation 1 + .mockResolvedValueOnce(results3); // Variation 2 + + const results = await retriever.search({ text: "test query", limit: 10 }); + + // doc-1 appears in all 3 result sets, should have highest RRF score + expect(results[0].id).toBe("doc-1"); + + // All results should have rrfScore + for (const result of results) { + expect(result.rrfScore).toBeDefined(); + expect(result.rrfScore).toBeGreaterThan(0); + } + }); + + it("should respect limit parameter", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["v1", "v2"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + // Return more results than requested limit + const manyResults = Array.from({ length: 20 }, (_, i) => ({ + id: `doc-${i}`, + score: 0.9 - i * 0.01, + payload: { content: `Content ${i}` }, + })); + + mockBaseRetriever.search.mockResolvedValue(manyResults); + + const results = await retriever.search({ text: "test", limit: 5 }); + + expect(results.length).toBeLessThanOrEqual(5); + }); + + it("should fall back to single query on expansion error", async () => { + mockGenerateObject.mockRejectedValueOnce(new Error("LLM API error")); + + const results = await retriever.search({ text: "test query", limit: 10 }); + + // Should fall back to single query + expect(mockBaseRetriever.search).toHaveBeenCalledTimes(1); + expect(results).toHaveLength(3); + }); + + it("should pass through search query options", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["variation"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await retriever.search({ + text: "test query", + limit: 5, + strategy: "hybrid", + filters: { session_id: "session-123" }, + rerank: true, + }); + + expect(mockBaseRetriever.search).toHaveBeenCalledWith( + expect.objectContaining({ + strategy: "hybrid", + filters: { session_id: "session-123" }, + rerank: true, + }), + ); + }); + }); + + describe("expandQuery()", () => { + it("should return variations including original query", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { + queries: [ + "OAuth2 authentication guide", + "implementing OAuth login", + "secure authentication flow", + ], + }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const variations = await retriever.expandQuery("How to implement OAuth2?"); + + // Should include original + 3 variations + expect(variations).toHaveLength(4); + expect(variations[0]).toBe("How to implement OAuth2?"); + }); + + it("should filter out empty variations", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { + queries: [ + "valid query", + " ", // Empty/whitespace + "another valid", + "", // Empty + ], + }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const variations = await retriever.expandQuery("original"); + + // Should include original + 2 valid variations (not 4) + expect(variations).toHaveLength(3); + expect(variations).not.toContain(""); + expect(variations).not.toContain(" "); + }); + + it("should not duplicate original query in variations", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { + queries: [ + "original", // Same as input + "variation 1", + "variation 2", + ], + }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const variations = await retriever.expandQuery("original"); + + // Should have original once, not twice + expect(variations.filter((v) => v === "original")).toHaveLength(1); + }); + + it("should limit variations to numVariations config", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { + queries: ["variation 1", "variation 2", "variation 3", "variation 4", "variation 5"], + }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + const variations = await retriever.expandQuery("original"); + + // Original + numVariations (3) = 4 + expect(variations).toHaveLength(4); + }); + + it("should return only original on LLM error", async () => { + mockGenerateObject.mockRejectedValueOnce(new Error("API error")); + + const variations = await retriever.expandQuery("original"); + + expect(variations).toEqual(["original"]); + }); + + it("should build prompt with configured strategies", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["v1", "v2", "v3"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await retriever.expandQuery("test query"); + + const callArgs = mockGenerateObject.mock.calls[0][0]; + + expect(callArgs.prompt).toContain("Paraphrase"); + expect(callArgs.prompt).toContain("Keyword"); + expect(callArgs.prompt).toContain("Step-back"); + }); + + it("should include decompose strategy when configured", async () => { + const decomposeRetriever = new MultiQueryRetriever({ + baseRetriever: mockBaseRetriever, + config: { + strategies: ["decompose"], + numVariations: 2, + }, + }); + + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["sub-q1", "sub-q2"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await decomposeRetriever.expandQuery("complex query"); + + const callArgs = mockGenerateObject.mock.calls[0][0]; + + expect(callArgs.prompt).toContain("Decompose"); + }); + }); + + describe("RRF fusion", () => { + it("should compute correct RRF scores", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["q1", "q2"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + // Set up results where doc-1 appears first in both sets + const results1 = [ + { id: "doc-1", score: 0.9, payload: {} }, + { id: "doc-2", score: 0.8, payload: {} }, + ]; + const results2 = [ + { id: "doc-1", score: 0.85, payload: {} }, + { id: "doc-3", score: 0.7, payload: {} }, + ]; + + mockBaseRetriever.search.mockResolvedValueOnce(results1).mockResolvedValueOnce(results2); + + // Create retriever that doesn't include original + const rrfRetriever = new MultiQueryRetriever({ + baseRetriever: mockBaseRetriever, + config: { includeOriginal: false, numVariations: 2, rrfK: 60 }, + }); + + const results = await rrfRetriever.search({ text: "test", limit: 10 }); + + // doc-1 appears at rank 0 in both sets + // RRF score = 1/(60+1) + 1/(60+1) = 2/61 ≈ 0.0328 + const doc1 = results.find((r) => r.id === "doc-1"); + expect(doc1).toBeDefined(); + + // doc-1 should have highest RRF score + expect(results[0].id).toBe("doc-1"); + }); + + it("should deduplicate documents across result sets", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["v1"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + // Same document appears in multiple result sets + const results1 = [{ id: "doc-1", score: 0.9, payload: {} }]; + const results2 = [{ id: "doc-1", score: 0.8, payload: {} }]; + + mockBaseRetriever.search.mockResolvedValueOnce(results1).mockResolvedValueOnce(results2); + + const results = await retriever.search({ text: "test", limit: 10 }); + + // doc-1 should appear only once + const doc1Count = results.filter((r) => r.id === "doc-1").length; + expect(doc1Count).toBe(1); + }); + }); + + describe("getUsage()", () => { + it("should track LLM usage", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["v1", "v2"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + + await retriever.search({ text: "test", limit: 10 }); + + const usage = retriever.getUsage(); + expect(usage.totalCostCents).toBeGreaterThan(0); + expect(usage.totalTokens).toBeGreaterThan(0); + }); + }); + + describe("resetUsage()", () => { + it("should reset usage counters", async () => { + mockGenerateObject.mockResolvedValueOnce({ + object: { queries: ["v1"] }, + usage: { inputTokens: 500, outputTokens: 50, totalTokens: 550 }, + }); + await retriever.search({ text: "test", limit: 10 }); + + retriever.resetUsage(); + + const usage = retriever.getUsage(); + expect(usage.totalCostCents).toBe(0); + expect(usage.totalTokens).toBe(0); + }); + }); + + describe("getConfig()", () => { + it("should return current configuration", () => { + const config = retriever.getConfig(); + + expect(config).toEqual({ + numVariations: 3, + strategies: ["paraphrase", "keyword", "stepback"], + includeOriginal: true, + rrfK: 60, + }); + }); + + it("should return a copy to prevent mutation", () => { + const config1 = retriever.getConfig(); + config1.numVariations = 100; + + const config2 = retriever.getConfig(); + expect(config2.numVariations).toBe(3); + }); + }); +}); diff --git a/packages/search/src/services/multi-query-retriever.ts b/packages/search/src/services/multi-query-retriever.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0e3727a650dea8f2a51a659d12b2df46d003eb0 --- /dev/null +++ b/packages/search/src/services/multi-query-retriever.ts @@ -0,0 +1,373 @@ +import { createGoogleGenerativeAI } from "@ai-sdk/google"; +import { createLogger } from "@engram/logger"; +import { generateObject } from "ai"; +import { z } from "zod"; +import type { SearchQuery, SearchResult, SearchResultPayload } from "../models/schema"; +import type { SearchRetriever } from "./retriever"; + +/** + * Raw result from SearchRetriever before full type mapping. + * SearchRetriever returns a looser type than SearchResult. + */ +interface RawSearchResult { + id: string | number; + score: number; + payload?: unknown; + rrfScore?: number; + rerankerScore?: number; + degraded?: boolean; + degradedReason?: string; +} + +/** + * Query expansion strategies based on DMQR-RAG research. + * @see https://arxiv.org/abs/2411.13154 + * + * - paraphrase: Rephrase with synonyms (GQR in paper) + * - keyword: Extract key entities and terms (KWR in paper) + * - stepback: Generalize to broader concept + * - decompose: Break into sub-questions (for complex queries) + */ +export type QueryExpansionStrategy = "paraphrase" | "keyword" | "stepback" | "decompose"; + +/** + * Configuration for multi-query retrieval. + */ +export interface MultiQueryConfig { + /** Number of query variations to generate */ + numVariations: number; + /** Expansion strategies to use */ + strategies: QueryExpansionStrategy[]; + /** Whether to include original query in retrieval */ + includeOriginal: boolean; + /** RRF fusion constant (typically 60) */ + rrfK: number; +} + +const DEFAULT_CONFIG: MultiQueryConfig = { + numVariations: 3, + strategies: ["paraphrase", "keyword", "stepback"], + includeOriginal: true, + rrfK: 60, +}; + +/** + * Zod schema for LLM query expansion response. + */ +const QueryExpansionSchema = z.object({ + queries: z.array(z.string().min(1)), +}); + +/** + * System prompt for query expansion. + * Instructs the model to generate diverse query variations using DMQR-RAG strategies. + */ +const EXPANSION_SYSTEM_PROMPT = `You are a search query expansion expert. Given a user query, generate alternative search queries that will help retrieve relevant documents. + +Rules: +- Generate queries that are semantically different but target the same information need +- Each query should emphasize different aspects or use different vocabulary +- Return ONLY a JSON object with a "queries" array of query strings +- Example: {"queries": ["query 1", "query 2", "query 3"]} +- Do not include numbering, bullets, or markdown formatting`; + +export interface MultiQueryRetrieverOptions { + /** Base retriever to use for each query */ + baseRetriever: SearchRetriever; + /** Multi-query configuration */ + config?: Partial; + /** Model to use for expansion - defaults to gemini-3-flash */ + model?: string; + /** Google AI API key - defaults to GOOGLE_GENERATIVE_AI_API_KEY env var */ + apiKey?: string; +} + +/** + * Multi-query retriever that generates query variations using LLM + * and fuses results using Reciprocal Rank Fusion (RRF). + * + * Based on DMQR-RAG: Diverse Multi-Query Rewriting for RAG. + * @see https://arxiv.org/abs/2411.13154 + * + * Key strategies: + * - Paraphrase: Rephrase with synonyms to capture vocabulary variance + * - Keyword: Extract key entities for precise matching + * - Step-back: Generalize to broader concepts for high-level documents + * - Decompose: Break complex queries into sub-questions + * + * @example + * ```ts + * const retriever = new MultiQueryRetriever({ + * baseRetriever: searchRetriever, + * config: { numVariations: 3, strategies: ["paraphrase", "keyword", "stepback"] } + * }); + * + * const results = await retriever.search({ + * text: "How do I implement OAuth2 authentication?", + * limit: 10 + * }); + * ``` + */ +export class MultiQueryRetriever { + private baseRetriever: SearchRetriever; + private google: ReturnType; + private model: string; + private config: MultiQueryConfig; + private logger = createLogger({ component: "MultiQueryRetriever" }); + private totalCostCents = 0; + private totalTokens = 0; + + constructor(options: MultiQueryRetrieverOptions) { + this.baseRetriever = options.baseRetriever; + this.config = { ...DEFAULT_CONFIG, ...options.config }; + this.model = options.model ?? "gemini-3-flash"; + + this.google = createGoogleGenerativeAI({ + apiKey: options.apiKey, + }); + } + + /** + * Search using multi-query expansion and RRF fusion. + * + * @param query - The search query + * @returns Fused and ranked search results + */ + async search(query: SearchQuery): Promise { + const startTime = Date.now(); + const limit = query.limit ?? 10; + + this.logger.info({ + msg: "Multi-query search started", + query: query.text.slice(0, 100), + numVariations: this.config.numVariations, + strategies: this.config.strategies, + includeOriginal: this.config.includeOriginal, + limit, + }); + + try { + // Step 1: Generate query variations using LLM + const variations = await this.expandQuery(query.text); + + this.logger.debug({ + msg: "Query expansion completed", + originalQuery: query.text, + variations, + }); + + // Step 2: Search with each variation in parallel + // Fetch more results per query since we'll dedupe + const perQueryLimit = Math.max(limit * 2, 20); + const searchPromises = variations.map((varQuery) => + this.baseRetriever.search({ + ...query, + text: varQuery, + limit: perQueryLimit, + }), + ); + + const allResults = await Promise.all(searchPromises); + + this.logger.debug({ + msg: "Parallel searches completed", + queriesExecuted: variations.length, + resultCounts: allResults.map((r) => r.length), + }); + + // Step 3: Fuse results using RRF + const fused = this.rrfFusion(allResults, limit); + + const latencyMs = Date.now() - startTime; + + this.logger.info({ + msg: "Multi-query search completed", + queriesExecuted: variations.length, + totalCandidates: allResults.reduce((sum, r) => sum + r.length, 0), + uniqueResults: fused.length, + latencyMs, + }); + + return fused; + } catch (error) { + const latencyMs = Date.now() - startTime; + + this.logger.error({ + msg: "Multi-query search failed - falling back to single query", + latencyMs, + error: error instanceof Error ? error.message : String(error), + }); + + // Graceful degradation: fall back to single query + const fallbackResults = await this.baseRetriever.search(query); + return fallbackResults.map((r) => { + const raw = r as RawSearchResult; + return { + id: raw.id, + score: raw.score, + rrfScore: raw.rrfScore, + rerankerScore: raw.rerankerScore, + payload: raw.payload as SearchResultPayload | undefined, + degraded: raw.degraded, + degradedReason: raw.degradedReason, + }; + }); + } + } + + /** + * Expand a query into multiple variations using LLM. + */ + async expandQuery(query: string): Promise { + const variations: string[] = []; + + // Always include original query if configured + if (this.config.includeOriginal) { + variations.push(query); + } + + const prompt = this.buildExpansionPrompt(query); + + try { + const result = await generateObject({ + model: this.google(this.model), + schema: QueryExpansionSchema, + system: EXPANSION_SYSTEM_PROMPT, + prompt, + }); + + // Track LLM usage + const usage = result.usage as + | { totalTokens?: number; inputTokens?: number; outputTokens?: number } + | undefined; + if (usage) { + this.totalTokens += usage.totalTokens ?? 0; + // Cost estimation for gemini-3-flash + // Input: $0.50/1M tokens, Output: $3.00/1M tokens + const inputTokens = usage.inputTokens ?? 0; + const outputTokens = usage.outputTokens ?? 0; + const costCents = (inputTokens / 1_000_000) * 50 + (outputTokens / 1_000_000) * 300; + this.totalCostCents += costCents; + } + + // Filter and limit variations + const queries = (result.object as { queries: string[] }).queries; + const validVariations = queries + .filter((v: string) => v.trim().length > 0 && v !== query) + .slice(0, this.config.numVariations); + + variations.push(...validVariations); + + return variations; + } catch (error) { + this.logger.warn({ + msg: "Query expansion failed - using original query only", + error: error instanceof Error ? error.message : String(error), + }); + + // Return at least the original query + return [query]; + } + } + + /** + * Build the user prompt for query expansion. + */ + private buildExpansionPrompt(query: string): string { + const strategyInstructions = this.config.strategies + .map((strategy) => { + switch (strategy) { + case "paraphrase": + return "- Paraphrase: Rephrase the query using different words and synonyms"; + case "keyword": + return "- Keyword: Focus on key entities, names, and technical terms"; + case "stepback": + return "- Step-back: Generalize to a broader concept or category"; + case "decompose": + return "- Decompose: Break into simpler sub-questions (if query is complex)"; + default: + return ""; + } + }) + .filter(Boolean) + .join("\n"); + + return `Generate ${this.config.numVariations} alternative search queries for: +"${query}" + +Use these strategies: +${strategyInstructions} + +Return ONLY a JSON object with a "queries" array. No explanations.`; + } + + /** + * Fuse multiple result sets using Reciprocal Rank Fusion (RRF). + * + * RRF score = sum(1 / (k + rank_i)) across all result sets + * where k is typically 60 to dampen the impact of high rankings. + * + * @see https://dl.acm.org/doi/10.1145/1571941.1572114 + */ + private rrfFusion(resultSets: RawSearchResult[][], topK: number): SearchResult[] { + const k = this.config.rrfK; + const scoreMap = new Map(); + + for (const results of resultSets) { + for (let rank = 0; rank < results.length; rank++) { + const result = results[rank]; + const rrfScore = 1 / (k + rank + 1); + const key = result.id; + + const existing = scoreMap.get(key); + if (existing) { + // Sum RRF scores for documents appearing in multiple result sets + existing.rrfScore += rrfScore; + } else { + scoreMap.set(key, { result, rrfScore }); + } + } + } + + // Sort by RRF score and return top K + return Array.from(scoreMap.values()) + .sort((a, b) => b.rrfScore - a.rrfScore) + .slice(0, topK) + .map(({ result, rrfScore }) => ({ + id: result.id, + score: rrfScore, // Use RRF score as final score + rrfScore, // Also store in rrfScore for transparency + payload: result.payload as SearchResultPayload | undefined, + degraded: result.degraded, + degradedReason: result.degradedReason, + })); + } + + /** + * Get usage statistics for this retriever instance. + */ + getUsage(): { + totalCostCents: number; + totalTokens: number; + } { + return { + totalCostCents: this.totalCostCents, + totalTokens: this.totalTokens, + }; + } + + /** + * Reset usage counters. + */ + resetUsage(): void { + this.totalCostCents = 0; + this.totalTokens = 0; + } + + /** + * Get current configuration. + */ + getConfig(): MultiQueryConfig { + return { ...this.config }; + } +} diff --git a/packages/search/src/services/query-cache.test.ts b/packages/search/src/services/query-cache.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3fc033e5f4b2915a68b4dd43bd0599b1d0fc54b --- /dev/null +++ b/packages/search/src/services/query-cache.test.ts @@ -0,0 +1,250 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { BatchedRerankResult } from "./batched-reranker"; +import { type CacheKey, QueryCache } from "./query-cache"; + +// Mock ioredis +const mockRedis = { + connect: vi.fn().mockResolvedValue(undefined), + get: vi.fn(), + setex: vi.fn(), + scan: vi.fn(), + del: vi.fn(), + quit: vi.fn().mockResolvedValue(undefined), + on: vi.fn(), +}; + +vi.mock("ioredis", () => ({ + default: vi.fn(() => mockRedis), +})); + +describe("QueryCache", () => { + let cache: QueryCache; + + beforeEach(() => { + vi.clearAllMocks(); + cache = new QueryCache({ + redisUrl: "redis://localhost:6379", + ttlSeconds: 300, + keyPrefix: "test:", + }); + }); + + afterEach(async () => { + await cache.disconnect(); + }); + + describe("constructor", () => { + it("should use default options when none provided", () => { + const defaultCache = new QueryCache(); + expect(defaultCache).toBeDefined(); + }); + + it("should use provided options", () => { + const customCache = new QueryCache({ + redisUrl: "redis://custom:6379", + ttlSeconds: 600, + keyPrefix: "custom:", + }); + expect(customCache).toBeDefined(); + }); + + it("should handle missing Redis URL gracefully", async () => { + const noRedisCache = new QueryCache({ redisUrl: undefined }); + const result = await noRedisCache.get({ query: "test" }); + expect(result).toBeNull(); + }); + }); + + describe("get()", () => { + const mockResults: BatchedRerankResult[] = [ + { id: "doc1", score: 0.9, originalIndex: 0, originalScore: 0.5 }, + { id: "doc2", score: 0.8, originalIndex: 1, originalScore: 0.4 }, + ]; + + it("should return cached results when available", async () => { + mockRedis.get.mockResolvedValue(JSON.stringify(mockResults)); + + const params: CacheKey = { query: "test query" }; + const result = await cache.get(params); + + expect(result).toEqual(mockResults); + expect(mockRedis.get).toHaveBeenCalled(); + }); + + it("should return null when no cached results", async () => { + mockRedis.get.mockResolvedValue(null); + + const params: CacheKey = { query: "test query" }; + const result = await cache.get(params); + + expect(result).toBeNull(); + }); + + it("should return null on Redis error (graceful degradation)", async () => { + mockRedis.get.mockRejectedValue(new Error("Redis connection failed")); + + const params: CacheKey = { query: "test query" }; + const result = await cache.get(params); + + expect(result).toBeNull(); + }); + + it("should normalize query for consistent cache keys", async () => { + mockRedis.get.mockResolvedValue(JSON.stringify(mockResults)); + + // These should generate the same cache key + await cache.get({ query: "Test Query" }); + await cache.get({ query: "test query" }); + await cache.get({ query: " TEST QUERY " }); + + // Should all use the same Redis key + const calls = mockRedis.get.mock.calls; + expect(calls[0][0]).toBe(calls[1][0]); + expect(calls[1][0]).toBe(calls[2][0]); + }); + }); + + describe("set()", () => { + const mockResults: BatchedRerankResult[] = [ + { id: "doc1", score: 0.9, originalIndex: 0, originalScore: 0.5 }, + ]; + + it("should cache results with TTL", async () => { + const params: CacheKey = { query: "test query" }; + await cache.set(params, mockResults); + + expect(mockRedis.setex).toHaveBeenCalled(); + + const [key, ttl, value] = mockRedis.setex.mock.calls[0]; + expect(ttl).toBe(300); + expect(JSON.parse(value)).toEqual(mockResults); + }); + + it("should handle Redis errors gracefully", async () => { + mockRedis.setex.mockRejectedValue(new Error("Redis connection failed")); + + const params: CacheKey = { query: "test query" }; + + // Should not throw + await expect(cache.set(params, mockResults)).resolves.toBeUndefined(); + }); + + it("should include all cache key params in hash", async () => { + await cache.set({ query: "q1", filters: { type: "code" } }, mockResults); + await cache.set({ query: "q1", rerankTier: "fast" }, mockResults); + await cache.set({ query: "q1", limit: 20 }, mockResults); + await cache.set({ query: "q2" }, mockResults); + + // Should generate different keys for different params + const calls = mockRedis.setex.mock.calls; + const keys = calls.map((call) => call[0]); + + // All should be unique + expect(new Set(keys).size).toBe(4); + }); + }); + + describe("invalidatePattern()", () => { + it("should delete keys matching pattern", async () => { + // Mock SCAN to return some keys + mockRedis.scan + .mockResolvedValueOnce(["10", ["test:key1", "test:key2"]]) + .mockResolvedValueOnce(["0", ["test:key3"]]); + + await cache.invalidatePattern("*"); + + expect(mockRedis.scan).toHaveBeenCalledTimes(2); + expect(mockRedis.del).toHaveBeenCalledWith("test:key1", "test:key2"); + expect(mockRedis.del).toHaveBeenCalledWith("test:key3"); + }); + + it("should handle empty scan results", async () => { + mockRedis.scan.mockResolvedValue(["0", []]); + + await cache.invalidatePattern("*"); + + expect(mockRedis.del).not.toHaveBeenCalled(); + }); + + it("should handle Redis errors gracefully", async () => { + mockRedis.scan.mockRejectedValue(new Error("Redis connection failed")); + + // Should not throw + await expect(cache.invalidatePattern("*")).resolves.toBeUndefined(); + }); + }); + + describe("clear()", () => { + it("should clear all cache entries", async () => { + mockRedis.scan.mockResolvedValue(["0", ["test:key1"]]); + + await cache.clear(); + + expect(mockRedis.scan).toHaveBeenCalled(); + }); + }); + + describe("disconnect()", () => { + it("should disconnect from Redis", async () => { + // Ensure Redis is initialized + await cache.get({ query: "test" }); + + await cache.disconnect(); + + expect(mockRedis.quit).toHaveBeenCalled(); + }); + + it("should handle disconnect errors gracefully", async () => { + mockRedis.quit.mockRejectedValue(new Error("Already disconnected")); + + // Should not throw + await expect(cache.disconnect()).resolves.toBeUndefined(); + }); + }); + + describe("isAvailable()", () => { + it("should return false before initialization", () => { + const newCache = new QueryCache({ redisUrl: "redis://localhost:6379" }); + expect(newCache.isAvailable()).toBe(false); + }); + + it("should return true after successful initialization", async () => { + await cache.get({ query: "test" }); // Trigger initialization + expect(cache.isAvailable()).toBe(true); + }); + + it("should return false when Redis unavailable", async () => { + const noRedisCache = new QueryCache({ redisUrl: undefined }); + await noRedisCache.get({ query: "test" }); // Trigger initialization + expect(noRedisCache.isAvailable()).toBe(false); + }); + }); + + describe("lazy initialization", () => { + it("should not connect to Redis on construction", () => { + new QueryCache({ redisUrl: "redis://localhost:6379" }); + expect(mockRedis.connect).not.toHaveBeenCalled(); + }); + + it("should connect on first get", async () => { + const newCache = new QueryCache({ redisUrl: "redis://localhost:6379" }); + await newCache.get({ query: "test" }); + expect(mockRedis.connect).toHaveBeenCalled(); + }); + + it("should connect on first set", async () => { + const newCache = new QueryCache({ redisUrl: "redis://localhost:6379" }); + await newCache.set({ query: "test" }, []); + expect(mockRedis.connect).toHaveBeenCalled(); + }); + + it("should only initialize once", async () => { + await cache.get({ query: "test1" }); + await cache.get({ query: "test2" }); + await cache.set({ query: "test3" }, []); + + // Should only connect once + expect(mockRedis.connect).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/packages/search/src/services/query-cache.ts b/packages/search/src/services/query-cache.ts new file mode 100644 index 0000000000000000000000000000000000000000..793faf150b501f7d139bf8082ea75bd7e64214c3 --- /dev/null +++ b/packages/search/src/services/query-cache.ts @@ -0,0 +1,324 @@ +import { createHash } from "node:crypto"; +import { createLogger } from "@engram/logger"; +import { RERANK_CONFIG } from "../config"; +import type { BatchedRerankResult } from "./batched-reranker"; +import { + computeHitRate, + queryCacheHitRate, + recordQueryCacheError, + recordQueryCacheHit, + recordQueryCacheMiss, +} from "./cache-metrics"; + +export interface QueryCacheOptions { + redisUrl?: string; // Default: REDIS_URL env var + ttlSeconds?: number; // Default: 300 (5 minutes) + keyPrefix?: string; // Default: "rerank:" +} + +export interface CacheKey { + query: string; + filters?: Record; + rerankTier?: string; + limit?: number; +} + +/** + * Redis-backed cache for reranked query results. + * + * Features: + * - Redis persistence for distributed caching + * - Graceful degradation when Redis unavailable + * - TTL-based expiration (default: 5 minutes) + * - Cache key hashing for consistent lookups + * + * Target: 30%+ hit rate for repeated queries + */ +export class QueryCache { + private redis: any = null; + private readonly ttlSeconds: number; + private readonly keyPrefix: string; + private readonly redisUrl?: string; + private logger = createLogger({ component: "QueryCache" }); + private initializationAttempted = false; + private initializationFailed = false; + private hits = 0; + private misses = 0; + + constructor(options?: QueryCacheOptions) { + this.redisUrl = options?.redisUrl ?? process.env.REDIS_URL; + this.ttlSeconds = options?.ttlSeconds ?? RERANK_CONFIG.cache.queryResultTTL; + this.keyPrefix = options?.keyPrefix ?? "rerank:"; + + // Lazy initialization - only connect when first used + this.logger.info({ + msg: "QueryCache initialized (lazy mode)", + ttlSeconds: this.ttlSeconds, + keyPrefix: this.keyPrefix, + redisConfigured: !!this.redisUrl, + }); + } + + /** + * Initialize Redis connection (lazy). + * Returns true if successful, false if Redis unavailable. + */ + private async initialize(): Promise { + if (this.initializationAttempted) { + return !this.initializationFailed; + } + + this.initializationAttempted = true; + + if (!this.redisUrl) { + this.logger.warn({ + msg: "Redis URL not configured, query cache disabled", + hint: "Set REDIS_URL environment variable to enable query caching", + }); + this.initializationFailed = true; + return false; + } + + try { + // Dynamic import of ioredis + const { default: Redis } = await import("ioredis"); + + this.redis = new Redis(this.redisUrl, { + // Graceful error handling + lazyConnect: true, + retryStrategy: (times: number) => { + // Give up after 3 retries + if (times > 3) { + return null; + } + return Math.min(times * 100, 1000); + }, + maxRetriesPerRequest: 3, + }); + + // Connect and handle errors + await this.redis.connect(); + + this.redis.on("error", (error: Error) => { + this.logger.warn({ + msg: "Redis connection error, cache degraded", + error: error.message, + }); + }); + + this.logger.info({ msg: "Redis connected successfully" }); + return true; + } catch (error) { + this.logger.warn({ + msg: "Failed to initialize Redis, query cache disabled", + error: error instanceof Error ? error.message : String(error), + }); + this.initializationFailed = true; + this.redis = null; + return false; + } + } + + /** + * Generate cache key from query params. + * Uses SHA256 hash for consistent, compact keys. + */ + private generateKey(params: CacheKey): string { + // Normalize params for consistent hashing + const normalized = { + query: params.query.trim().toLowerCase(), + filters: params.filters ?? {}, + rerankTier: params.rerankTier ?? "default", + limit: params.limit ?? 10, + }; + + // Create deterministic JSON string + const data = JSON.stringify(normalized, Object.keys(normalized).sort()); + + // Hash for compact key + const hash = createHash("sha256").update(data).digest("hex"); + + return `${this.keyPrefix}${hash}`; + } + + /** + * Get cached results. + * Returns null if not found or Redis unavailable. + */ + async get(params: CacheKey): Promise { + // Initialize Redis if not already done + if (!this.redis) { + const initialized = await this.initialize(); + if (!initialized) { + this.misses++; + recordQueryCacheMiss(); + this.updateMetrics(); + return null; // Graceful degradation + } + } + + try { + const key = this.generateKey(params); + const cached = await this.redis.get(key); + + if (!cached) { + this.misses++; + recordQueryCacheMiss(); + this.updateMetrics(); + return null; + } + + // Parse cached JSON + const results = JSON.parse(cached) as BatchedRerankResult[]; + + this.logger.debug({ + msg: "Cache hit", + key, + resultCount: results.length, + }); + + this.hits++; + recordQueryCacheHit(); + this.updateMetrics(); + + return results; + } catch (error) { + // Graceful degradation on error + this.logger.warn({ + msg: "Cache get failed, degrading gracefully", + error: error instanceof Error ? error.message : String(error), + }); + recordQueryCacheError(); + this.misses++; + recordQueryCacheMiss(); + this.updateMetrics(); + return null; + } + } + + /** + * Cache results. + * Silently fails if Redis unavailable. + */ + async set(params: CacheKey, results: BatchedRerankResult[]): Promise { + // Initialize Redis if not already done + if (!this.redis) { + const initialized = await this.initialize(); + if (!initialized) { + return; // Graceful degradation + } + } + + try { + const key = this.generateKey(params); + const serialized = JSON.stringify(results); + + await this.redis.setex(key, this.ttlSeconds, serialized); + + this.logger.debug({ + msg: "Cached results", + key, + resultCount: results.length, + ttlSeconds: this.ttlSeconds, + }); + } catch (error) { + // Graceful degradation on error + this.logger.warn({ + msg: "Cache set failed, continuing without caching", + error: error instanceof Error ? error.message : String(error), + }); + recordQueryCacheError(); + } + } + + /** + * Invalidate by pattern (e.g., all queries for a document). + * Pattern uses Redis SCAN for safe iteration. + */ + async invalidatePattern(pattern: string): Promise { + // Initialize Redis if not already done + if (!this.redis) { + const initialized = await this.initialize(); + if (!initialized) { + return; // Graceful degradation + } + } + + try { + const fullPattern = `${this.keyPrefix}${pattern}`; + let cursor = "0"; + let keysDeleted = 0; + + do { + // SCAN for keys matching pattern + const [nextCursor, keys] = await this.redis.scan( + cursor, + "MATCH", + fullPattern, + "COUNT", + 100, + ); + cursor = nextCursor; + + if (keys.length > 0) { + await this.redis.del(...keys); + keysDeleted += keys.length; + } + } while (cursor !== "0"); + + this.logger.info({ + msg: "Invalidated cache pattern", + pattern: fullPattern, + keysDeleted, + }); + } catch (error) { + // Graceful degradation on error + this.logger.warn({ + msg: "Cache invalidation failed", + pattern, + error: error instanceof Error ? error.message : String(error), + }); + recordQueryCacheError(); + } + } + + /** + * Clear all cache entries with this prefix. + */ + async clear(): Promise { + await this.invalidatePattern("*"); + } + + /** + * Disconnect from Redis. + * Call on application shutdown. + */ + async disconnect(): Promise { + if (this.redis) { + try { + await this.redis.quit(); + this.logger.info({ msg: "Redis connection closed" }); + } catch (error) { + this.logger.warn({ + msg: "Error disconnecting from Redis", + error: error instanceof Error ? error.message : String(error), + }); + } + } + } + + /** + * Check if Redis is available. + */ + isAvailable(): boolean { + return this.redis !== null && !this.initializationFailed; + } + + /** + * Update Prometheus metrics with current cache stats. + */ + private updateMetrics(): void { + const hitRate = computeHitRate(this.hits, this.misses); + queryCacheHitRate.set(hitRate); + } +} diff --git a/packages/search/src/services/query-features.test.ts b/packages/search/src/services/query-features.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..06d2e9db54b011254ee7c157ff2df930989942ef --- /dev/null +++ b/packages/search/src/services/query-features.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from "vitest"; +import { getFusionHints, QueryFeatureExtractor } from "./query-features"; + +describe("QueryFeatureExtractor", () => { + const extractor = new QueryFeatureExtractor(); + + describe("extract", () => { + it("should extract length correctly", () => { + const features = extractor.extract("How many tokens in this query?"); + expect(features.length).toBe(6); + }); + + it("should detect temporal markers", () => { + const temporal = extractor.extract("What happened yesterday?"); + const nonTemporal = extractor.extract("What is machine learning?"); + + expect(temporal.hasTemporal).toBe(true); + expect(nonTemporal.hasTemporal).toBe(false); + }); + + it("should classify factoid questions", () => { + const who = extractor.extract("Who founded Microsoft?"); + const what = extractor.extract("What is the capital of France?"); + const when = extractor.extract("When was the company started?"); + const where = extractor.extract("Where is the headquarters?"); + + expect(who.questionType).toBe("factoid"); + expect(what.questionType).toBe("factoid"); + expect(when.questionType).toBe("temporal"); // 'when' triggers temporal + expect(where.questionType).toBe("factoid"); + }); + + it("should classify list questions", () => { + const list = extractor.extract("List all the features"); + const enumerate = extractor.extract("Enumerate the steps"); + + expect(list.questionType).toBe("list"); + expect(enumerate.questionType).toBe("list"); + }); + + it("should classify comparison questions", () => { + // 'compare' keyword triggers comparison + const compare = extractor.extract("Compare React and Vue"); + // 'difference' keyword triggers comparison + const difference = extractor.extract("explain the difference between them"); + + expect(compare.questionType).toBe("comparison"); + expect(difference.questionType).toBe("comparison"); + }); + + it("should classify causal questions", () => { + const why = extractor.extract("Why did the test fail?"); + const how = extractor.extract("How does authentication work?"); + + expect(why.questionType).toBe("causal"); + expect(how.questionType).toBe("causal"); + }); + + it("should classify opinion questions", () => { + // Need 'think' keyword without leading 'what' to avoid factoid classification + const opinion = extractor.extract("Do you think TypeScript is good?"); + const recommend = extractor.extract("Would you recommend Redux?"); + + expect(opinion.questionType).toBe("opinion"); + expect(recommend.questionType).toBe("opinion"); + }); + + it("should detect entity density", () => { + const withEntities = extractor.extract("Tell me about Microsoft and Google"); + const withoutEntities = extractor.extract("how do i do this"); + + expect(withEntities.entityDensity).toBeGreaterThan(0); + expect(withoutEntities.entityDensity).toBe(0); + }); + + it("should detect specific terms", () => { + // Version numbers are specific + const withVersion = extractor.extract("How to upgrade to v2.0.0?"); + // Entities are specific + const withEntity = extractor.extract("Tell me about Microsoft Azure"); + const plain = extractor.extract("how to implement login"); + + expect(withVersion.hasSpecificTerms).toBe(true); + expect(withEntity.hasSpecificTerms).toBe(true); + expect(plain.hasSpecificTerms).toBe(false); + }); + + it("should calculate complexity", () => { + const simple = extractor.extract("What is X?"); + const complex = extractor.extract( + "If the user is authenticated and has admin role, how should the system handle permission checks?", + ); + + expect(complex.complexity).toBeGreaterThan(simple.complexity); + }); + }); + + describe("toNormalizedVector", () => { + it("should return normalized feature vector", () => { + const features = extractor.extract("Who founded Microsoft in 1975?"); + const normalized = extractor.toNormalizedVector(features); + + expect(normalized.vector).toHaveLength(8); + expect(normalized.names).toHaveLength(8); + + // All values should be between 0 and ~1 + for (const val of normalized.vector) { + expect(val).toBeGreaterThanOrEqual(0); + expect(val).toBeLessThanOrEqual(2); // Some normalization may exceed 1 + } + }); + }); + + describe("buildIDFIndex", () => { + it("should build IDF index from corpus", () => { + const localExtractor = new QueryFeatureExtractor(); + localExtractor.buildIDFIndex(["The quick brown fox", "The lazy dog", "The quick rabbit"]); + + // 'the' appears in all docs, should have low IDF + // 'fox' appears in one doc, should have high IDF + const commonFeatures = localExtractor.extract("the"); + const rareFeatures = localExtractor.extract("fox"); + + expect(rareFeatures.avgIDF).toBeGreaterThan(commonFeatures.avgIDF); + }); + + it("should detect rare terms after IDF index built", () => { + const localExtractor = new QueryFeatureExtractor({ + rareTermThreshold: 1.0, // Lower threshold to make rare detection easier + }); + localExtractor.buildIDFIndex([ + "common word appears here", + "common word appears again", + "common word once more", + "unique special appears once", + ]); + + const withRare = localExtractor.extract("unique"); + const withCommon = localExtractor.extract("common"); + + // 'unique' should be rare since it only appears in 1 of 4 docs (IDF = log(4/1) = 1.38) + // 'common' appears in 3 of 4 docs (IDF = log(4/3) = 0.29) + expect(withRare.avgIDF).toBeGreaterThan(withCommon.avgIDF); + }); + }); +}); + +describe("getFusionHints", () => { + const extractor = new QueryFeatureExtractor(); + + it("should suggest balanced weights for factoid questions with entities", () => { + const features = extractor.extract("Who is the CEO of Apple?"); + const hints = getFusionHints(features); + + // Factoid with entity - should have reasonable dense weight + // But entity presence may also increase sparse weight + expect(hints.dense).toBeGreaterThanOrEqual(0.25); + expect(hints.sparse).toBeGreaterThanOrEqual(0.25); + }); + + it("should suggest higher sparse weight for queries with specific terms", () => { + const features = extractor.extract("error TS2345 in TypeScript"); + const hints = getFusionHints(features); + + // Specific terms should favor sparse + expect(hints.sparse).toBeGreaterThanOrEqual(0.3); + }); + + it("should suggest higher rerank weight for complex queries", () => { + const simple = extractor.extract("What is X?"); + const complex = extractor.extract( + "Compare the performance implications of using Redux versus MobX for state management in a large React application", + ); + + const simpleHints = getFusionHints(simple); + const complexHints = getFusionHints(complex); + + expect(complexHints.rerank).toBeGreaterThanOrEqual(simpleHints.rerank); + }); + + it("should return weights that sum to approximately 1", () => { + const features = extractor.extract("Any random query here"); + const hints = getFusionHints(features); + + const sum = hints.dense + hints.sparse + hints.rerank; + expect(sum).toBeCloseTo(1.0, 1); + }); +}); diff --git a/packages/search/src/services/query-features.ts b/packages/search/src/services/query-features.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7049473afda4045fd3a4d4f89031e9eab1b63f0 --- /dev/null +++ b/packages/search/src/services/query-features.ts @@ -0,0 +1,397 @@ +/** + * Query feature extraction for learned fusion weight prediction. + * + * Extracts features from queries that can be used to predict optimal + * fusion weights for combining dense/sparse/rerank results. + */ + +/** + * Question type classification for query analysis. + */ +export type QuestionType = + | "factoid" // Who, what, when, where + | "list" // List all, enumerate + | "comparison" // Compare, difference + | "causal" // Why, how + | "opinion" // What do you think + | "temporal" // Time-based queries + | "other"; + +/** + * Extracted features from a query for fusion weight prediction. + */ +export interface FusionQueryFeatures { + /** Number of tokens in the query */ + length: number; + /** Ratio of named entities to total tokens (0-1) */ + entityDensity: number; + /** Whether query contains temporal markers */ + hasTemporal: boolean; + /** Classified question type */ + questionType: QuestionType; + /** Average IDF of query terms */ + avgIDF: number; + /** Whether query contains rare terms (IDF > threshold) */ + hasRareTerms: boolean; + /** Whether query contains specific keywords/entities */ + hasSpecificTerms: boolean; + /** Query complexity score (0-1) */ + complexity: number; +} + +/** + * Normalized feature vector for ML model input. + */ +export interface FusionNormalizedFeatures { + /** Features as array for model input */ + vector: number[]; + /** Feature names for debugging */ + names: string[]; +} + +/** + * Configuration for the feature extractor. + */ +export interface QueryFeatureExtractorConfig { + /** IDF index for term frequency analysis */ + idfIndex?: Map; + /** Threshold for considering a term "rare" */ + rareTermThreshold?: number; +} + +const DEFAULT_CONFIG: QueryFeatureExtractorConfig = { + rareTermThreshold: 5.0, +}; + +/** + * Extracts features from queries for learned fusion weight prediction. + * + * @example + * ```typescript + * const extractor = new QueryFeatureExtractor(); + * const features = extractor.extract("Who founded Microsoft in 1975?"); + * // features.questionType = "factoid" + * // features.hasTemporal = true + * // features.entityDensity = 0.33 (Microsoft is an entity) + * ``` + */ +export class QueryFeatureExtractor { + private config: Required; + private idfIndex: Map; + + constructor(config: QueryFeatureExtractorConfig = {}) { + this.config = { ...DEFAULT_CONFIG, ...config } as Required; + this.idfIndex = config.idfIndex ?? new Map(); + } + + /** + * Set or update the IDF index for term frequency analysis. + */ + setIDFIndex(index: Map): void { + this.idfIndex = index; + } + + /** + * Build IDF index from a corpus of documents. + */ + buildIDFIndex(documents: string[]): void { + const docCount = documents.length; + const termDocCounts = new Map(); + + // Count documents containing each term + for (const doc of documents) { + const terms = new Set(this.tokenize(doc)); + for (const term of terms) { + termDocCounts.set(term, (termDocCounts.get(term) ?? 0) + 1); + } + } + + // Calculate IDF: log(N / df) + this.idfIndex = new Map(); + for (const [term, df] of termDocCounts) { + this.idfIndex.set(term, Math.log(docCount / df)); + } + } + + /** + * Extract features from a query. + */ + extract(query: string): FusionQueryFeatures { + const tokens = this.tokenize(query); + const entities = this.extractEntities(query); + + return { + length: tokens.length, + entityDensity: tokens.length > 0 ? entities.length / tokens.length : 0, + hasTemporal: this.detectTemporal(query), + questionType: this.classifyQuestion(query), + avgIDF: this.calculateAvgIDF(tokens), + hasRareTerms: this.hasRareTerms(tokens), + hasSpecificTerms: entities.length > 0 || this.hasSpecificKeywords(query), + complexity: this.calculateComplexity(query, tokens), + }; + } + + /** + * Convert features to normalized vector for ML model input. + */ + toNormalizedVector(features: FusionQueryFeatures): FusionNormalizedFeatures { + const vector = [ + features.length / 20, // Normalize to ~0-1 for typical queries + features.entityDensity, + features.hasTemporal ? 1 : 0, + this.encodeQuestionType(features.questionType), + features.avgIDF / 10, // Normalize IDF + features.hasRareTerms ? 1 : 0, + features.hasSpecificTerms ? 1 : 0, + features.complexity, + ]; + + const names = [ + "length_norm", + "entity_density", + "has_temporal", + "question_type", + "avg_idf_norm", + "has_rare_terms", + "has_specific_terms", + "complexity", + ]; + + return { vector, names }; + } + + /** + * Simple tokenization (words, lowercase). + */ + private tokenize(text: string): string[] { + return text + .toLowerCase() + .replace(/[^\w\s]/g, " ") + .split(/\s+/) + .filter((t) => t.length > 0); + } + + /** + * Extract named entities using simple heuristics. + * Returns capitalized words that aren't at sentence start. + */ + private extractEntities(query: string): string[] { + const entities: string[] = []; + + // Match capitalized words not at the start of the query + const words = query.split(/\s+/); + for (let i = 1; i < words.length; i++) { + const word = words[i].replace(/[^\w]/g, ""); + if (word.length > 1 && /^[A-Z]/.test(word)) { + entities.push(word); + } + } + + // Also match common entity patterns + const patterns = [ + /\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)+\b/g, // Multi-word names + /\b[A-Z]{2,}\b/g, // Acronyms + /\b\d{4}\b/g, // Years + ]; + + for (const pattern of patterns) { + const matches = query.match(pattern); + if (matches) { + entities.push(...matches); + } + } + + return [...new Set(entities)]; + } + + /** + * Detect temporal expressions in query. + */ + private detectTemporal(query: string): boolean { + const temporalPatterns = + /\b(yesterday|today|tomorrow|last|recent|before|after|when|during|since|ago|week|month|year|january|february|march|april|may|june|july|august|september|october|november|december|\d{4})\b/i; + return temporalPatterns.test(query); + } + + /** + * Classify question type based on query patterns. + */ + private classifyQuestion(query: string): QuestionType { + const lower = query.toLowerCase(); + + // Check for temporal markers first (overlaps with factoid) + if (this.detectTemporal(query) && /^when\b/.test(lower)) { + return "temporal"; + } + + // Factoid questions (who, what, when, where) + if (/^(who|what|when|where|which)\b/.test(lower)) { + return "factoid"; + } + + // List questions + if (/^(list|enumerate|name|give me all|what are all)\b/.test(lower)) { + return "list"; + } + + // Comparison questions + if (/\b(compare|difference|versus|vs|differ|between)\b/.test(lower)) { + return "comparison"; + } + + // Causal questions (why, how) + if (/^(why|how)\b/.test(lower)) { + return "causal"; + } + + // Opinion questions + if (/\b(think|opinion|feel|believe|should|recommend)\b/.test(lower)) { + return "opinion"; + } + + return "other"; + } + + /** + * Calculate average IDF of query terms. + */ + private calculateAvgIDF(tokens: string[]): number { + if (tokens.length === 0 || this.idfIndex.size === 0) { + return 0; + } + + let totalIDF = 0; + let count = 0; + + for (const token of tokens) { + const idf = this.idfIndex.get(token); + if (idf !== undefined) { + totalIDF += idf; + count++; + } + } + + return count > 0 ? totalIDF / count : 0; + } + + /** + * Check if query contains rare terms (high IDF). + */ + private hasRareTerms(tokens: string[]): boolean { + for (const token of tokens) { + const idf = this.idfIndex.get(token); + if (idf !== undefined && idf > this.config.rareTermThreshold) { + return true; + } + } + return false; + } + + /** + * Check for specific keywords that suggest keyword search would help. + */ + private hasSpecificKeywords(query: string): boolean { + // Technical terms, version numbers, etc. + const specificPatterns = [ + /v\d+(\.\d+)*/i, // Version numbers + /\b[A-Z][a-z]+[A-Z]\w*\b/, // CamelCase + /\b\w+[-_]\w+\b/, // Hyphenated/underscored terms + /"[^"]+"/g, // Quoted phrases + ]; + + return specificPatterns.some((p) => p.test(query)); + } + + /** + * Calculate query complexity based on structure and content. + */ + private calculateComplexity(query: string, tokens: string[]): number { + let complexity = 0; + + // Length contributes to complexity + complexity += Math.min(tokens.length / 15, 0.3); + + // Multiple clauses + if (/\b(and|or|but|however|although)\b/i.test(query)) { + complexity += 0.2; + } + + // Nested questions + if ((query.match(/\?/g) || []).length > 1) { + complexity += 0.2; + } + + // Conditional language + if (/\b(if|when|assuming|given that)\b/i.test(query)) { + complexity += 0.15; + } + + // Multiple entities + const entities = this.extractEntities(query); + complexity += Math.min(entities.length * 0.1, 0.2); + + return Math.min(complexity, 1.0); + } + + /** + * Encode question type as numeric value for ML model. + */ + private encodeQuestionType(type: QuestionType): number { + const encoding: Record = { + factoid: 0.0, + list: 0.15, + comparison: 0.3, + causal: 0.45, + temporal: 0.6, + opinion: 0.75, + other: 0.9, + }; + return encoding[type]; + } +} + +/** + * Recommended fusion weight hints based on query features. + * This provides rule-based defaults when no trained model is available. + */ +export function getFusionHints(features: FusionQueryFeatures): { + dense: number; + sparse: number; + rerank: number; +} { + // Default balanced weights + let dense = 0.4; + let sparse = 0.3; + let rerank = 0.3; + + // Factoid queries benefit from dense (semantic) + if (features.questionType === "factoid") { + dense = 0.5; + sparse = 0.2; + rerank = 0.3; + } + + // Queries with specific terms benefit from sparse (keyword) + if (features.hasSpecificTerms || features.hasRareTerms) { + sparse = 0.4; + dense = 0.3; + rerank = 0.3; + } + + // Complex queries benefit more from reranking + if (features.complexity > 0.5) { + rerank = 0.4; + dense = 0.35; + sparse = 0.25; + } + + // Short keyword-like queries favor sparse + if (features.length <= 3 && !features.hasTemporal) { + sparse = 0.5; + dense = 0.25; + rerank = 0.25; + } + + return { dense, sparse, rerank }; +} diff --git a/packages/search/src/services/rate-limiter.test.ts b/packages/search/src/services/rate-limiter.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4b8fd2dbd7211943a492b259834519a6159cd43 --- /dev/null +++ b/packages/search/src/services/rate-limiter.test.ts @@ -0,0 +1,353 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { RateLimiter } from "./rate-limiter"; + +describe("RateLimiter", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + describe("Rate Limiting", () => { + it("should allow requests within limit", () => { + const limiter = new RateLimiter({ + maxRequests: 3, + windowMs: 60000, // 1 minute + }); + + const user = "user1"; + + // First request + let check = limiter.checkLimit(user); + expect(check.allowed).toBe(true); + expect(check.remaining).toBe(3); + limiter.recordRequest(user); + + // Second request + check = limiter.checkLimit(user); + expect(check.allowed).toBe(true); + expect(check.remaining).toBe(2); + limiter.recordRequest(user); + + // Third request + check = limiter.checkLimit(user); + expect(check.allowed).toBe(true); + expect(check.remaining).toBe(1); + limiter.recordRequest(user); + }); + + it("should block requests exceeding limit", () => { + const limiter = new RateLimiter({ + maxRequests: 2, + windowMs: 60000, + }); + + const user = "user1"; + + // Use up the quota + limiter.recordRequest(user); + limiter.recordRequest(user); + + // Next request should be blocked + const check = limiter.checkLimit(user); + expect(check.allowed).toBe(false); + expect(check.remaining).toBe(0); + expect(check.reason).toContain("Rate limit exceeded"); + }); + + it("should implement sliding window correctly", () => { + const limiter = new RateLimiter({ + maxRequests: 3, + windowMs: 60000, // 1 minute + }); + + const user = "user1"; + + // Make request at T=0 + limiter.recordRequest(user); + + // Advance 30 seconds and make another request + vi.advanceTimersByTime(30000); + limiter.recordRequest(user); + + // Make third request at T=30s + limiter.recordRequest(user); + + // Should be blocked now (3 requests in window) + let check = limiter.checkLimit(user); + expect(check.allowed).toBe(false); + + // Advance time by 31 seconds (T=61s, first request at T=0 expired) + vi.advanceTimersByTime(31000); + check = limiter.checkLimit(user); + expect(check.allowed).toBe(true); // Should be allowed now + expect(check.remaining).toBe(1); // Two requests still in window (at T=30s) + }); + + it("should track users independently", () => { + const limiter = new RateLimiter({ + maxRequests: 2, + windowMs: 60000, + }); + + // User 1 uses quota + limiter.recordRequest("user1"); + limiter.recordRequest("user1"); + + // User 1 blocked + let check = limiter.checkLimit("user1"); + expect(check.allowed).toBe(false); + + // User 2 still has quota + check = limiter.checkLimit("user2"); + expect(check.allowed).toBe(true); + expect(check.remaining).toBe(2); + }); + }); + + describe("Cost Attribution", () => { + it("should track cost per request", () => { + const limiter = new RateLimiter({ + maxRequests: 100, + windowMs: 3600000, // 1 hour + trackCosts: true, + costPerRequest: 5, // 5 cents + budgetLimit: 100, // $1 budget + }); + + const user = "user1"; + + // Make 10 requests + for (let i = 0; i < 10; i++) { + limiter.recordRequest(user); + } + + // Check usage + const usage = limiter.getUsage(user); + expect(usage.requestCount).toBe(10); + expect(usage.totalCost).toBe(50); // 10 * 5 cents + expect(usage.budgetExceeded).toBe(false); + }); + + it("should block requests when budget exceeded", () => { + const limiter = new RateLimiter({ + maxRequests: 100, + windowMs: 3600000, + trackCosts: true, + costPerRequest: 10, // 10 cents + budgetLimit: 50, // 50 cents budget + }); + + const user = "user1"; + + // Make 5 requests (50 cents total) + for (let i = 0; i < 5; i++) { + limiter.recordRequest(user); + } + + // Budget should be exceeded + const check = limiter.checkLimit(user); + expect(check.allowed).toBe(false); + expect(check.reason).toContain("Budget limit exceeded"); + + const usage = limiter.getUsage(user); + expect(usage.budgetExceeded).toBe(true); + expect(usage.totalCost).toBe(50); + }); + + it("should allow custom cost per request", () => { + const limiter = new RateLimiter({ + maxRequests: 100, + windowMs: 3600000, + trackCosts: true, + costPerRequest: 5, // Default 5 cents + budgetLimit: 1000, + }); + + const user = "user1"; + + // Record request with custom cost + limiter.recordRequest(user, "llm", 25); // 25 cents + + const usage = limiter.getUsage(user); + expect(usage.totalCost).toBe(25); + }); + + it("should not track costs if disabled", () => { + const limiter = new RateLimiter({ + maxRequests: 10, + windowMs: 60000, + trackCosts: false, + }); + + const user = "user1"; + + limiter.recordRequest(user); + limiter.recordRequest(user); + + const usage = limiter.getUsage(user); + expect(usage.totalCost).toBe(0); + expect(usage.budgetExceeded).toBe(false); + }); + }); + + describe("Usage Statistics", () => { + it("should provide accurate usage statistics", () => { + const limiter = new RateLimiter({ + maxRequests: 10, + windowMs: 60000, + trackCosts: true, + costPerRequest: 5, + budgetLimit: 1000, + }); + + const user = "user1"; + + // Make some requests + limiter.recordRequest(user); + limiter.recordRequest(user); + limiter.recordRequest(user); + + const usage = limiter.getUsage(user); + expect(usage.requestCount).toBe(3); + expect(usage.totalCost).toBe(15); + expect(usage.budgetExceeded).toBe(false); + expect(usage.oldestRequest).toBeInstanceOf(Date); + }); + + it("should clean up expired requests in usage stats", () => { + const limiter = new RateLimiter({ + maxRequests: 10, + windowMs: 60000, + }); + + const user = "user1"; + + // Make 3 requests at T=0 + limiter.recordRequest(user); + limiter.recordRequest(user); + limiter.recordRequest(user); + + // Check usage at T=0 + let usage = limiter.getUsage(user); + expect(usage.requestCount).toBe(3); + + // Advance time past window + vi.advanceTimersByTime(61000); + + // Check usage again - should be 0 + usage = limiter.getUsage(user); + expect(usage.requestCount).toBe(0); + expect(usage.oldestRequest).toBeNull(); + }); + }); + + describe("Admin Functions", () => { + it("should reset user limits", () => { + const limiter = new RateLimiter({ + maxRequests: 2, + windowMs: 60000, + }); + + const user = "user1"; + + // Use up quota + limiter.recordRequest(user); + limiter.recordRequest(user); + + // Blocked + let check = limiter.checkLimit(user); + expect(check.allowed).toBe(false); + + // Reset user + limiter.resetUser(user); + + // Should be allowed now + check = limiter.checkLimit(user); + expect(check.allowed).toBe(true); + expect(check.remaining).toBe(2); + }); + + it("should reset all limits", () => { + const limiter = new RateLimiter({ + maxRequests: 1, + windowMs: 60000, + }); + + // Multiple users use quota + limiter.recordRequest("user1"); + limiter.recordRequest("user2"); + limiter.recordRequest("user3"); + + // All blocked + expect(limiter.checkLimit("user1").allowed).toBe(false); + expect(limiter.checkLimit("user2").allowed).toBe(false); + expect(limiter.checkLimit("user3").allowed).toBe(false); + + // Reset all + limiter.resetAll(); + + // All should be allowed now + expect(limiter.checkLimit("user1").allowed).toBe(true); + expect(limiter.checkLimit("user2").allowed).toBe(true); + expect(limiter.checkLimit("user3").allowed).toBe(true); + }); + }); + + describe("Cleanup", () => { + it("should clean up expired records periodically", () => { + const limiter = new RateLimiter({ + maxRequests: 10, + windowMs: 60000, + }); + + const user = "user1"; + + // Make a request + limiter.recordRequest(user); + + // Advance time past window + vi.advanceTimersByTime(61000); + + // Trigger cleanup (runs every 5 minutes) + vi.advanceTimersByTime(5 * 60 * 1000); + + // Usage should be clean + const usage = limiter.getUsage(user); + expect(usage.requestCount).toBe(0); + + // Cleanup + limiter.destroy(); + }); + + it("should stop cleanup interval on destroy", () => { + const limiter = new RateLimiter({ + maxRequests: 10, + windowMs: 60000, + }); + + // Destroy should not throw + expect(() => limiter.destroy()).not.toThrow(); + + // Second destroy should also not throw + expect(() => limiter.destroy()).not.toThrow(); + }); + }); + + describe("Default Configuration", () => { + it("should use default config for LLM tier", () => { + const limiter = new RateLimiter(); + const config = limiter.config; + + expect(config.maxRequests).toBe(100); + expect(config.windowMs).toBe(60 * 60 * 1000); // 1 hour + expect(config.trackCosts).toBe(true); + expect(config.costPerRequest).toBe(5); + expect(config.budgetLimit).toBe(1000); + }); + }); +}); diff --git a/packages/search/src/services/rate-limiter.ts b/packages/search/src/services/rate-limiter.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff6ff2f1a7552b9b631a66697d4502a171f592fd --- /dev/null +++ b/packages/search/src/services/rate-limiter.ts @@ -0,0 +1,362 @@ +import { createLogger } from "@engram/logger"; +import { Counter, Gauge } from "prom-client"; + +/** + * Rate limiter configuration for LLM reranker tier. + * + * Implements sliding window rate limiting to prevent excessive LLM API costs. + * Default: 100 requests per hour per user. + */ +export interface RateLimiterConfig { + /** Maximum requests per window */ + maxRequests: number; + /** Window duration in milliseconds */ + windowMs: number; + /** Enable cost attribution tracking */ + trackCosts?: boolean; + /** Cost per request (in cents) */ + costPerRequest?: number; + /** Budget limit in cents */ + budgetLimit?: number; +} + +interface RequestRecord { + timestamp: number; + cost?: number; +} + +interface UserLimitState { + requests: RequestRecord[]; + totalCost: number; + budgetExceeded: boolean; +} + +/** + * Prometheus metrics for rate limiting + */ +const rateLimitHitsCounter = new Counter({ + name: "engram_rate_limit_hits_total", + help: "Total rate limit hits by user", + labelNames: ["user_id", "tier"], +}); + +const rateLimitRemainingGauge = new Gauge({ + name: "engram_rate_limit_remaining", + help: "Remaining requests in current window", + labelNames: ["user_id", "tier"], +}); + +const costAttributionCounter = new Counter({ + name: "engram_rerank_cost_total_cents", + help: "Total reranking cost in cents", + labelNames: ["user_id", "tier"], +}); + +const budgetExceededCounter = new Counter({ + name: "engram_budget_exceeded_total", + help: "Total budget exceeded events", + labelNames: ["user_id", "tier"], +}); + +/** + * RateLimiter implements sliding window rate limiting for the LLM reranker tier. + * + * Features: + * - Sliding window algorithm for accurate rate limiting + * - Per-user/session tracking + * - Cost attribution and budget alerting + * - Prometheus metrics for monitoring + * - Automatic cleanup of expired records + */ +export class RateLimiter { + private limits: Map = new Map(); + private logger = createLogger({ component: "RateLimiter" }); + private config: Required; + private cleanupInterval: NodeJS.Timeout | null = null; + + constructor(config: RateLimiterConfig = RateLimiter.defaultConfig()) { + this.config = { + maxRequests: config.maxRequests, + windowMs: config.windowMs, + trackCosts: config.trackCosts ?? true, + costPerRequest: config.costPerRequest ?? 5, // Default 5 cents per LLM rerank + budgetLimit: config.budgetLimit ?? 1000, // Default $10 budget + }; + + // Start cleanup interval to remove expired records + this.startCleanup(); + } + + /** + * Default configuration: 100 requests per hour + */ + static defaultConfig(): RateLimiterConfig { + return { + maxRequests: 100, + windowMs: 60 * 60 * 1000, // 1 hour + trackCosts: true, + costPerRequest: 5, // 5 cents + budgetLimit: 1000, // $10 + }; + } + + /** + * Check if a request is allowed for the given user. + * + * @param userId - User or session identifier + * @param tier - Reranker tier (for metrics) + * @returns Object indicating if request is allowed and remaining quota + */ + checkLimit( + userId: string, + tier: string = "llm", + ): { allowed: boolean; remaining: number; resetAt: Date; reason?: string } { + const now = Date.now(); + const state = this.getUserState(userId); + + // Remove expired requests from sliding window + this.pruneExpiredRequests(state, now); + + // Check budget first if cost tracking is enabled + if (this.config.trackCosts && state.budgetExceeded) { + this.logger.warn({ + msg: "Budget exceeded for user", + userId, + totalCost: state.totalCost, + budgetLimit: this.config.budgetLimit, + }); + + budgetExceededCounter.inc({ user_id: userId, tier }); + + return { + allowed: false, + remaining: 0, + resetAt: this.getResetTime(state, now), + reason: `Budget limit exceeded: $${(state.totalCost / 100).toFixed(2)} / $${(this.config.budgetLimit / 100).toFixed(2)}`, + }; + } + + // Check rate limit + const requestCount = state.requests.length; + const remaining = Math.max(0, this.config.maxRequests - requestCount); + + if (requestCount >= this.config.maxRequests) { + this.logger.warn({ + msg: "Rate limit exceeded", + userId, + tier, + requestCount, + maxRequests: this.config.maxRequests, + windowMs: this.config.windowMs, + }); + + rateLimitHitsCounter.inc({ user_id: userId, tier }); + rateLimitRemainingGauge.set({ user_id: userId, tier }, 0); + + return { + allowed: false, + remaining: 0, + resetAt: this.getResetTime(state, now), + reason: `Rate limit exceeded: ${requestCount}/${this.config.maxRequests} requests in ${this.config.windowMs / 1000}s window`, + }; + } + + // Update gauge + rateLimitRemainingGauge.set({ user_id: userId, tier }, remaining); + + return { + allowed: true, + remaining, + resetAt: this.getResetTime(state, now), + }; + } + + /** + * Record a request for the given user. + * + * @param userId - User or session identifier + * @param tier - Reranker tier (for metrics) + * @param cost - Optional custom cost (overrides default) + */ + recordRequest(userId: string, tier: string = "llm", cost?: number): void { + const now = Date.now(); + const state = this.getUserState(userId); + const requestCost = cost ?? this.config.costPerRequest; + + // Add new request record + state.requests.push({ + timestamp: now, + cost: this.config.trackCosts ? requestCost : undefined, + }); + + // Update total cost + if (this.config.trackCosts && requestCost) { + state.totalCost += requestCost; + costAttributionCounter.inc({ user_id: userId, tier }, requestCost); + + // Check if budget exceeded + if (state.totalCost >= this.config.budgetLimit && !state.budgetExceeded) { + state.budgetExceeded = true; + + this.logger.error({ + msg: "User budget exceeded", + userId, + totalCost: state.totalCost, + budgetLimit: this.config.budgetLimit, + requestCount: state.requests.length, + }); + + budgetExceededCounter.inc({ user_id: userId, tier }); + } + } + + this.logger.debug({ + msg: "Request recorded", + userId, + tier, + cost: requestCost, + totalCost: state.totalCost, + requestCount: state.requests.length, + }); + } + + /** + * Get current usage statistics for a user. + */ + getUsage(userId: string): { + requestCount: number; + totalCost: number; + budgetExceeded: boolean; + oldestRequest: Date | null; + } { + const state = this.getUserState(userId); + this.pruneExpiredRequests(state, Date.now()); + + return { + requestCount: state.requests.length, + totalCost: state.totalCost, + budgetExceeded: state.budgetExceeded, + oldestRequest: state.requests[0]?.timestamp ? new Date(state.requests[0].timestamp) : null, + }; + } + + /** + * Reset limits for a user (admin function). + */ + resetUser(userId: string): void { + this.limits.delete(userId); + this.logger.info({ + msg: "User limits reset", + userId, + }); + } + + /** + * Reset all limits (admin function). + */ + resetAll(): void { + this.limits.clear(); + this.logger.info({ + msg: "All limits reset", + }); + } + + /** + * Get or create user limit state. + */ + private getUserState(userId: string): UserLimitState { + if (!this.limits.has(userId)) { + this.limits.set(userId, { + requests: [], + totalCost: 0, + budgetExceeded: false, + }); + } + const state = this.limits.get(userId); + if (!state) throw new Error("Failed to create user limit state"); + return state; + } + + /** + * Remove requests outside the sliding window. + * Also subtracts the cost of expired requests from totalCost. + */ + private pruneExpiredRequests(state: UserLimitState, now: number): void { + const cutoff = now - this.config.windowMs; + const expiredRequests = state.requests.filter((req) => req.timestamp <= cutoff); + const activeRequests = state.requests.filter((req) => req.timestamp > cutoff); + + // Subtract cost of expired requests from totalCost + if (this.config.trackCosts && expiredRequests.length > 0) { + const expiredCost = expiredRequests.reduce((sum, req) => sum + (req.cost || 0), 0); + state.totalCost = Math.max(0, state.totalCost - expiredCost); + + // Reset budget exceeded flag if cost drops below limit + if (state.budgetExceeded && state.totalCost < this.config.budgetLimit) { + state.budgetExceeded = false; + this.logger.info({ + msg: "User budget reset after cost expiration", + userId: "unknown", // We don't have userId here, but log the reset + newTotalCost: state.totalCost, + budgetLimit: this.config.budgetLimit, + }); + } + } + + state.requests = activeRequests; + } + + /** + * Calculate when the rate limit will reset for a user. + */ + private getResetTime(state: UserLimitState, now: number): Date { + if (state.requests.length === 0) { + return new Date(now + this.config.windowMs); + } + // Reset time is when the oldest request expires + const oldestTimestamp = state.requests[0].timestamp; + return new Date(oldestTimestamp + this.config.windowMs); + } + + /** + * Start periodic cleanup of expired records. + */ + private startCleanup(): void { + // Run cleanup every 5 minutes + this.cleanupInterval = setInterval( + () => { + const now = Date.now(); + let cleanedUsers = 0; + + for (const [userId, state] of this.limits.entries()) { + this.pruneExpiredRequests(state, now); + + // Remove user entry if no active requests + if (state.requests.length === 0 && !state.budgetExceeded) { + this.limits.delete(userId); + cleanedUsers++; + } + } + + if (cleanedUsers > 0) { + this.logger.debug({ + msg: "Rate limiter cleanup completed", + cleanedUsers, + remainingUsers: this.limits.size, + }); + } + }, + 5 * 60 * 1000, + ); // 5 minutes + } + + /** + * Stop cleanup interval (for testing/shutdown). + */ + destroy(): void { + if (this.cleanupInterval) { + clearInterval(this.cleanupInterval); + this.cleanupInterval = null; + } + } +} diff --git a/packages/search/src/services/reranker-integration.test.ts b/packages/search/src/services/reranker-integration.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..31e998df8a44f37677cbd60b0b16b0d249f5c554 --- /dev/null +++ b/packages/search/src/services/reranker-integration.test.ts @@ -0,0 +1,433 @@ +/** + * Integration tests for the reranking pipeline. + * + * This test suite verifies: + * 1. End-to-end reranking functionality + * 2. Tier routing integration + * 3. BatchedReranker integration with large candidate sets + * 4. Timeout fallback behavior + * 5. Score preservation (rrfScore, rerankerScore) + * + * REQUIREMENTS: + * - Qdrant running on localhost:6333 (use `bun infra:up`) + * - Run with: RUN_INTEGRATION_TESTS=1 npm test reranker-integration.test.ts + * + * These tests are skipped by default because they require infrastructure. + * Set RUN_INTEGRATION_TESTS=1 to enable them. + */ + +import { QdrantClient } from "@qdrant/js-client-rest"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +const RUN_INTEGRATION_TESTS = process.env.RUN_INTEGRATION_TESTS === "1"; + +import { BatchedReranker, type DocumentCandidate } from "./batched-reranker"; +import { RerankerRouter } from "./reranker-router"; +import { SearchRetriever } from "./retriever"; +import { TextEmbedder } from "./text-embedder"; + +const TEST_COLLECTION = "reranker_integration_test"; + +// Test documents designed to verify reranking behavior +const TEST_DOCUMENTS = [ + { + id: 1, + content: "Machine learning models require large datasets for training and validation.", + type: "thought", + }, + { + id: 2, + content: "Python is a popular programming language for data science and machine learning.", + type: "thought", + }, + { + id: 3, + content: "Neural networks are computational models inspired by biological neural systems.", + type: "thought", + }, + { + id: 4, + content: "function trainModel(data) { return model.fit(data); }", + type: "code", + }, + { + id: 5, + content: "Deep learning uses multiple layers to progressively extract features from data.", + type: "thought", + }, + { + id: 6, + content: "The weather today is sunny with a chance of rain in the afternoon.", + type: "thought", + }, + { + id: 7, + content: "import tensorflow as tf\nmodel = tf.keras.Sequential([tf.keras.layers.Dense(10)])", + type: "code", + }, + { + id: 8, + content: "Transformers revolutionized natural language processing with attention mechanisms.", + type: "thought", + }, +]; + +describe.skipIf(!RUN_INTEGRATION_TESTS)("Reranker Pipeline Integration", () => { + let client: QdrantClient; + let retriever: SearchRetriever; + let textEmbedder: TextEmbedder; + + beforeAll(async () => { + // Initialize services + client = new QdrantClient({ url: "http://localhost:6333" }); + retriever = new SearchRetriever(); + textEmbedder = new TextEmbedder(); + + // Clean up and create test collection + try { + await client.deleteCollection(TEST_COLLECTION); + } catch { + // Collection may not exist + } + + await client.createCollection(TEST_COLLECTION, { + vectors: { + text_dense: { + size: 384, // e5-small dimensions + distance: "Cosine", + }, + }, + }); + + // Index test documents + for (const doc of TEST_DOCUMENTS) { + const vector = await textEmbedder.embed(doc.content); + + await client.upsert(TEST_COLLECTION, { + points: [ + { + id: doc.id, + vector: { + text_dense: vector, + }, + payload: { + content: doc.content, + type: doc.type, + }, + }, + ], + }); + } + + // Allow time for indexing + await new Promise((resolve) => setTimeout(resolve, 500)); + }, 120000); // 2 minute timeout for model loading + + afterAll(async () => { + // Cleanup + try { + await client.deleteCollection(TEST_COLLECTION); + } catch { + // Ignore cleanup errors + } + }); + + describe("End-to-end reranking", () => { + it("should rerank search results when enabled", async () => { + const results = await retriever.search({ + text: "machine learning training", + limit: 5, + rerank: true, + rerankDepth: 10, + }); + + expect(results.length).toBeGreaterThan(0); + expect(results.length).toBeLessThanOrEqual(5); + + // Results should have rerankerScore OR be fallback (if timeout occurred) + // Check if we got reranked results or fallback + const hasRerankerScore = results.some((r) => Object.hasOwn(r, "rerankerScore")); + + if (hasRerankerScore) { + // Reranking succeeded + for (const result of results) { + expect(result).toHaveProperty("rerankerScore"); + expect(result).toHaveProperty("rrfScore"); + } + } + // If not, fallback occurred which is also valid behavior + + // Top result should be relevant to machine learning + const topDoc = results[0].payload as { content: string }; + expect(topDoc.content.toLowerCase()).toMatch( + /machine learning|neural|deep learning|transformer/, + ); + }); + + it("should skip reranking when disabled", async () => { + const results = await retriever.search({ + text: "machine learning training", + limit: 5, + rerank: false, + }); + + expect(results.length).toBeGreaterThan(0); + + // Results should NOT have rerankerScore + for (const result of results) { + expect(result).not.toHaveProperty("rerankerScore"); + } + }); + + it("should fall back to RRF on timeout", async () => { + // Create a retriever with very short timeout by mocking + // Note: This test relies on the 500ms timeout in the retriever + // We can't easily trigger it without mocking, so we verify the fallback logic exists + + const results = await retriever.search({ + text: "machine learning", + limit: 3, + rerank: true, + }); + + // Should get results either way (reranked or fallback) + expect(results.length).toBeGreaterThan(0); + expect(results.length).toBeLessThanOrEqual(3); + }); + + it("should preserve rrfScore and add rerankerScore", async () => { + const results = await retriever.search({ + text: "deep learning neural networks", + limit: 3, + rerank: true, + }); + + expect(results.length).toBeGreaterThan(0); + + for (const result of results) { + // Both scores should be present + expect(result).toHaveProperty("rrfScore"); + expect(result).toHaveProperty("rerankerScore"); + + // Scores should be numbers + expect(typeof result.rrfScore).toBe("number"); + expect(typeof result.rerankerScore).toBe("number"); + + // Final score should be rerankerScore + expect(result.score).toBe(result.rerankerScore); + } + }); + + it("should improve ranking quality vs no reranking", async () => { + const query = "what are neural networks"; + + // Search without reranking + const noRerank = await retriever.search({ + text: query, + limit: 5, + rerank: false, + }); + + // Search with reranking + const withRerank = await retriever.search({ + text: query, + limit: 5, + rerank: true, + }); + + expect(noRerank.length).toBeGreaterThan(0); + expect(withRerank.length).toBeGreaterThan(0); + + // The neural networks doc should be ranked higher with reranking + const neuralDocId = 3; // "Neural networks are computational models..." + + const noRerankPos = noRerank.findIndex((r) => r.id === neuralDocId); + const withRerankPos = withRerank.findIndex((r) => r.id === neuralDocId); + + // If the doc appears in both results, reranking should rank it higher + if (noRerankPos !== -1 && withRerankPos !== -1) { + expect(withRerankPos).toBeLessThanOrEqual(noRerankPos); + } + }); + }); + + describe("Tier routing integration", () => { + const router = new RerankerRouter(); + + it("should route code queries to code tier", () => { + const codeQuery = "function trainModel() { return model.fit(); }"; + const routing = router.route(codeQuery); + + expect(routing.tier).toBe("code"); + expect(routing.model).toContain("jina"); + expect(routing.reason).toMatch(/code/i); + }); + + it("should route complex queries to accurate tier", () => { + const complexQuery = + "Explain how transformer architectures use self-attention mechanisms to process sequential data and why they are superior to recurrent neural networks for long-range dependencies"; + const routing = router.route(complexQuery); + + expect(routing.tier).toBe("accurate"); + expect(routing.model).toContain("bge-reranker"); + expect(routing.reason).toMatch(/complex|agentic/i); + }); + + it("should route simple queries to fast tier", () => { + const simpleQuery = "machine learning"; + const routing = router.route(simpleQuery); + + expect(routing.tier).toBe("fast"); + expect(routing.model).toContain("MiniLM"); + }); + + it("should respect forceTier option", () => { + const query = "simple query"; + + const forcedRouting = router.route(query, { forceTier: "accurate" }); + + expect(forcedRouting.tier).toBe("accurate"); + expect(forcedRouting.reason).toMatch(/forced/i); + }); + + it("should route based on content type", () => { + const query = "search for code"; + + const routing = router.route(query, { contentType: "code" }); + + expect(routing.tier).toBe("code"); + expect(routing.reason).toMatch(/code/i); + }); + + it("should route based on latency budget", () => { + const query = "machine learning models"; + + // Very tight latency budget + const tightBudget = router.route(query, { latencyBudgetMs: 30 }); + expect(tightBudget.tier).toBe("fast"); + expect(tightBudget.reason).toMatch(/latency/i); + + // Generous latency budget + const genBudget = router.route(query, { latencyBudgetMs: 2000 }); + // Should not force fast tier based on latency alone + expect(genBudget.tier).toMatch(/fast|accurate/); + }); + }); + + describe("BatchedReranker integration", () => { + it("should handle large candidate sets with batching", async () => { + const reranker = new BatchedReranker({ + model: "Xenova/ms-marco-MiniLM-L-6-v2", + maxBatchSize: 4, + maxConcurrency: 2, + }); + + // Create 20 candidate documents + const candidates: DocumentCandidate[] = TEST_DOCUMENTS.map((doc) => ({ + id: doc.id, + content: doc.content, + score: Math.random(), + })); + + const results = await reranker.rerank("machine learning neural networks", candidates, 5); + + expect(results).toHaveLength(5); + + // Results should be sorted by score descending + for (let i = 1; i < results.length; i++) { + expect(results[i - 1].score).toBeGreaterThanOrEqual(results[i].score); + } + }); + + it("should maintain score ordering", async () => { + const reranker = BatchedReranker.forTier("fast"); + + const candidates: DocumentCandidate[] = [ + { + id: 1, + content: + "Deep learning is a subset of machine learning that uses neural networks with multiple hidden layers to learn hierarchical representations of data", + score: 0.8, + }, + { id: 2, content: "The weather is nice and sunny today", score: 0.9 }, + { + id: 3, + content: "Machine learning algorithms train models on labeled data", + score: 0.7, + }, + ]; + + const results = await reranker.rerank("what is deep learning", candidates, 3); + + // All documents should be ranked + expect(results.length).toBe(3); + + // The reranked scores should put deep learning doc highly ranked + const deepLearningResult = results.find((r) => r.id === 1); + expect(deepLearningResult).toBeDefined(); + + // Deep learning doc should be ranked higher than weather doc + const deepLearningIdx = results.findIndex((r) => r.id === 1); + const weatherIdx = results.findIndex((r) => r.id === 2); + + expect(deepLearningIdx).toBeLessThan(weatherIdx); + }); + + it("should preserve original scores and indices", async () => { + const reranker = BatchedReranker.forTier("fast"); + + const candidates: DocumentCandidate[] = [ + { id: "a", content: "First document about ML", score: 0.95 }, + { id: "b", content: "Second document about AI", score: 0.85 }, + { id: "c", content: "Third document about data", score: 0.75 }, + ]; + + const results = await reranker.rerank("machine learning", candidates, 3); + + for (const result of results) { + expect(result).toHaveProperty("originalScore"); + expect(result).toHaveProperty("originalIndex"); + + // Original score should match one of the input scores + expect([0.95, 0.85, 0.75]).toContain(result.originalScore); + + // Original index should be valid + expect(result.originalIndex).toBeGreaterThanOrEqual(0); + expect(result.originalIndex).toBeLessThan(candidates.length); + } + }); + + it("should handle empty candidate sets", async () => { + const reranker = BatchedReranker.forTier("fast"); + + const results = await reranker.rerank("test query", [], 5); + + expect(results).toEqual([]); + }); + + it("should work with different tier models", async () => { + const fastReranker = BatchedReranker.forTier("fast"); + const accurateReranker = BatchedReranker.forTier("accurate"); + + const candidates: DocumentCandidate[] = [ + { id: 1, content: "Machine learning training involves neural networks", score: 0.8 }, + ]; + + // Fast and accurate tiers should be able to rerank + const fastResults = await fastReranker.rerank("ML training", candidates, 1); + const accurateResults = await accurateReranker.rerank("ML training", candidates, 1); + + expect(fastResults).toHaveLength(1); + expect(accurateResults).toHaveLength(1); + + // All should have valid scores + expect(fastResults[0].score).toBeGreaterThanOrEqual(0); + expect(fastResults[0].score).toBeLessThanOrEqual(1); + + expect(accurateResults[0].score).toBeGreaterThanOrEqual(0); + expect(accurateResults[0].score).toBeLessThanOrEqual(1); + + // Note: Code tier (Jina model) is skipped due to compatibility issues with current transformers.js version + }); + }); +}); diff --git a/packages/search/src/services/reranker-metrics.ts b/packages/search/src/services/reranker-metrics.ts new file mode 100644 index 0000000000000000000000000000000000000000..22997b0ad37800abd74d78a62d0391d452ec9fb3 --- /dev/null +++ b/packages/search/src/services/reranker-metrics.ts @@ -0,0 +1,100 @@ +import { Counter, Gauge, Histogram } from "prom-client"; + +/** + * Prometheus metrics for reranking pipeline observability. + * + * These metrics enable monitoring of: + * - Reranking latency by tier and model + * - Candidate counts processed + * - Score improvements from reranking + * - Request success/failure rates + */ + +/** + * Latency histogram by tier + * + * Tracks how long reranking takes for different tiers. + * Buckets are tuned for sub-second and low-latency operations: + * - 10ms-50ms: fast tier + * - 50ms-250ms: accurate/code tiers + * - 500ms-2000ms: LLM tier + */ +export const rerankLatencyHistogram = new Histogram({ + name: "engram_rerank_latency_seconds", + help: "Reranking latency in seconds", + labelNames: ["tier", "model"], + buckets: [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2], +}); + +/** + * Candidate count histogram + * + * Tracks how many candidates are being reranked. + * Helps understand query complexity and batch sizes. + */ +export const rerankCandidatesHistogram = new Histogram({ + name: "engram_rerank_candidates_count", + help: "Number of candidates processed", + labelNames: ["tier"], + buckets: [5, 10, 20, 30, 50, 100], +}); + +/** + * Score improvement gauge + * + * Tracks average score improvement after reranking. + * Positive values indicate reranking is improving relevance. + * Can be used to measure reranking effectiveness. + */ +export const scoreImprovementGauge = new Gauge({ + name: "engram_rerank_score_improvement", + help: "Average score improvement after reranking", + labelNames: ["tier"], +}); + +/** + * Rerank requests counter + * + * Tracks total rerank requests with success/failure status. + * Use to monitor error rates and throughput. + */ +export const rerankRequestsCounter = new Counter({ + name: "engram_rerank_requests_total", + help: "Total rerank requests", + labelNames: ["tier", "status"], +}); + +/** + * Record metrics for a reranking operation. + * + * @param tier - The reranker tier used + * @param model - The model identifier + * @param latencySeconds - Time taken in seconds + * @param candidateCount - Number of candidates processed + * @param scoreImprovement - Average score improvement (optional) + * @param status - success or failure + */ +export function recordRerankMetrics(params: { + tier: string; + model: string; + latencySeconds: number; + candidateCount: number; + scoreImprovement?: number; + status: "success" | "failure"; +}): void { + const { tier, model, latencySeconds, candidateCount, scoreImprovement, status } = params; + + // Record latency + rerankLatencyHistogram.observe({ tier, model }, latencySeconds); + + // Record candidate count + rerankCandidatesHistogram.observe({ tier }, candidateCount); + + // Record score improvement if provided + if (scoreImprovement !== undefined) { + scoreImprovementGauge.set({ tier }, scoreImprovement); + } + + // Increment request counter + rerankRequestsCounter.inc({ tier, status }); +} diff --git a/packages/search/src/services/reranker-router.test.ts b/packages/search/src/services/reranker-router.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d25bb755a29427777639adc58ea131a0995c7dfe --- /dev/null +++ b/packages/search/src/services/reranker-router.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from "vitest"; +import { RerankerRouter } from "./reranker-router"; + +describe("RerankerRouter", () => { + const router = new RerankerRouter(); + + describe("route()", () => { + describe("forceTier option", () => { + it("should use forced tier when specified", () => { + const result = router.route("any query", { forceTier: "accurate" }); + expect(result.tier).toBe("accurate"); + expect(result.reason).toContain("Forced tier"); + }); + + it("should use llm tier when forced", () => { + const result = router.route("any query", { forceTier: "llm" }); + expect(result.tier).toBe("llm"); + }); + }); + + describe("code pattern detection", () => { + it("should route method calls to code tier", () => { + const result = router.route("console.log()"); + expect(result.tier).toBe("code"); + expect(result.reason).toContain("code patterns"); + }); + + it("should route function declarations to code tier", () => { + const result = router.route("function handleClick"); + expect(result.tier).toBe("code"); + }); + + it("should route class declarations to code tier", () => { + const result = router.route("class UserService"); + expect(result.tier).toBe("code"); + }); + + it("should route arrow functions to code tier", () => { + const result = router.route("const fn = () =>"); + expect(result.tier).toBe("code"); + }); + + it("should route import statements to code tier", () => { + const result = router.route("import { useState }"); + expect(result.tier).toBe("code"); + }); + + it("should route code contentType to code tier", () => { + const result = router.route("simple query", { contentType: "code" }); + expect(result.tier).toBe("code"); + }); + }); + + describe("complex query detection", () => { + it("should route long queries to accurate tier", () => { + const longQuery = + "How do I implement a distributed cache invalidation strategy across multiple services with eventual consistency guarantees?"; + const result = router.route(longQuery); + expect(result.tier).toBe("accurate"); + expect(result.reason).toContain("Complex query"); + }); + + it("should route queries with operators AND long text to accurate tier", () => { + // Score: length > 50 (+2) + operators (+2) + word count > 8 (+1) = 5 (complex) + const result = router.route( + "authentication AND authorization NOT oauth implementation strategy patterns examples best practices", + ); + expect(result.tier).toBe("accurate"); + }); + + it("should route moderate queries with operators to fast tier", () => { + // Score: length > 25 (+1) + operators (+2) = 3 (moderate) → fast tier + const result = router.route("authentication AND authorization NOT oauth"); + expect(result.tier).toBe("fast"); + }); + }); + + describe("agentic query detection", () => { + it("should route tool-related queries to accurate tier", () => { + const result = router.route("how to call the tool"); + expect(result.tier).toBe("accurate"); + expect(result.reason).toContain("Agentic"); + }); + + it("should route execute-related queries to accurate tier", () => { + const result = router.route("execute the function"); + expect(result.tier).toBe("accurate"); + }); + + it("should route API-related queries to accurate tier", () => { + const result = router.route("api endpoint for users"); + expect(result.tier).toBe("accurate"); + }); + }); + + describe("latency budget", () => { + it("should use fast tier for tight latency budgets", () => { + const result = router.route("simple query", { latencyBudgetMs: 30 }); + expect(result.tier).toBe("fast"); + expect(result.reason).toContain("latency"); + }); + + it("should use fast tier when budget is below accurate threshold", () => { + const result = router.route("moderately complex query here", { + latencyBudgetMs: 100, + }); + expect(result.tier).toBe("fast"); + }); + }); + + describe("default routing", () => { + it("should default to fast tier for simple queries", () => { + const result = router.route("hello"); + expect(result.tier).toBe("fast"); + expect(result.reason).toContain("simple query"); + }); + + it("should use fast tier for moderate complexity", () => { + const result = router.route("how to implement login"); + expect(result.tier).toBe("fast"); + }); + }); + }); + + describe("shouldUseLLM()", () => { + it("should return true when forceTier is llm", () => { + expect(router.shouldUseLLM("any query", { forceTier: "llm" })).toBe(true); + }); + + it("should return false by default", () => { + expect(router.shouldUseLLM("any query")).toBe(false); + }); + + it("should return false even for complex queries", () => { + const complexQuery = + "Explain the distributed consensus algorithm with Byzantine fault tolerance"; + expect(router.shouldUseLLM(complexQuery)).toBe(false); + }); + }); + + describe("getModelForTier()", () => { + it("should return model for fast tier", () => { + const model = router.getModelForTier("fast"); + expect(model).toContain("MiniLM"); + }); + + it("should return model for accurate tier", () => { + const model = router.getModelForTier("accurate"); + expect(model).toContain("bge-reranker"); + }); + + it("should return model for code tier", () => { + const model = router.getModelForTier("code"); + expect(model).toContain("jina"); + }); + + it("should return model for llm tier", () => { + const model = router.getModelForTier("llm"); + expect(model).toContain("grok"); + }); + }); + + describe("routing result structure", () => { + it("should include all required fields", () => { + const result = router.route("test query"); + + expect(result).toHaveProperty("tier"); + expect(result).toHaveProperty("model"); + expect(result).toHaveProperty("maxCandidates"); + expect(result).toHaveProperty("reason"); + + expect(typeof result.tier).toBe("string"); + expect(typeof result.model).toBe("string"); + expect(typeof result.maxCandidates).toBe("number"); + expect(typeof result.reason).toBe("string"); + }); + + it("should have reasonable maxCandidates values", () => { + const result = router.route("test query"); + expect(result.maxCandidates).toBeGreaterThan(0); + expect(result.maxCandidates).toBeLessThanOrEqual(100); + }); + }); +}); diff --git a/packages/search/src/services/reranker-router.ts b/packages/search/src/services/reranker-router.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f0d2f05e854301acf928927d404521e6be357c2 --- /dev/null +++ b/packages/search/src/services/reranker-router.ts @@ -0,0 +1,132 @@ +import { RERANK_CONFIG } from "../config"; +import type { RerankerTier } from "../models/schema"; +import { QueryClassifier } from "./classifier"; + +export interface RerankerRoutingResult { + /** Selected reranker tier */ + tier: RerankerTier; + /** Model identifier for the selected tier */ + model: string; + /** Maximum candidates to process */ + maxCandidates: number; + /** Human-readable reason for the routing decision */ + reason: string; +} + +export interface RoutingOptions { + /** Force a specific tier (bypasses routing logic) */ + forceTier?: RerankerTier; + /** Content type filter from query */ + contentType?: "thought" | "code" | "doc"; + /** User tier/subscription level (future use) */ + userTier?: "free" | "pro" | "enterprise"; + /** Latency budget in milliseconds */ + latencyBudgetMs?: number; +} + +/** + * RerankerRouter selects the appropriate reranker tier based on query characteristics. + * + * Routing rules (in priority order): + * 1. If forceTier is specified, use it + * 2. If query contains code patterns → code tier + * 3. If query is complex or agentic → accurate tier + * 4. If latency budget is tight → fast tier + * 5. Default → fast tier + */ +export class RerankerRouter { + private classifier: QueryClassifier; + + constructor() { + this.classifier = new QueryClassifier(); + } + + /** + * Route a query to the appropriate reranker tier. + */ + route(query: string, options: RoutingOptions = {}): RerankerRoutingResult { + const { forceTier, contentType, latencyBudgetMs } = options; + + // Priority 1: Forced tier + if (forceTier) { + return this.createResult(forceTier, `Forced tier: ${forceTier}`); + } + + // Priority 2: Code content type or code query patterns + if (contentType === "code" || this.classifier.isCodeQuery(query)) { + return this.createResult("code", "Query contains code patterns"); + } + + // Priority 3: Complex or agentic queries + const { complexity, score } = this.classifier.classifyComplexity(query); + if (complexity === "complex") { + return this.createResult("accurate", `Complex query (score: ${score})`); + } + + if (this.classifier.isAgenticQuery(query)) { + return this.createResult("accurate", "Agentic/tool-related query"); + } + + // Priority 4: Tight latency budget + if (latencyBudgetMs !== undefined) { + const fastConfig = RERANK_CONFIG.tiers.fast; + const accurateConfig = RERANK_CONFIG.tiers.accurate; + + if (latencyBudgetMs < fastConfig.maxLatencyMs) { + // Very tight budget - might need to skip reranking entirely + return this.createResult("fast", `Tight latency budget (${latencyBudgetMs}ms)`); + } + + if (latencyBudgetMs < accurateConfig.maxLatencyMs) { + return this.createResult("fast", `Latency budget favors fast tier (${latencyBudgetMs}ms)`); + } + } + + // Priority 5: Moderate complexity + if (complexity === "moderate") { + // For moderate queries, use fast tier but could upgrade based on other signals + return this.createResult("fast", `Moderate complexity (score: ${score})`); + } + + // Default: Fast tier for simple queries + return this.createResult("fast", "Default routing (simple query)"); + } + + /** + * Check if LLM reranking should be used for this query. + * LLM tier is only used when explicitly requested or for very high-value queries. + */ + shouldUseLLM(_query: string, options: RoutingOptions = {}): boolean { + // LLM tier must be explicitly forced for now + if (options.forceTier === "llm") { + return true; + } + + // Future: Could add logic for enterprise users or high-stakes queries + return false; + } + + /** + * Get the model for a specific tier. + */ + getModelForTier(tier: RerankerTier): string { + return RERANK_CONFIG.tiers[tier].model; + } + + /** + * Get max candidates for a tier. + */ + getMaxCandidatesForTier(tier: RerankerTier): number { + const config = RERANK_CONFIG.tiers[tier]; + return config.maxCandidates ?? RERANK_CONFIG.depth; + } + + private createResult(tier: RerankerTier, reason: string): RerankerRoutingResult { + return { + tier, + model: this.getModelForTier(tier), + maxCandidates: this.getMaxCandidatesForTier(tier), + reason, + }; + } +} diff --git a/packages/search/src/services/reranker.test.ts b/packages/search/src/services/reranker.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad86345fe5168dbcba283e879cf5cf6c1ffbba85 --- /dev/null +++ b/packages/search/src/services/reranker.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it, vi } from "vitest"; +import { Reranker } from "./reranker"; + +const { mockPipeline } = vi.hoisted(() => { + const mockPipeline = vi.fn(async (_task: string, _model: string) => { + return async (input: any) => { + // Mock scoring logic: if text_pair contains "relevant", give high score + const doc = input.text_pair; + if (doc.includes("relevant")) { + return [{ label: "LABEL_1", score: 0.9 }]; + } + return [{ label: "LABEL_0", score: 0.1 }]; + }; + }); + return { mockPipeline }; +}); + +vi.mock("@huggingface/transformers", () => ({ + pipeline: mockPipeline, +})); + +describe("Reranker", () => { + it("should rerank documents", async () => { + const reranker = new Reranker(); + const query = "find relevant"; + const docs = ["bad doc", "very relevant doc", "another doc"]; + + const results = await reranker.rerank(query, docs, 2); + + expect(mockPipeline).toHaveBeenCalledWith( + "text-classification", + "Xenova/bge-reranker-base", + expect.any(Object), + ); + + expect(results).toHaveLength(2); + expect(results[0].document).toBe("very relevant doc"); + expect(results[0].score).toBe(0.9); + }); +}); diff --git a/packages/search/src/services/reranker.ts b/packages/search/src/services/reranker.ts new file mode 100644 index 0000000000000000000000000000000000000000..0dd999b374f2adf2a0704aafe37a3488e966671e --- /dev/null +++ b/packages/search/src/services/reranker.ts @@ -0,0 +1,86 @@ +import { pipeline } from "@huggingface/transformers"; + +export interface RerankResult { + index: number; + score: number; +} + +export class Reranker { + private static instance: unknown; + private static modelName = "Xenova/bge-reranker-base"; // Standard small reranker + + static async getInstance() { + if (!Reranker.instance) { + // 'text-classification' is appropriate for Cross-Encoders (they output a score/logit) + // Some rerankers output a single logit (regression) or 2 logits (classification). + // bge-reranker usually outputs a single score. + Reranker.instance = await pipeline("text-classification", Reranker.modelName, { + dtype: "q8", + }); + } + return Reranker.instance; + } + + async rerank( + query: string, + documents: string[], + topK = 5, + ): Promise<{ document: string; score: number; originalIndex: number }[]> { + const classifier = await Reranker.getInstance(); + + // Construct pairs + // Transformers.js pipeline input for pairs: { text: string, text_pair: string } or [string, string] + // We need to check support. + // Most robust way: use tokenizer + model directly if pipeline is flaky on pairs. + // But pipeline SHOULD support it. + + // We process sequentially or in batches. + // For simplicity in V1, we process sequentially or use Promise.all (if instance handles concurrency, which JS runtime does). + + const scores: { index: number; score: number }[] = []; + + for (let i = 0; i < documents.length; i++) { + const classifyFn = classifier as (input: { + text: string; + text_pair: string; + }) => Promise>; + const output = await classifyFn({ text: query, text_pair: documents[i] }); + // Output for bge-reranker usually: [{ label: 'LABEL_0', score: 0.99 }] or similar. + // CrossEncoders trained for ranking often output a single logit or Sigmoid score. + // If it returns a list of labels, we need to know which label is "relevant". + // BGE-Reranker usually returns a single value if treated as regression, or 'LABEL_0'/'LABEL_1'. + // Actually, bge-reranker models on HF are often AutoModelForSequenceClassification with 1 label? + // Let's assume it returns a score object. + // We'll take the score. + // If multiple labels, usually the positive class score is what we want. + // Let's assume 'LABEL_1' is positive if binary, or just use the score if single. + + let score = 0; + if (Array.isArray(output)) { + // Find label with highest score or specific label? + // For BGE, typically high logit = relevant. + // If outputs [{ label: 'LABEL_0', score: ... }] + // We might need to inspect the model config. + // Fallback: Use the score of the first element if only 1, or look for '1'/'relevant'. + // For now, we use output[0].score assuming regression or binary positive at 0. + score = output[0].score; + } else if (typeof output === "object" && "score" in output) { + score = (output as { score: number }).score; + } + + scores.push({ index: i, score }); + } + + // Sort descending + scores.sort((a, b) => b.score - a.score); + + // Top K + const top = scores.slice(0, topK); + + return top.map((s) => ({ + document: documents[s.index], + score: s.score, + originalIndex: s.index, + })); + } +} diff --git a/packages/search/src/services/retriever.test.ts b/packages/search/src/services/retriever.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c892b60ac419e0654eae306d71428bb069025a61 --- /dev/null +++ b/packages/search/src/services/retriever.test.ts @@ -0,0 +1,154 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mockQdrantClient = { + search: vi.fn(async () => []), + query: vi.fn(async () => ({ points: [] })), +}; + +const mockEmbedder = { + embedQuery: vi.fn(async () => new Array(384).fill(0.1)), + embedSparseQuery: vi.fn(async () => ({ indices: [100, 200, 300], values: [0.5, 0.3, 0.2] })), +}; + +const mockCodeEmbedder = { + embedQuery: vi.fn(async () => new Array(768).fill(0.2)), +}; + +const mockClassifier = { + classify: vi.fn(() => ({ strategy: "dense", alpha: 1.0 })), +}; + +vi.mock("@qdrant/js-client-rest", () => ({ + QdrantClient: vi.fn(() => mockQdrantClient), +})); + +vi.mock("./text-embedder", () => ({ + TextEmbedder: vi.fn(() => mockEmbedder), +})); + +vi.mock("./code-embedder", () => ({ + CodeEmbedder: vi.fn(() => mockCodeEmbedder), +})); + +vi.mock("./classifier", () => ({ + QueryClassifier: vi.fn(() => mockClassifier), +})); + +// Import after mocking +const { SearchRetriever } = await import("./retriever"); + +describe("SearchRetriever", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("should perform dense search", async () => { + const retriever = new SearchRetriever(); + const query = { + text: "test query", + strategy: "dense", + }; + + await retriever.search(query as any); + + expect(mockEmbedder.embedQuery).toHaveBeenCalledWith("test query"); + expect(mockQdrantClient.search).toHaveBeenCalled(); + const call = mockQdrantClient.search.mock.calls[0]; + expect(call[0]).toBe("engram_memory"); + expect(call[1].vector.name).toBe("text_dense"); + }); + + it("should use classifier if strategy not provided", async () => { + const retriever = new SearchRetriever(); + const query = { text: "test query" }; + + await retriever.search(query as any); + + expect(mockClassifier.classify).toHaveBeenCalledWith("test query"); + expect(mockQdrantClient.search).toHaveBeenCalled(); + }); + + it("should perform sparse-only search", async () => { + const retriever = new SearchRetriever(); + const query = { + text: "exact match query", + strategy: "sparse", + }; + + await retriever.search(query as any); + + expect(mockEmbedder.embedSparseQuery).toHaveBeenCalledWith("exact match query"); + expect(mockQdrantClient.query).toHaveBeenCalled(); + const call = mockQdrantClient.query.mock.calls[0]; + expect(call[0]).toBe("engram_memory"); + expect(call[1].using).toBe("sparse"); + expect(call[1].query).toEqual({ + indices: [100, 200, 300], + values: [0.5, 0.3, 0.2], + }); + }); + + it("should perform hybrid search with RRF fusion", async () => { + const retriever = new SearchRetriever(); + const query = { + text: "hybrid search query", + strategy: "hybrid", + }; + + await retriever.search(query as any); + + // Both embedders should be called + expect(mockEmbedder.embedQuery).toHaveBeenCalledWith("hybrid search query"); + expect(mockEmbedder.embedSparseQuery).toHaveBeenCalledWith("hybrid search query"); + + // Should use query() with prefetch + expect(mockQdrantClient.query).toHaveBeenCalled(); + const call = mockQdrantClient.query.mock.calls[0]; + expect(call[0]).toBe("engram_memory"); + + // Verify prefetch array structure + expect(call[1].prefetch).toHaveLength(2); + expect(call[1].prefetch[0].using).toBe("text_dense"); + expect(call[1].prefetch[1].using).toBe("sparse"); + + // Verify RRF fusion + expect(call[1].query).toEqual({ fusion: "rrf" }); + }); + + it("should use code_dense vector for code search in hybrid mode", async () => { + const retriever = new SearchRetriever(); + const query = { + text: "function definition", + strategy: "hybrid", + filters: { type: "code" }, + }; + + await retriever.search(query as any); + + // Should use code embedder for dense vector + expect(mockCodeEmbedder.embedQuery).toHaveBeenCalledWith("function definition"); + + const call = mockQdrantClient.query.mock.calls[0]; + expect(call[1].prefetch[0].using).toBe("code_dense"); + }); + + it("should oversample in prefetch for better fusion", async () => { + const retriever = new SearchRetriever(); + const query = { + text: "test query", + strategy: "hybrid", + limit: 5, + rerankDepth: 10, // Explicit rerankDepth for predictable test + }; + + await retriever.search(query as any); + + const call = mockQdrantClient.query.mock.calls[0]; + // Prefetch uses Math.max(rerankDepth, limit) * 2 for oversampling + // With rerankDepth=10, limit=5: fetchLimit=10, prefetch=20 + expect(call[1].prefetch[0].limit).toBe(20); + expect(call[1].prefetch[1].limit).toBe(20); + // Final limit is fetchLimit (rerankDepth when reranking) + expect(call[1].limit).toBe(10); + }); +}); diff --git a/packages/search/src/services/retriever.ts b/packages/search/src/services/retriever.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc827cb2f0d98550ca612ede9321e2143652f1ab --- /dev/null +++ b/packages/search/src/services/retriever.ts @@ -0,0 +1,247 @@ +import { createLogger } from "@engram/logger"; +import { QdrantClient } from "@qdrant/js-client-rest"; +import { DEFAULT_SEARCH_CONFIG } from "../config"; +import type { SearchQuery } from "../models/schema"; +import { QueryClassifier } from "./classifier"; +import { CodeEmbedder } from "./code-embedder"; +import { Reranker } from "./reranker"; +import { TextEmbedder } from "./text-embedder"; + +/** Default depth for reranking - how many candidates to fetch before reranking */ +const DEFAULT_RERANK_DEPTH = 30; + +/** Maximum time to wait for reranking before falling back to RRF results */ +const RERANK_TIMEOUT_MS = 500; + +/** Creates a timeout promise that rejects after specified milliseconds */ +function createTimeout(ms: number): Promise { + return new Promise((_, reject) => { + setTimeout(() => reject(new Error(`Reranking timeout after ${ms}ms`)), ms); + }); +} + +export class SearchRetriever { + private client: QdrantClient; + private textEmbedder: TextEmbedder; + private codeEmbedder: CodeEmbedder; + private classifier: QueryClassifier; + private reranker: Reranker; + private collectionName = "engram_memory"; + private logger = createLogger({ component: "SearchRetriever" }); + + constructor(url: string = "http://localhost:6333") { + this.client = new QdrantClient({ url }); + this.textEmbedder = new TextEmbedder(); + this.codeEmbedder = new CodeEmbedder(); + this.classifier = new QueryClassifier(); + this.reranker = new Reranker(); + } + + async search(query: SearchQuery) { + const { + text, + limit = DEFAULT_SEARCH_CONFIG.limits.defaultResults, + strategy: userStrategy, + filters, + threshold, + rerank = true, + rerankDepth = DEFAULT_RERANK_DEPTH, + } = query; + + // Determine effective limit: oversample if reranking is enabled + const fetchLimit = rerank ? Math.max(rerankDepth, limit) : limit; + + // Determine strategy using classifier if not provided + let strategy = userStrategy; + if (!strategy) { + const classification = this.classifier.classify(text); + strategy = classification.strategy; + // We could use classification.alpha for hybrid weighting later + } + + const effectiveThreshold = threshold ?? DEFAULT_SEARCH_CONFIG.minScore[strategy]; + + // Determine which vector field to use based on type filter + const isCodeSearch = filters?.type === "code"; + const vectorName = isCodeSearch ? "code_dense" : "text_dense"; + + // Build Filter + const filter: Record = {}; + if (filters) { + const conditions = []; + if (filters.session_id) { + conditions.push({ key: "session_id", match: { value: filters.session_id } }); + } + if (filters.type) { + conditions.push({ key: "type", match: { value: filters.type } }); + } + if (conditions.length > 0) { + filter.must = conditions; + } + } + + // Fetch raw results based on strategy + let rawResults: Array<{ id: string | number; score: number; payload?: unknown }> = []; + + // Dense Search + if (strategy === "dense") { + const vector = isCodeSearch + ? await this.codeEmbedder.embedQuery(text) + : await this.textEmbedder.embedQuery(text); + + const denseResults = await this.client.search(this.collectionName, { + vector: { + name: vectorName, + vector: vector, + }, + filter: Object.keys(filter).length > 0 ? filter : undefined, + limit: fetchLimit, + with_payload: true, + score_threshold: effectiveThreshold, + }); + + rawResults = denseResults; + } + // Hybrid Search (Dense + Sparse with RRF Fusion) + else if (strategy === "hybrid") { + // Generate both dense and sparse query vectors in parallel + const [denseVector, sparseVector] = await Promise.all([ + isCodeSearch ? this.codeEmbedder.embedQuery(text) : this.textEmbedder.embedQuery(text), + this.textEmbedder.embedSparseQuery(text), + ]); + + // Prefetch from both vector spaces, fuse with RRF + const results = await this.client.query(this.collectionName, { + prefetch: [ + { + query: denseVector, + using: vectorName, + limit: fetchLimit * 2, // Oversample for fusion + }, + { + query: { + indices: sparseVector.indices, + values: sparseVector.values, + }, + using: "sparse", + limit: fetchLimit * 2, + }, + ], + query: { fusion: "rrf" }, + filter: Object.keys(filter).length > 0 ? filter : undefined, + limit: fetchLimit, + with_payload: true, + // No score_threshold with RRF (scores are rank-based, not similarity-based) + }); + + rawResults = results.points; + } + // Sparse Search + else if (strategy === "sparse") { + const sparseVector = await this.textEmbedder.embedSparseQuery(text); + + const results = await this.client.query(this.collectionName, { + query: { + indices: sparseVector.indices, + values: sparseVector.values, + }, + using: "sparse", + filter: Object.keys(filter).length > 0 ? filter : undefined, + limit: fetchLimit, + with_payload: true, + score_threshold: effectiveThreshold, + }); + + rawResults = results.points; + } + + // Apply reranking if enabled + if (rerank && rawResults.length > 0) { + const rerankStartTime = Date.now(); + + this.logger.debug({ + msg: "Starting reranking", + strategy, + candidateCount: rawResults.length, + limit, + rerankDepth, + }); + + try { + // Extract content for reranking + const documents = rawResults.map((r) => { + const payload = r.payload as { content?: string } | undefined; + return payload?.content ?? ""; + }); + + // Rerank with timeout circuit breaker + const reranked = await Promise.race([ + this.reranker.rerank(text, documents, limit), + createTimeout(RERANK_TIMEOUT_MS), + ]); + + const rerankLatencyMs = Date.now() - rerankStartTime; + + // Calculate score statistics + const originalScores = rawResults.slice(0, limit).map((r) => r.score); + const rerankedScores = reranked.map((r) => r.score); + const avgOriginalScore = originalScores.reduce((a, b) => a + b, 0) / originalScores.length; + const avgRerankedScore = rerankedScores.reduce((a, b) => a + b, 0) / rerankedScores.length; + const scoreImprovement = avgRerankedScore - avgOriginalScore; + + this.logger.info({ + msg: "Reranking completed", + strategy, + candidateCount: rawResults.length, + returnedCount: reranked.length, + rerankLatencyMs, + avgOriginalScore: avgOriginalScore.toFixed(3), + avgRerankedScore: avgRerankedScore.toFixed(3), + scoreImprovement: scoreImprovement.toFixed(3), + }); + + // Map reranked results back to original results with scores + return reranked.map((r) => { + const original = rawResults[r.originalIndex]; + return { + ...original, + score: r.score, // Use reranker score as final score + rrfScore: original.score, // Preserve original RRF/dense score + rerankerScore: r.score, + }; + }); + } catch (error) { + const rerankLatencyMs = Date.now() - rerankStartTime; + const errorMessage = error instanceof Error ? error.message : String(error); + + // Circuit breaker: fall back to RRF results on timeout or error + this.logger.error({ + msg: "Reranking failed - graceful degradation to original results", + strategy, + candidateCount: rawResults.length, + rerankLatencyMs, + error: errorMessage, + stack: error instanceof Error ? error.stack : undefined, + }); + + // Return results with degradation flags + return rawResults.slice(0, limit).map((result) => ({ + ...result, + degraded: true, + degradedReason: `Reranker failed: ${errorMessage}`, + })); + } + } + + // No reranking - return raw results trimmed to limit + this.logger.debug({ + msg: "Skipping reranking", + strategy, + resultCount: rawResults.length, + limit, + rerankEnabled: rerank, + }); + + return rawResults.slice(0, limit); + } +} diff --git a/packages/search/src/services/schema-manager.test.ts b/packages/search/src/services/schema-manager.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b14616b6a76eeaf4ebd97baac7bb18c14253f71 --- /dev/null +++ b/packages/search/src/services/schema-manager.test.ts @@ -0,0 +1,67 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { SchemaManager, VECTOR_DIMENSIONS } from "./schema-manager"; + +const mockCreateCollection = vi.fn(async () => {}); +const mockDeleteCollection = vi.fn(async () => {}); +const mockGetCollections = vi.fn(async () => ({ collections: [] })); + +vi.mock("@qdrant/js-client-rest", () => { + return { + QdrantClient: class { + createCollection = mockCreateCollection; + deleteCollection = mockDeleteCollection; + getCollections = mockGetCollections; + }, + }; +}); + +describe("SchemaManager", () => { + beforeEach(() => { + mockCreateCollection.mockClear(); + mockDeleteCollection.mockClear(); + mockGetCollections.mockClear(); + }); + + it("should create collection with separate text and code vectors", async () => { + mockGetCollections.mockResolvedValueOnce({ collections: [] }); + + const manager = new SchemaManager(); + await manager.ensureCollection(); + + expect(mockGetCollections).toHaveBeenCalled(); + expect(mockCreateCollection).toHaveBeenCalled(); + const call = mockCreateCollection.mock.calls[0]; + expect(call[0]).toBe("engram_memory"); + + // Verify separate vector fields + const config = call[1]; + expect(config.vectors.text_dense.size).toBe(VECTOR_DIMENSIONS.text); + expect(config.vectors.code_dense.size).toBe(VECTOR_DIMENSIONS.code); + expect(config.vectors.text_dense.distance).toBe("Cosine"); + expect(config.vectors.code_dense.distance).toBe("Cosine"); + }); + + it("should skip creation if exists", async () => { + mockGetCollections.mockResolvedValueOnce({ + collections: [{ name: "engram_memory" }], + }); + + const manager = new SchemaManager(); + await manager.ensureCollection(); + + expect(mockGetCollections).toHaveBeenCalled(); + expect(mockCreateCollection).not.toHaveBeenCalled(); + }); + + it("should migrate collection by deleting and recreating", async () => { + mockGetCollections + .mockResolvedValueOnce({ collections: [{ name: "engram_memory" }] }) // For migration check + .mockResolvedValueOnce({ collections: [] }); // For ensureCollection + + const manager = new SchemaManager(); + await manager.migrateToMultiVectorSchema(); + + expect(mockDeleteCollection).toHaveBeenCalledWith("engram_memory"); + expect(mockCreateCollection).toHaveBeenCalled(); + }); +}); diff --git a/packages/search/src/services/schema-manager.ts b/packages/search/src/services/schema-manager.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2243b21df6317c46d81155b37d3827816528887 --- /dev/null +++ b/packages/search/src/services/schema-manager.ts @@ -0,0 +1,75 @@ +import { QdrantClient } from "@qdrant/js-client-rest"; + +// Vector dimensions for different embedding models +export const VECTOR_DIMENSIONS = { + text: 384, // e5-small + code: 768, // nomic-embed-text-v1 + colbert: 128, // jina-colbert-v2 token dimension +} as const; + +export class SchemaManager { + private client: QdrantClient; + private collectionName = "engram_memory"; + + constructor(url: string = "http://localhost:6333") { + this.client = new QdrantClient({ url }); + } + + async ensureCollection() { + const response = await this.client.getCollections(); + const exists = response.collections.some((c) => c.name === this.collectionName); + + if (!exists) { + console.log(`Creating collection ${this.collectionName}...`); + await this.client.createCollection(this.collectionName, { + vectors: { + // Separate vector fields for different content types + text_dense: { + size: VECTOR_DIMENSIONS.text, // e5-small: 384 dimensions + distance: "Cosine", + }, + code_dense: { + size: VECTOR_DIMENSIONS.code, // nomic-embed-text-v1: 768 dimensions + distance: "Cosine", + }, + // ColBERT multivector for late interaction reranking + colbert: { + size: VECTOR_DIMENSIONS.colbert, // jina-colbert-v2: 128d token embeddings + distance: "Cosine", + multivector_config: { + comparator: "max_sim", // MaxSim for late interaction + }, + }, + }, + sparse_vectors: { + sparse: { + index: { + on_disk: false, + datatype: "float16", + }, + }, + }, + }); + console.log(`Collection ${this.collectionName} created.`); + } else { + console.log(`Collection ${this.collectionName} already exists.`); + } + } + + /** + * Migrate existing collection to new schema with separate text/code vectors. + * This will delete and recreate the collection - use with caution! + */ + async migrateToMultiVectorSchema() { + const response = await this.client.getCollections(); + const exists = response.collections.some((c) => c.name === this.collectionName); + + if (exists) { + console.log(`Deleting existing collection ${this.collectionName} for migration...`); + await this.client.deleteCollection(this.collectionName); + } + + await this.ensureCollection(); + console.log("Migration complete. Re-index all data to populate new vector fields."); + } +} diff --git a/packages/search/src/services/score-merger.test.ts b/packages/search/src/services/score-merger.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..64bbd880bb1ff0362fc19a67b2f24adee03d0029 --- /dev/null +++ b/packages/search/src/services/score-merger.test.ts @@ -0,0 +1,448 @@ +import { describe, expect, it } from "vitest"; +import { type MergeStrategy, ScoreMerger } from "./score-merger"; + +describe("ScoreMerger", () => { + describe("constructor", () => { + it("should use rank-based strategy by default", () => { + const merger = new ScoreMerger(); + expect(merger.getStrategy()).toBe("rank-based"); + }); + + it("should accept custom strategy", () => { + const merger = new ScoreMerger({ strategy: "replace" }); + expect(merger.getStrategy()).toBe("replace"); + }); + + it("should use default weights (0.3 RRF, 0.7 reranker)", () => { + const merger = new ScoreMerger({ strategy: "weighted" }); + expect(merger.getRrfWeight()).toBe(0.3); + expect(merger.getRerankerWeight()).toBe(0.7); + }); + + it("should accept custom weights", () => { + const merger = new ScoreMerger({ + strategy: "weighted", + rrfWeight: 0.4, + rerankerWeight: 0.6, + }); + expect(merger.getRrfWeight()).toBe(0.4); + expect(merger.getRerankerWeight()).toBe(0.6); + }); + + it("should throw error if weighted strategy weights don't sum to 1.0", () => { + expect(() => { + new ScoreMerger({ + strategy: "weighted", + rrfWeight: 0.5, + rerankerWeight: 0.6, // Sum = 1.1 + }); + }).toThrow("Weights must sum to 1.0"); + }); + }); + + describe("merge - empty inputs", () => { + it("should return empty array for empty RRF results", () => { + const merger = new ScoreMerger(); + const result = merger.merge([], [{ id: "1", score: 0.9 }]); + expect(result).toEqual([]); + }); + + it("should return empty array for empty reranked results", () => { + const merger = new ScoreMerger(); + const result = merger.merge([{ id: "1", rrfScore: 0.5 }], []); + expect(result).toEqual([]); + }); + }); + + describe("replace strategy", () => { + const merger = new ScoreMerger({ strategy: "replace" }); + + it("should use reranker score as final score", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + { id: "doc3", rrfScore: 0.4 }, + ]; + + const rerankedResults = [ + { id: "doc3", score: 0.95 }, // Reranked to top + { id: "doc1", score: 0.85 }, + { id: "doc2", score: 0.75 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged).toHaveLength(3); + + // Check first result (doc3) + expect(merged[0].id).toBe("doc3"); + expect(merged[0].finalScore).toBe(0.95); // Reranker score + expect(merged[0].rrfScore).toBe(0.4); // Original RRF score + expect(merged[0].rerankerScore).toBe(0.95); + }); + + it("should calculate rank improvement correctly", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, // Rank 0 + { id: "doc2", rrfScore: 0.6 }, // Rank 1 + { id: "doc3", rrfScore: 0.4 }, // Rank 2 + ]; + + const rerankedResults = [ + { id: "doc3", score: 0.95 }, // New rank 0 (improvement: 2 - 0 = 2) + { id: "doc1", score: 0.85 }, // New rank 1 (improvement: 0 - 1 = -1) + { id: "doc2", score: 0.75 }, // New rank 2 (improvement: 1 - 2 = -1) + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged[0].rankImprovement).toBe(2); // doc3 moved up 2 positions + expect(merged[1].rankImprovement).toBe(-1); // doc1 moved down 1 position + expect(merged[2].rankImprovement).toBe(-1); // doc2 moved down 1 position + }); + + it("should preserve original and new ranks", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + ]; + + const rerankedResults = [ + { id: "doc2", score: 0.9 }, + { id: "doc1", score: 0.7 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged[0].originalRank).toBe(1); // doc2 was at position 1 + expect(merged[0].newRank).toBe(0); // doc2 is now at position 0 + expect(merged[1].originalRank).toBe(0); // doc1 was at position 0 + expect(merged[1].newRank).toBe(1); // doc1 is now at position 1 + }); + }); + + describe("weighted strategy", () => { + const merger = new ScoreMerger({ + strategy: "weighted", + rrfWeight: 0.4, + rerankerWeight: 0.6, + }); + + it("should combine RRF and reranker scores with weights", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 1.0 }, // Max RRF + { id: "doc2", rrfScore: 0.0 }, // Min RRF + ]; + + const rerankedResults = [ + { id: "doc1", score: 0.0 }, // Min reranker + { id: "doc2", score: 1.0 }, // Max reranker + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + // Normalized scores: + // doc1: RRF=1.0 (norm=1.0), Reranker=0.0 (norm=0.0) -> 0.4*1.0 + 0.6*0.0 = 0.4 + // doc2: RRF=0.0 (norm=0.0), Reranker=1.0 (norm=1.0) -> 0.4*0.0 + 0.6*1.0 = 0.6 + + expect(merged[0].finalScore).toBeCloseTo(0.6); // doc2 wins + expect(merged[1].finalScore).toBeCloseTo(0.4); // doc1 + }); + + it("should sort results by final score descending", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + { id: "doc3", rrfScore: 0.4 }, + ]; + + const rerankedResults = [ + { id: "doc1", score: 0.5 }, + { id: "doc2", score: 0.9 }, + { id: "doc3", score: 0.7 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + // Results should be sorted by finalScore descending + expect(merged[0].finalScore).toBeGreaterThan(merged[1].finalScore); + expect(merged[1].finalScore).toBeGreaterThan(merged[2].finalScore); + }); + + it("should update ranks after sorting", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + ]; + + const rerankedResults = [ + { id: "doc1", score: 0.5 }, + { id: "doc2", score: 0.9 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + // After weighted combination and sorting, ranks should be updated + expect(merged[0].newRank).toBe(0); + expect(merged[1].newRank).toBe(1); + }); + + it("should handle identical scores", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.5 }, + { id: "doc2", rrfScore: 0.5 }, + ]; + + const rerankedResults = [ + { id: "doc1", score: 0.5 }, + { id: "doc2", score: 0.5 }, + ]; + + // All values are the same, should normalize to 0.5 + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged).toHaveLength(2); + expect(merged[0].finalScore).toBeCloseTo(0.5); + expect(merged[1].finalScore).toBeCloseTo(0.5); + }); + }); + + describe("rank-based strategy (recommended)", () => { + const merger = new ScoreMerger({ strategy: "rank-based" }); + + it("should preserve reranker ordering", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + { id: "doc3", rrfScore: 0.4 }, + ]; + + const rerankedResults = [ + { id: "doc3", score: 0.95 }, + { id: "doc1", score: 0.85 }, + { id: "doc2", score: 0.75 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + // Order should match rerankedResults exactly + expect(merged[0].id).toBe("doc3"); + expect(merged[1].id).toBe("doc1"); + expect(merged[2].id).toBe("doc2"); + }); + + it("should use reranker score as final score", () => { + const rrfResults = [{ id: "doc1", rrfScore: 0.5 }]; + + const rerankedResults = [{ id: "doc1", score: 0.9 }]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged[0].finalScore).toBe(0.9); + expect(merged[0].rerankerScore).toBe(0.9); + }); + + it("should preserve both RRF and reranker scores", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + ]; + + const rerankedResults = [ + { id: "doc2", score: 0.95 }, + { id: "doc1", score: 0.85 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + // doc2 should have both scores preserved + expect(merged[0].id).toBe("doc2"); + expect(merged[0].rrfScore).toBe(0.6); // Original RRF + expect(merged[0].rerankerScore).toBe(0.95); // Reranker + expect(merged[0].finalScore).toBe(0.95); // Same as reranker + + // doc1 should have both scores preserved + expect(merged[1].id).toBe("doc1"); + expect(merged[1].rrfScore).toBe(0.8); + expect(merged[1].rerankerScore).toBe(0.85); + expect(merged[1].finalScore).toBe(0.85); + }); + + it("should calculate rank improvement", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.9 }, // Rank 0 + { id: "doc2", rrfScore: 0.5 }, // Rank 1 + { id: "doc3", rrfScore: 0.3 }, // Rank 2 + ]; + + const rerankedResults = [ + { id: "doc3", score: 0.95 }, // New rank 0 (improvement: 2) + { id: "doc2", score: 0.85 }, // New rank 1 (improvement: 0) + { id: "doc1", score: 0.75 }, // New rank 2 (improvement: -2) + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged[0].rankImprovement).toBe(2); // doc3: 2 - 0 = 2 + expect(merged[1].rankImprovement).toBe(0); // doc2: 1 - 1 = 0 + expect(merged[2].rankImprovement).toBe(-2); // doc1: 0 - 2 = -2 + }); + }); + + describe("strategy comparison", () => { + it("all strategies should handle same input set", () => { + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + ]; + + const rerankedResults = [ + { id: "doc2", score: 0.9 }, + { id: "doc1", score: 0.7 }, + ]; + + const strategies: MergeStrategy[] = ["replace", "weighted", "rank-based"]; + + strategies.forEach((strategy) => { + const merger = new ScoreMerger({ strategy }); + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged).toHaveLength(2); + expect(merged[0]).toHaveProperty("id"); + expect(merged[0]).toHaveProperty("rrfScore"); + expect(merged[0]).toHaveProperty("rerankerScore"); + expect(merged[0]).toHaveProperty("finalScore"); + expect(merged[0]).toHaveProperty("rankImprovement"); + }); + }); + }); + + describe("edge cases", () => { + it("should handle single document", () => { + const merger = new ScoreMerger(); + const rrfResults = [{ id: "doc1", rrfScore: 0.8 }]; + const rerankedResults = [{ id: "doc1", score: 0.9 }]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged).toHaveLength(1); + expect(merged[0].id).toBe("doc1"); + expect(merged[0].rrfScore).toBe(0.8); + expect(merged[0].rerankerScore).toBe(0.9); + }); + + it("should handle mismatched IDs gracefully", () => { + const merger = new ScoreMerger(); + const rrfResults = [ + { id: "doc1", rrfScore: 0.8 }, + { id: "doc2", rrfScore: 0.6 }, + ]; + + const rerankedResults = [ + { id: "doc3", score: 0.9 }, // doc3 not in RRF results + { id: "doc1", score: 0.7 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + // doc3 should have rrfScore of 0 (default) + const doc3 = merged.find((r) => r.id === "doc3"); + expect(doc3?.rrfScore).toBe(0); + expect(doc3?.rankImprovement).toBeUndefined(); + }); + + it("should handle numeric IDs", () => { + const merger = new ScoreMerger(); + const rrfResults = [ + { id: 1, rrfScore: 0.8 }, + { id: 2, rrfScore: 0.6 }, + ]; + + const rerankedResults = [ + { id: 2, score: 0.9 }, + { id: 1, score: 0.7 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged).toHaveLength(2); + expect(merged[0].id).toBe(2); + expect(merged[1].id).toBe(1); + }); + + it("should handle large score differences", () => { + const merger = new ScoreMerger({ strategy: "weighted" }); + const rrfResults = [ + { id: "doc1", rrfScore: 0.001 }, + { id: "doc2", rrfScore: 0.999 }, + ]; + + const rerankedResults = [ + { id: "doc1", score: 0.999 }, + { id: "doc2", score: 0.001 }, + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + // Should normalize and combine properly + expect(merged).toHaveLength(2); + expect(merged[0].finalScore).toBeGreaterThan(merged[1].finalScore); + }); + }); + + describe("rank improvement metrics", () => { + it("should calculate positive improvement for documents moving up", () => { + const merger = new ScoreMerger(); + const rrfResults = [ + { id: "doc1", rrfScore: 0.9 }, // Rank 0 + { id: "doc2", rrfScore: 0.5 }, // Rank 1 + ]; + + const rerankedResults = [ + { id: "doc2", score: 0.95 }, // New rank 0 + { id: "doc1", score: 0.85 }, // New rank 1 + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged[0].rankImprovement).toBe(1); // doc2 moved from 1 to 0 + expect(merged[0].rankImprovement).toBeGreaterThan(0); + }); + + it("should calculate negative improvement for documents moving down", () => { + const merger = new ScoreMerger(); + const rrfResults = [ + { id: "doc1", rrfScore: 0.9 }, // Rank 0 + { id: "doc2", rrfScore: 0.5 }, // Rank 1 + ]; + + const rerankedResults = [ + { id: "doc2", score: 0.95 }, // New rank 0 + { id: "doc1", score: 0.85 }, // New rank 1 + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged[1].rankImprovement).toBe(-1); // doc1 moved from 0 to 1 + expect(merged[1].rankImprovement).toBeLessThan(0); + }); + + it("should calculate zero improvement for unchanged positions", () => { + const merger = new ScoreMerger(); + const rrfResults = [ + { id: "doc1", rrfScore: 0.9 }, + { id: "doc2", rrfScore: 0.5 }, + ]; + + const rerankedResults = [ + { id: "doc1", score: 0.95 }, // Stays at rank 0 + { id: "doc2", score: 0.85 }, // Stays at rank 1 + ]; + + const merged = merger.merge(rrfResults, rerankedResults); + + expect(merged[0].rankImprovement).toBe(0); + expect(merged[1].rankImprovement).toBe(0); + }); + }); +}); diff --git a/packages/search/src/services/score-merger.ts b/packages/search/src/services/score-merger.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a3b909b19f76fd3ea9cc2b0dd25e4e3a69b368d --- /dev/null +++ b/packages/search/src/services/score-merger.ts @@ -0,0 +1,319 @@ +import { createLogger } from "@engram/logger"; + +/** + * Merged result containing both RRF and reranker scores with metadata. + */ +export interface MergedResult { + /** Document identifier */ + id: string | number; + + /** Original RRF/dense/sparse score before reranking */ + rrfScore: number; + + /** Cross-encoder relevance score from reranker (0-1) */ + rerankerScore: number; + + /** Final score used for sorting (determined by merge strategy) */ + finalScore: number; + + /** Position change after reranking (positive = moved up, negative = moved down) */ + rankImprovement?: number; + + /** Original position before reranking (0-indexed) */ + originalRank?: number; + + /** New position after reranking (0-indexed) */ + newRank?: number; +} + +/** + * Score merging strategy: + * - replace: Use reranker score as final score (simple replacement) + * - weighted: Combine RRF and reranker scores with configurable weights + * - rank-based: Use reranker ordering, preserve both scores (recommended) + */ +export type MergeStrategy = "replace" | "weighted" | "rank-based"; + +/** + * Configuration options for the ScoreMerger. + */ +export interface ScoreMergerOptions { + /** Merge strategy to use. Default: 'rank-based' */ + strategy?: MergeStrategy; + + /** Weight for RRF score in weighted strategy (0-1). Default: 0.3 */ + rrfWeight?: number; + + /** Weight for reranker score in weighted strategy (0-1). Default: 0.7 */ + rerankerWeight?: number; +} + +/** + * ScoreMerger combines RRF retrieval scores with reranker scores. + * + * This class implements three merging strategies: + * 1. Replace: Simple replacement with reranker score + * 2. Weighted: Configurable weighted combination + * 3. Rank-based: Reranker ordering with both scores preserved (recommended) + * + * The rank-based strategy is recommended for transparency, preserving both + * the original retrieval score and the reranker score for debugging/analysis. + */ +export class ScoreMerger { + private strategy: MergeStrategy; + private rrfWeight: number; + private rerankerWeight: number; + private logger = createLogger({ component: "ScoreMerger" }); + + constructor(options: ScoreMergerOptions = {}) { + this.strategy = options.strategy ?? "rank-based"; + this.rrfWeight = options.rrfWeight ?? 0.3; + this.rerankerWeight = options.rerankerWeight ?? 0.7; + + // Validate weights sum to 1.0 for weighted strategy + if (this.strategy === "weighted") { + const weightSum = this.rrfWeight + this.rerankerWeight; + if (Math.abs(weightSum - 1.0) > 0.001) { + throw new Error( + `Weights must sum to 1.0 for weighted strategy (got ${weightSum}). ` + + `rrfWeight=${this.rrfWeight}, rerankerWeight=${this.rerankerWeight}`, + ); + } + } + + this.logger.debug({ + msg: "ScoreMerger initialized", + strategy: this.strategy, + rrfWeight: this.rrfWeight, + rerankerWeight: this.rerankerWeight, + }); + } + + /** + * Merge RRF results with reranker scores. + * + * @param rrfResults - Original RRF-scored results (in retrieval order) + * @param rerankedResults - Results after reranking with new scores (in reranked order) + * @returns Merged results with both scores preserved, sorted by final score + */ + merge( + rrfResults: Array<{ id: string | number; rrfScore: number }>, + rerankedResults: Array<{ id: string | number; score: number }>, + ): MergedResult[] { + if (rrfResults.length === 0 || rerankedResults.length === 0) { + this.logger.warn({ + msg: "Empty input to merge", + rrfCount: rrfResults.length, + rerankedCount: rerankedResults.length, + }); + return []; + } + + // Route to appropriate strategy + let merged: MergedResult[]; + switch (this.strategy) { + case "replace": + merged = this.replaceStrategy(rrfResults, rerankedResults); + break; + case "weighted": + merged = this.weightedStrategy(rrfResults, rerankedResults); + break; + case "rank-based": + merged = this.rankBasedStrategy(rrfResults, rerankedResults); + break; + default: + throw new Error(`Unknown merge strategy: ${this.strategy}`); + } + + this.logger.debug({ + msg: "Score merge completed", + strategy: this.strategy, + inputCount: rrfResults.length, + outputCount: merged.length, + avgRankImprovement: this.calculateAvgRankImprovement(merged), + }); + + return merged; + } + + /** + * Replace strategy: Use reranker score as final score. + * Simple and direct - reranker score completely replaces RRF score. + */ + private replaceStrategy( + rrfResults: Array<{ id: string | number; rrfScore: number }>, + rerankedResults: Array<{ id: string | number; score: number }>, + ): MergedResult[] { + // Create lookup map for RRF scores and original ranks + const rrfMap = new Map( + rrfResults.map((r, index) => [String(r.id), { rrfScore: r.rrfScore, originalRank: index }]), + ); + + // Map reranked results, preserving order + return rerankedResults.map((r, newRank) => { + const rrfData = rrfMap.get(String(r.id)); + const originalRank = rrfData?.originalRank ?? -1; + const rrfScore = rrfData?.rrfScore ?? 0; + + return { + id: r.id, + rrfScore, + rerankerScore: r.score, + finalScore: r.score, // Use reranker score directly + originalRank, + newRank, + rankImprovement: originalRank >= 0 ? originalRank - newRank : undefined, + }; + }); + } + + /** + * Weighted strategy: Combine RRF and reranker scores with configurable weights. + * Allows tuning the balance between retrieval and reranker signals. + */ + private weightedStrategy( + rrfResults: Array<{ id: string | number; rrfScore: number }>, + rerankedResults: Array<{ id: string | number; score: number }>, + ): MergedResult[] { + // Create lookup map for RRF scores and original ranks + const rrfMap = new Map( + rrfResults.map((r, index) => [String(r.id), { rrfScore: r.rrfScore, originalRank: index }]), + ); + + // Normalize scores to 0-1 range before weighting + const rrfScores = rrfResults.map((r) => r.rrfScore); + const rerankerScores = rerankedResults.map((r) => r.score); + + const { min: rrfMin, max: rrfMax } = this.getMinMax(rrfScores); + const { min: rerankerMin, max: rerankerMax } = this.getMinMax(rerankerScores); + + // Map and combine scores + const merged = rerankedResults.map((r) => { + const rrfData = rrfMap.get(String(r.id)); + const originalRank = rrfData?.originalRank ?? -1; + const rrfScore = rrfData?.rrfScore ?? 0; + + // Normalize both scores to 0-1 + const normalizedRrf = this.normalize(rrfScore, rrfMin, rrfMax); + const normalizedReranker = this.normalize(r.score, rerankerMin, rerankerMax); + + // Weighted combination + const finalScore = this.rrfWeight * normalizedRrf + this.rerankerWeight * normalizedReranker; + + return { + id: r.id, + rrfScore, + rerankerScore: r.score, + finalScore, + originalRank: originalRank >= 0 ? originalRank : undefined, + newRank: undefined, // Will be set after sorting + rankImprovement: undefined, // Will be calculated after sorting + }; + }); + + // Sort by final score descending + merged.sort((a, b) => b.finalScore - a.finalScore); + + // Update ranks and calculate improvements + return merged.map((result, newRank) => ({ + ...result, + newRank, + rankImprovement: + result.originalRank !== undefined && result.originalRank >= 0 + ? result.originalRank - newRank + : undefined, + })); + } + + /** + * Rank-based strategy (RECOMMENDED): Use reranker ordering, preserve both scores. + * This strategy trusts the reranker's ordering completely while maintaining + * transparency by preserving both the original RRF score and reranker score. + */ + private rankBasedStrategy( + rrfResults: Array<{ id: string | number; rrfScore: number }>, + rerankedResults: Array<{ id: string | number; score: number }>, + ): MergedResult[] { + // Create lookup map for RRF scores and original ranks + const rrfMap = new Map( + rrfResults.map((r, index) => [String(r.id), { rrfScore: r.rrfScore, originalRank: index }]), + ); + + // Use reranker ordering directly + // Final score = reranker score (for consistency) + return rerankedResults.map((r, newRank) => { + const rrfData = rrfMap.get(String(r.id)); + const originalRank = rrfData?.originalRank ?? -1; + const rrfScore = rrfData?.rrfScore ?? 0; + + return { + id: r.id, + rrfScore, + rerankerScore: r.score, + finalScore: r.score, // Use reranker score for final ordering + originalRank, + newRank, + rankImprovement: originalRank >= 0 ? originalRank - newRank : undefined, + }; + }); + } + + /** + * Normalize a value to 0-1 range using min-max normalization. + */ + private normalize(value: number, min: number, max: number): number { + if (max === min) { + return 0.5; // All values are the same + } + return (value - min) / (max - min); + } + + /** + * Get min and max values from an array. + */ + private getMinMax(values: number[]): { min: number; max: number } { + if (values.length === 0) { + return { min: 0, max: 1 }; + } + return { + min: Math.min(...values), + max: Math.max(...values), + }; + } + + /** + * Calculate average rank improvement across all results. + */ + private calculateAvgRankImprovement(results: MergedResult[]): number | undefined { + const improvements = results + .map((r) => r.rankImprovement) + .filter((imp): imp is number => imp !== undefined); + + if (improvements.length === 0) { + return undefined; + } + + return improvements.reduce((sum, imp) => sum + imp, 0) / improvements.length; + } + + /** + * Get the current merge strategy. + */ + getStrategy(): MergeStrategy { + return this.strategy; + } + + /** + * Get the RRF weight (for weighted strategy). + */ + getRrfWeight(): number { + return this.rrfWeight; + } + + /** + * Get the reranker weight (for weighted strategy). + */ + getRerankerWeight(): number { + return this.rerankerWeight; + } +} diff --git a/packages/search/src/services/session-retriever.test.ts b/packages/search/src/services/session-retriever.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b90c4bd1fd302fdf987b612e699c6b27de14808 --- /dev/null +++ b/packages/search/src/services/session-retriever.test.ts @@ -0,0 +1,400 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { DEFAULT_SESSION_RETRIEVER_CONFIG, SessionAwareRetriever } from "./session-retriever"; + +/** + * Mock Qdrant client for testing + */ +function createMockQdrantClient() { + return { + search: vi.fn(), + query: vi.fn(), + }; +} + +/** + * Mock reranker for testing + */ +function createMockReranker() { + return { + rerank: vi.fn().mockImplementation((_, docs: string[], topK: number) => { + return Promise.resolve( + docs.slice(0, topK).map((_, idx) => ({ + originalIndex: idx, + score: 1 - idx * 0.1, + })), + ); + }), + }; +} + +/** + * Create mock session search results + */ +function createMockSessionResults(count: number = 3) { + return Array.from({ length: count }, (_, i) => ({ + id: `session-${i}`, + score: 0.9 - i * 0.1, + payload: { + session_id: `session-${i}`, + summary: `Summary for session ${i}`, + topics: [`topic-${i}`], + entities: [`entity-${i}`], + }, + })); +} + +/** + * Create mock turn search results + */ +function createMockTurnResults(sessionId: string, count: number = 2) { + return Array.from({ length: count }, (_, i) => ({ + id: `${sessionId}-turn-${i}`, + score: 0.85 - i * 0.05, + payload: { + content: `Turn ${i} content for ${sessionId}`, + node_id: `node-${i}`, + session_id: sessionId, + type: "thought" as const, + timestamp: Date.now() - i * 60000, + }, + })); +} + +describe("SessionAwareRetriever", () => { + let mockClient: ReturnType; + + beforeEach(() => { + mockClient = createMockQdrantClient(); + vi.clearAllMocks(); + }); + + describe("constructor", () => { + it("should use default config when none provided", () => { + const retriever = new SessionAwareRetriever(mockClient as never); + expect(retriever.getConfig()).toEqual(DEFAULT_SESSION_RETRIEVER_CONFIG); + }); + + it("should merge custom config with defaults", () => { + const retriever = new SessionAwareRetriever(mockClient as never, { + topSessions: 10, + turnsPerSession: 5, + }); + expect(retriever.getConfig().topSessions).toBe(10); + expect(retriever.getConfig().turnsPerSession).toBe(5); + expect(retriever.getConfig().finalTopK).toBe(DEFAULT_SESSION_RETRIEVER_CONFIG.finalTopK); + }); + }); + + describe("retrieve", () => { + it("should return empty array when no sessions found", async () => { + mockClient.search.mockResolvedValue([]); + + const retriever = new SessionAwareRetriever(mockClient as never); + + // Mock the embedder + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + const results = await retriever.retrieve("test query"); + + expect(results).toEqual([]); + expect(mockClient.search).toHaveBeenCalledTimes(1); + }); + + it("should perform two-stage retrieval", async () => { + const sessionResults = createMockSessionResults(2); + const turnResults0 = createMockTurnResults("session-0", 2); + const turnResults1 = createMockTurnResults("session-1", 2); + + // First call: session search, subsequent calls: turn searches + mockClient.search + .mockResolvedValueOnce(sessionResults) + .mockResolvedValueOnce(turnResults0) + .mockResolvedValueOnce(turnResults1); + + const retriever = new SessionAwareRetriever(mockClient as never, { + topSessions: 2, + turnsPerSession: 2, + parallelTurnRetrieval: false, // Sequential for predictable test + }); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + const results = await retriever.retrieve("test query"); + + // Should have 4 results (2 sessions × 2 turns) + expect(results).toHaveLength(4); + + // Verify session search was called first + expect(mockClient.search).toHaveBeenCalledWith( + "sessions", + expect.objectContaining({ + limit: 2, + with_payload: true, + }), + ); + + // Verify turn searches were called with session filters + expect(mockClient.search).toHaveBeenCalledWith( + "engram_memory", + expect.objectContaining({ + filter: { must: [{ key: "session_id", match: { value: "session-0" } }] }, + }), + ); + }); + + it("should include session context in results", async () => { + const sessionResults = createMockSessionResults(1); + const turnResults = createMockTurnResults("session-0", 1); + + mockClient.search.mockResolvedValueOnce(sessionResults).mockResolvedValueOnce(turnResults); + + const retriever = new SessionAwareRetriever(mockClient as never, { + topSessions: 1, + turnsPerSession: 1, + }); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + const results = await retriever.retrieve("test query"); + + expect(results[0].sessionId).toBe("session-0"); + expect(results[0].sessionSummary).toBe("Summary for session 0"); + expect(results[0].sessionScore).toBe(0.9); + }); + + it("should apply reranking when reranker provided and results exceed finalTopK", async () => { + const sessionResults = createMockSessionResults(3); + const turnResults = createMockTurnResults("session-0", 5); + + mockClient.search.mockResolvedValueOnce(sessionResults).mockResolvedValue(turnResults); + + const mockReranker = createMockReranker(); + const retriever = new SessionAwareRetriever( + mockClient as never, + { topSessions: 3, turnsPerSession: 5, finalTopK: 5 }, + mockReranker as never, + ); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + await retriever.retrieve("test query"); + + // Reranker should be called since we have 15 turns (3×5) > finalTopK (5) + expect(mockReranker.rerank).toHaveBeenCalledWith("test query", expect.any(Array), 5); + }); + + it("should not rerank when results are below finalTopK", async () => { + const sessionResults = createMockSessionResults(1); + const turnResults = createMockTurnResults("session-0", 2); + + mockClient.search.mockResolvedValueOnce(sessionResults).mockResolvedValueOnce(turnResults); + + const mockReranker = createMockReranker(); + const retriever = new SessionAwareRetriever( + mockClient as never, + { topSessions: 1, turnsPerSession: 2, finalTopK: 10 }, + mockReranker as never, + ); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + await retriever.retrieve("test query"); + + // Reranker should NOT be called since we only have 2 turns < finalTopK (10) + expect(mockReranker.rerank).not.toHaveBeenCalled(); + }); + + it("should handle session retrieval errors gracefully", async () => { + mockClient.search.mockRejectedValueOnce(new Error("Connection failed")); + + const retriever = new SessionAwareRetriever(mockClient as never); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + const results = await retriever.retrieve("test query"); + + expect(results).toEqual([]); + }); + + it("should handle turn retrieval errors gracefully", async () => { + const sessionResults = createMockSessionResults(2); + + mockClient.search + .mockResolvedValueOnce(sessionResults) + .mockRejectedValueOnce(new Error("Turn query failed")) + .mockResolvedValueOnce(createMockTurnResults("session-1", 2)); + + const retriever = new SessionAwareRetriever(mockClient as never, { + parallelTurnRetrieval: false, + }); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + const results = await retriever.retrieve("test query"); + + // Should still get results from session-1 + expect(results.length).toBeGreaterThan(0); + expect(results.every((r) => r.sessionId === "session-1")).toBe(true); + }); + + it("should perform parallel turn retrieval when enabled", async () => { + const sessionResults = createMockSessionResults(3); + + // All turn searches resolve immediately + mockClient.search + .mockResolvedValueOnce(sessionResults) + .mockResolvedValue(createMockTurnResults("session-x", 2)); + + const retriever = new SessionAwareRetriever(mockClient as never, { + topSessions: 3, + turnsPerSession: 2, + parallelTurnRetrieval: true, + }); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + await retriever.retrieve("test query"); + + // 1 session search + 3 parallel turn searches = 4 total calls + expect(mockClient.search).toHaveBeenCalledTimes(4); + }); + }); + + describe("retrieveSessions", () => { + it("should apply score threshold filter", async () => { + mockClient.search.mockResolvedValue([]); + + const retriever = new SessionAwareRetriever(mockClient as never, { + sessionScoreThreshold: 0.5, + }); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + await retriever.retrieve("test query"); + + expect(mockClient.search).toHaveBeenCalledWith( + "sessions", + expect.objectContaining({ + score_threshold: 0.5, + }), + ); + }); + + it("should use configured vector name", async () => { + mockClient.search.mockResolvedValue([]); + + const retriever = new SessionAwareRetriever(mockClient as never, { + sessionVectorName: "custom_vector", + }); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + await retriever.retrieve("test query"); + + expect(mockClient.search).toHaveBeenCalledWith( + "sessions", + expect.objectContaining({ + vector: expect.objectContaining({ + name: "custom_vector", + }), + }), + ); + }); + }); + + describe("configuration", () => { + it("should update config at runtime", () => { + const retriever = new SessionAwareRetriever(mockClient as never, { + topSessions: 5, + }); + expect(retriever.getConfig().topSessions).toBe(5); + + retriever.updateConfig({ topSessions: 10 }); + expect(retriever.getConfig().topSessions).toBe(10); + }); + + it("should preserve other config when updating", () => { + const retriever = new SessionAwareRetriever(mockClient as never, { + topSessions: 5, + turnsPerSession: 3, + }); + + retriever.updateConfig({ topSessions: 10 }); + + expect(retriever.getConfig().topSessions).toBe(10); + expect(retriever.getConfig().turnsPerSession).toBe(3); + }); + }); + + describe("reranking", () => { + it("should fall back to sorted results on reranker error", async () => { + const sessionResults = createMockSessionResults(2); + const turnResults = createMockTurnResults("session-0", 5); + + mockClient.search.mockResolvedValueOnce(sessionResults).mockResolvedValue(turnResults); + + const mockReranker = { + rerank: vi.fn().mockRejectedValue(new Error("Reranker failed")), + }; + + const retriever = new SessionAwareRetriever( + mockClient as never, + { topSessions: 2, turnsPerSession: 5, finalTopK: 3 }, + mockReranker as never, + ); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + const results = await retriever.retrieve("test query"); + + // Should fall back to top 3 by score + expect(results).toHaveLength(3); + }); + + it("should preserve session context after reranking", async () => { + const sessionResults = createMockSessionResults(1); + const turnResults = createMockTurnResults("session-0", 3); + + mockClient.search.mockResolvedValueOnce(sessionResults).mockResolvedValueOnce(turnResults); + + const mockReranker = createMockReranker(); + const retriever = new SessionAwareRetriever( + mockClient as never, + { topSessions: 1, turnsPerSession: 3, finalTopK: 2 }, + mockReranker as never, + ); + + vi.spyOn(retriever as never, "embedder", "get").mockReturnValue({ + embedQuery: vi.fn().mockResolvedValue(new Array(384).fill(0.1)), + } as never); + + const results = await retriever.retrieve("test query"); + + // All results should still have session context + expect(results.every((r) => r.sessionId === "session-0")).toBe(true); + expect(results.every((r) => r.sessionSummary !== undefined)).toBe(true); + }); + }); +}); diff --git a/packages/search/src/services/session-retriever.ts b/packages/search/src/services/session-retriever.ts new file mode 100644 index 0000000000000000000000000000000000000000..824b567c8d1c4009d1aaa8accae576d2b481f764 --- /dev/null +++ b/packages/search/src/services/session-retriever.ts @@ -0,0 +1,382 @@ +/** + * Session-Aware Retriever for hierarchical two-stage retrieval. + * + * Implements a two-stage retrieval approach: + * 1. Stage 1: Retrieve top-S sessions based on session summaries + * 2. Stage 2: Retrieve top-T turns within each matched session + * 3. Optional reranking of combined results + * + * This approach improves Multi-Session Reasoning (MR) by ensuring + * related turns from the same session are retrieved together. + * + * Based on research from: + * - LiCoMemory: Hierarchical Retrieval + * - SGMem: Sentence Graph Memory + * + * @see https://arxiv.org/html/2511.01448 (LiCoMemory) + * @see https://arxiv.org/html/2509.21212 (SGMem) + */ + +import { createLogger } from "@engram/logger"; +import type { QdrantClient } from "@qdrant/js-client-rest"; +import type { SearchResult, SearchResultPayload } from "../models/schema"; +import type { Reranker } from "./reranker"; +import { TextEmbedder } from "./text-embedder"; + +/** + * Configuration for SessionAwareRetriever + */ +export interface SessionRetrieverConfig { + /** Number of sessions to retrieve in stage 1 (default: 5) */ + topSessions: number; + /** Number of turns per session in stage 2 (default: 3) */ + turnsPerSession: number; + /** Final top-K after reranking (default: 10) */ + finalTopK: number; + /** Collection name for session summaries (default: "sessions") */ + sessionCollection: string; + /** Collection name for turns (default: "engram_memory") */ + turnCollection: string; + /** Vector field name for session embeddings (default: "text_dense") */ + sessionVectorName: string; + /** Vector field name for turn embeddings (default: "text_dense") */ + turnVectorName: string; + /** Minimum score threshold for sessions (default: 0.3) */ + sessionScoreThreshold: number; + /** Enable parallel turn retrieval (default: true) */ + parallelTurnRetrieval: boolean; +} + +/** + * Default configuration for session-aware retrieval + */ +export const DEFAULT_SESSION_RETRIEVER_CONFIG: SessionRetrieverConfig = { + topSessions: 5, + turnsPerSession: 3, + finalTopK: 10, + sessionCollection: "sessions", + turnCollection: "engram_memory", + sessionVectorName: "text_dense", + turnVectorName: "text_dense", + sessionScoreThreshold: 0.3, + parallelTurnRetrieval: true, +}; + +/** + * Result from stage 1 session retrieval + */ +export interface SessionResult { + /** Session ID */ + sessionId: string; + /** Session summary text */ + summary: string; + /** Similarity score */ + score: number; + /** Topics associated with session */ + topics?: string[]; + /** Entities mentioned in session */ + entities?: string[]; +} + +/** + * Extended search result with session context + */ +export interface SessionAwareSearchResult extends SearchResult { + /** Session ID this result belongs to */ + sessionId: string; + /** Session summary for context */ + sessionSummary?: string; + /** Session-level score from stage 1 */ + sessionScore?: number; +} + +/** + * SessionAwareRetriever implements two-stage hierarchical retrieval. + * + * Stage 1: Session Retrieval + * - Query against session summary embeddings + * - Returns top-S most relevant sessions + * + * Stage 2: Turn Retrieval + * - For each session from stage 1, query turns filtered by session_id + * - Returns top-T turns per session + * + * Final: Reranking + * - Combines all turns (S × T) + * - Optionally reranks to final top-K + * + * @example + * ```typescript + * const retriever = new SessionAwareRetriever(qdrantClient, { + * topSessions: 5, + * turnsPerSession: 3, + * finalTopK: 10, + * }); + * + * const results = await retriever.retrieve("What did we discuss about Docker?"); + * // Returns up to 10 turns from the 5 most relevant sessions + * ``` + */ +export class SessionAwareRetriever { + private client: QdrantClient; + private embedder: TextEmbedder; + private config: SessionRetrieverConfig; + private reranker?: Reranker; + private logger = createLogger({ component: "SessionAwareRetriever" }); + + constructor( + client: QdrantClient, + config: Partial = {}, + reranker?: Reranker, + ) { + this.client = client; + this.config = { ...DEFAULT_SESSION_RETRIEVER_CONFIG, ...config }; + this.reranker = reranker; + this.embedder = new TextEmbedder(); + } + + /** + * Perform two-stage session-aware retrieval. + * + * @param query - The search query + * @returns Array of search results with session context + */ + async retrieve(query: string): Promise { + const startTime = Date.now(); + + // Generate query embedding + const queryEmbedding = await this.embedder.embedQuery(query); + + // Stage 1: Retrieve relevant sessions + const sessions = await this.retrieveSessions(queryEmbedding); + + if (sessions.length === 0) { + this.logger.info({ + msg: "No sessions found in stage 1", + query: query.slice(0, 100), + latencyMs: Date.now() - startTime, + }); + return []; + } + + this.logger.debug({ + msg: "Stage 1 complete - sessions retrieved", + sessionCount: sessions.length, + topSessionScore: sessions[0]?.score, + }); + + // Stage 2: Retrieve turns within each session + const allTurns = await this.retrieveTurnsFromSessions(queryEmbedding, sessions); + + if (allTurns.length === 0) { + this.logger.info({ + msg: "No turns found in stage 2", + sessionCount: sessions.length, + latencyMs: Date.now() - startTime, + }); + return []; + } + + this.logger.debug({ + msg: "Stage 2 complete - turns retrieved", + turnCount: allTurns.length, + sessionsWithTurns: new Set(allTurns.map((t) => t.sessionId)).size, + }); + + // Stage 3: Rerank if enabled and needed + let finalResults = allTurns; + if (this.reranker && allTurns.length > this.config.finalTopK) { + finalResults = await this.rerankResults(query, allTurns); + } else { + // Sort by score and limit + finalResults = allTurns.sort((a, b) => b.score - a.score).slice(0, this.config.finalTopK); + } + + const latencyMs = Date.now() - startTime; + this.logger.info({ + msg: "Session-aware retrieval complete", + query: query.slice(0, 50), + sessionsFound: sessions.length, + turnsRetrieved: allTurns.length, + finalResults: finalResults.length, + latencyMs, + }); + + return finalResults; + } + + /** + * Stage 1: Retrieve relevant sessions based on summary embeddings. + * + * @param queryEmbedding - Query embedding vector + * @returns Array of matched sessions + */ + private async retrieveSessions(queryEmbedding: number[]): Promise { + try { + const results = await this.client.search(this.config.sessionCollection, { + vector: { + name: this.config.sessionVectorName, + vector: queryEmbedding, + }, + limit: this.config.topSessions, + with_payload: true, + score_threshold: this.config.sessionScoreThreshold, + }); + + return results.map((r) => { + const payload = r.payload as Record; + return { + sessionId: payload.session_id as string, + summary: payload.summary as string, + score: r.score, + topics: payload.topics as string[] | undefined, + entities: payload.entities as string[] | undefined, + }; + }); + } catch (error) { + this.logger.error({ + msg: "Session retrieval failed", + error: error instanceof Error ? error.message : String(error), + }); + return []; + } + } + + /** + * Stage 2: Retrieve turns within matched sessions. + * + * @param queryEmbedding - Query embedding vector + * @param sessions - Sessions from stage 1 + * @returns Array of turns with session context + */ + private async retrieveTurnsFromSessions( + queryEmbedding: number[], + sessions: SessionResult[], + ): Promise { + if (this.config.parallelTurnRetrieval) { + // Parallel retrieval for all sessions + const turnPromises = sessions.map((session) => + this.retrieveTurnsInSession(queryEmbedding, session), + ); + const results = await Promise.all(turnPromises); + return results.flat(); + } + + // Sequential retrieval + const allTurns: SessionAwareSearchResult[] = []; + for (const session of sessions) { + const turns = await this.retrieveTurnsInSession(queryEmbedding, session); + allTurns.push(...turns); + } + return allTurns; + } + + /** + * Retrieve turns within a single session. + * + * @param queryEmbedding - Query embedding vector + * @param session - Session to search within + * @returns Array of turns from this session + */ + private async retrieveTurnsInSession( + queryEmbedding: number[], + session: SessionResult, + ): Promise { + try { + const results = await this.client.search(this.config.turnCollection, { + vector: { + name: this.config.turnVectorName, + vector: queryEmbedding, + }, + limit: this.config.turnsPerSession, + filter: { + must: [{ key: "session_id", match: { value: session.sessionId } }], + }, + with_payload: true, + }); + + return results.map((r) => { + const payload = r.payload as unknown as SearchResultPayload; + return { + id: r.id, + score: r.score, + payload, + sessionId: session.sessionId, + sessionSummary: session.summary, + sessionScore: session.score, + }; + }); + } catch (error) { + this.logger.warn({ + msg: "Turn retrieval failed for session", + sessionId: session.sessionId, + error: error instanceof Error ? error.message : String(error), + }); + return []; + } + } + + /** + * Rerank combined results from all sessions. + * + * @param query - Original query + * @param turns - All turns from stage 2 + * @returns Reranked and limited results + */ + private async rerankResults( + query: string, + turns: SessionAwareSearchResult[], + ): Promise { + if (!this.reranker) { + return turns.slice(0, this.config.finalTopK); + } + + try { + // Extract content for reranking + const documents = turns.map((t) => t.payload?.content ?? ""); + + // Rerank + const reranked = await this.reranker.rerank(query, documents, this.config.finalTopK); + + // Map back to original results + return reranked.map((r) => { + const original = turns[r.originalIndex]; + return { + ...original, + score: r.score, + rrfScore: original.score, + rerankerScore: r.score, + }; + }); + } catch (error) { + this.logger.error({ + msg: "Reranking failed - returning sorted results", + error: error instanceof Error ? error.message : String(error), + }); + + // Fall back to score-sorted results + return turns.sort((a, b) => b.score - a.score).slice(0, this.config.finalTopK); + } + } + + /** + * Get current configuration. + */ + getConfig(): Readonly { + return this.config; + } + + /** + * Update configuration at runtime. + */ + updateConfig(config: Partial): void { + this.config = { ...this.config, ...config }; + } + + /** + * Preload the text embedder for faster first retrieval. + */ + async preload(): Promise { + await this.embedder.preload(); + } +} diff --git a/packages/search/src/services/session-summarizer.test.ts b/packages/search/src/services/session-summarizer.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..960eb1f56a4cde0c90d71f22022a6578d28df002 --- /dev/null +++ b/packages/search/src/services/session-summarizer.test.ts @@ -0,0 +1,402 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + DEFAULT_SESSION_SUMMARIZER_CONFIG, + type LLMProvider, + type LLMResponse, + SessionSummarizer, + type Turn, +} from "./session-summarizer"; + +/** + * Mock LLM provider for testing + */ +class MockLLMProvider implements LLMProvider { + private summaryResponse = "This is a test summary of the conversation."; + + setSummaryResponse(response: string): void { + this.summaryResponse = response; + } + + async complete(): Promise { + return { + text: this.summaryResponse, + usage: { inputTokens: 100, outputTokens: 50 }, + }; + } +} + +/** + * Create sample turns for testing + */ +function createSampleTurns(count: number = 3): Turn[] { + const baseTime = new Date("2024-01-15T10:00:00Z"); + return Array.from({ length: count }, (_, i) => ({ + id: `turn-${i}`, + sessionId: "session-123", + role: (i % 2 === 0 ? "user" : "assistant") as Turn["role"], + content: i % 2 === 0 ? `User message ${i + 1}` : `Assistant response ${i + 1}`, + timestamp: new Date(baseTime.getTime() + i * 60000), + })); +} + +describe("SessionSummarizer", () => { + let mockLLM: MockLLMProvider; + + beforeEach(() => { + mockLLM = new MockLLMProvider(); + }); + + describe("constructor", () => { + it("should use default config when none provided", () => { + const summarizer = new SessionSummarizer(mockLLM); + expect(summarizer.getConfig()).toEqual(DEFAULT_SESSION_SUMMARIZER_CONFIG); + }); + + it("should merge custom config with defaults", () => { + const summarizer = new SessionSummarizer(mockLLM, { maxTopics: 10 }); + expect(summarizer.getConfig().maxTopics).toBe(10); + expect(summarizer.getConfig().nerModel).toBe(DEFAULT_SESSION_SUMMARIZER_CONFIG.nerModel); + }); + }); + + describe("summarize", () => { + it("should throw error for empty turns array", async () => { + const summarizer = new SessionSummarizer(mockLLM); + await expect(summarizer.summarize([])).rejects.toThrow("Cannot summarize empty session"); + }); + + it("should generate summary with correct session metadata", async () => { + const summarizer = new SessionSummarizer(mockLLM); + const turns = createSampleTurns(3); + + // Mock the internal methods to avoid loading models + const mockSummary = "Test summary of conversation."; + const mockTopics = ["topic1", "topic2"]; + const mockEntities = ["Entity1"]; + const mockEmbedding = new Array(384).fill(0.1); + + vi.spyOn(summarizer as never, "generateSummary").mockResolvedValue(mockSummary as never); + vi.spyOn(summarizer, "extractTopics").mockResolvedValue(mockTopics); + vi.spyOn(summarizer, "extractEntities").mockResolvedValue(mockEntities); + vi.spyOn(summarizer as never, "embedder", "get").mockReturnValue({ + embed: vi.fn().mockResolvedValue(mockEmbedding), + } as never); + + const result = await summarizer.summarize(turns); + + expect(result.sessionId).toBe("session-123"); + expect(result.summary).toBe(mockSummary); + expect(result.topics).toEqual(mockTopics); + expect(result.entities).toEqual(mockEntities); + expect(result.turnCount).toBe(3); + expect(result.startTime).toEqual(turns[0].timestamp); + expect(result.endTime).toEqual(turns[2].timestamp); + expect(result.embedding).toHaveLength(384); + }); + + it("should use first turn sessionId for result", async () => { + const summarizer = new SessionSummarizer(mockLLM); + const turns = createSampleTurns(2); + turns[0].sessionId = "session-A"; + turns[1].sessionId = "session-B"; // Different session (edge case) + + vi.spyOn(summarizer as never, "generateSummary").mockResolvedValue("Summary" as never); + vi.spyOn(summarizer, "extractTopics").mockResolvedValue([]); + vi.spyOn(summarizer, "extractEntities").mockResolvedValue([]); + vi.spyOn(summarizer as never, "embedder", "get").mockReturnValue({ + embed: vi.fn().mockResolvedValue(new Array(384).fill(0)), + } as never); + + const result = await summarizer.summarize(turns); + + expect(result.sessionId).toBe("session-A"); + }); + }); + + describe("extractCandidateKeywords", () => { + it("should extract unique keywords from text", () => { + const summarizer = new SessionSummarizer(mockLLM); + const extractCandidates = (summarizer as never).extractCandidateKeywords.bind(summarizer) as ( + text: string, + ) => string[]; + + const text = "The TypeScript project uses Docker and Kubernetes for deployment"; + const keywords = extractCandidates(text); + + expect(keywords).toContain("typescript"); + expect(keywords).toContain("docker"); + expect(keywords).toContain("kubernetes"); + expect(keywords).toContain("deployment"); + }); + + it("should filter common stopwords", () => { + const summarizer = new SessionSummarizer(mockLLM); + const extractCandidates = (summarizer as never).extractCandidateKeywords.bind(summarizer) as ( + text: string, + ) => string[]; + + const text = "The user is working on a project"; + const keywords = extractCandidates(text); + + expect(keywords).not.toContain("the"); + expect(keywords).not.toContain("is"); + expect(keywords).not.toContain("on"); + expect(keywords).not.toContain("a"); + expect(keywords).not.toContain("user"); // "user" is in stopwords + }); + + it("should generate bigrams", () => { + const summarizer = new SessionSummarizer(mockLLM); + const extractCandidates = (summarizer as never).extractCandidateKeywords.bind(summarizer) as ( + text: string, + ) => string[]; + + const text = "machine learning models neural networks"; + const keywords = extractCandidates(text); + + // Should have bigrams + expect(keywords.some((k) => k.includes(" "))).toBe(true); + }); + + it("should filter short words", () => { + const summarizer = new SessionSummarizer(mockLLM); + const extractCandidates = (summarizer as never).extractCandidateKeywords.bind(summarizer) as ( + text: string, + ) => string[]; + + const text = "AI ML API SDK CLI"; + const keywords = extractCandidates(text); + + // Should filter 2-char or less + expect(keywords).not.toContain("ai"); + expect(keywords).not.toContain("ml"); + expect(keywords).toContain("api"); + expect(keywords).toContain("sdk"); + expect(keywords).toContain("cli"); + }); + }); + + describe("cosineSimilarity", () => { + it("should calculate correct similarity for identical vectors", () => { + const summarizer = new SessionSummarizer(mockLLM); + const cosine = (summarizer as never).cosineSimilarity.bind(summarizer) as ( + a: number[], + b: number[], + ) => number; + + const vec = [0.5, 0.5, 0.5]; + const similarity = cosine(vec, vec); + + expect(similarity).toBeCloseTo(1.0, 5); + }); + + it("should calculate correct similarity for orthogonal vectors", () => { + const summarizer = new SessionSummarizer(mockLLM); + const cosine = (summarizer as never).cosineSimilarity.bind(summarizer) as ( + a: number[], + b: number[], + ) => number; + + const vec1 = [1, 0, 0]; + const vec2 = [0, 1, 0]; + const similarity = cosine(vec1, vec2); + + expect(similarity).toBeCloseTo(0.0, 5); + }); + + it("should calculate correct similarity for opposite vectors", () => { + const summarizer = new SessionSummarizer(mockLLM); + const cosine = (summarizer as never).cosineSimilarity.bind(summarizer) as ( + a: number[], + b: number[], + ) => number; + + const vec1 = [1, 0, 0]; + const vec2 = [-1, 0, 0]; + const similarity = cosine(vec1, vec2); + + expect(similarity).toBeCloseTo(-1.0, 5); + }); + + it("should throw error for different length vectors", () => { + const summarizer = new SessionSummarizer(mockLLM); + const cosine = (summarizer as never).cosineSimilarity.bind(summarizer) as ( + a: number[], + b: number[], + ) => number; + + const vec1 = [1, 0]; + const vec2 = [1, 0, 0]; + + expect(() => cosine(vec1, vec2)).toThrow("Vectors must have same length"); + }); + + it("should handle zero vectors", () => { + const summarizer = new SessionSummarizer(mockLLM); + const cosine = (summarizer as never).cosineSimilarity.bind(summarizer) as ( + a: number[], + b: number[], + ) => number; + + const vec1 = [0, 0, 0]; + const vec2 = [1, 0, 0]; + const similarity = cosine(vec1, vec2); + + expect(similarity).toBe(0); + }); + }); + + describe("cleanEntityWord", () => { + it("should remove BERT subword prefix", () => { + const summarizer = new SessionSummarizer(mockLLM); + const clean = (summarizer as never).cleanEntityWord.bind(summarizer) as ( + word: string, + ) => string; + + expect(clean("##ing")).toBe("ing"); + expect(clean("##tion")).toBe("tion"); + }); + + it("should leave normal words unchanged", () => { + const summarizer = new SessionSummarizer(mockLLM); + const clean = (summarizer as never).cleanEntityWord.bind(summarizer) as ( + word: string, + ) => string; + + expect(clean("Docker")).toBe("Docker"); + expect(clean("TypeScript")).toBe("TypeScript"); + }); + }); + + describe("configuration", () => { + it("should update config at runtime", () => { + const summarizer = new SessionSummarizer(mockLLM, { maxTopics: 5 }); + expect(summarizer.getConfig().maxTopics).toBe(5); + + summarizer.updateConfig({ maxTopics: 10 }); + expect(summarizer.getConfig().maxTopics).toBe(10); + }); + + it("should preserve other config when updating", () => { + const summarizer = new SessionSummarizer(mockLLM, { + maxTopics: 5, + minEntityScore: 0.5, + }); + + summarizer.updateConfig({ maxTopics: 10 }); + + expect(summarizer.getConfig().maxTopics).toBe(10); + expect(summarizer.getConfig().minEntityScore).toBe(0.5); + }); + }); + + describe("generateSummary", () => { + it("should use LLM to generate summary", async () => { + mockLLM.setSummaryResponse(" Generated summary with whitespace "); + const summarizer = new SessionSummarizer(mockLLM); + + const generateSummary = (summarizer as never).generateSummary.bind(summarizer) as ( + context: string, + ) => Promise; + + const summary = await generateSummary("user: Hello\nassistant: Hi there!"); + + expect(summary).toBe("Generated summary with whitespace"); // Should be trimmed + }); + }); + + describe("extractEntities (unit)", () => { + it("should deduplicate entities case-insensitively", async () => { + const summarizer = new SessionSummarizer(mockLLM); + + // Mock NER pipeline + const mockNerResults = [ + { word: "Docker", entity: "B-ORG", score: 0.95, start: 0, end: 6 }, + { word: "docker", entity: "B-ORG", score: 0.9, start: 10, end: 16 }, + { word: "DOCKER", entity: "B-ORG", score: 0.85, start: 20, end: 26 }, + ]; + + vi.spyOn(summarizer as never, "loadNERPipeline").mockResolvedValue((() => + Promise.resolve(mockNerResults)) as never); + + const entities = await summarizer.extractEntities("Docker docker DOCKER"); + + // Should only have one entry (first occurrence) + expect(entities).toHaveLength(1); + expect(entities[0]).toBe("Docker"); + }); + + it("should filter entities below score threshold", async () => { + const summarizer = new SessionSummarizer(mockLLM, { minEntityScore: 0.8 }); + + const mockNerResults = [ + { word: "HighScore", entity: "B-ORG", score: 0.95, start: 0, end: 9 }, + { word: "LowScore", entity: "B-ORG", score: 0.5, start: 10, end: 18 }, + ]; + + vi.spyOn(summarizer as never, "loadNERPipeline").mockResolvedValue((() => + Promise.resolve(mockNerResults)) as never); + + const entities = await summarizer.extractEntities("HighScore LowScore"); + + expect(entities).toContain("HighScore"); + expect(entities).not.toContain("LowScore"); + }); + + it("should filter single-character entities", async () => { + const summarizer = new SessionSummarizer(mockLLM); + + const mockNerResults = [ + { word: "A", entity: "B-MISC", score: 0.95, start: 0, end: 1 }, + { word: "AWS", entity: "B-ORG", score: 0.95, start: 2, end: 5 }, + ]; + + vi.spyOn(summarizer as never, "loadNERPipeline").mockResolvedValue((() => + Promise.resolve(mockNerResults)) as never); + + const entities = await summarizer.extractEntities("A AWS"); + + expect(entities).not.toContain("A"); + expect(entities).toContain("AWS"); + }); + }); + + describe("extractTopics (unit)", () => { + it("should return empty array for text with only stopwords", async () => { + const summarizer = new SessionSummarizer(mockLLM); + + // Mock keyword pipeline + vi.spyOn(summarizer as never, "loadKeywordPipeline").mockResolvedValue(((texts: string[]) => + Promise.resolve(texts.map(() => ({ data: new Float32Array(384).fill(0.1) })))) as never); + + // Override extractCandidateKeywords to return empty + vi.spyOn(summarizer as never, "extractCandidateKeywords").mockReturnValue([] as never); + + const topics = await summarizer.extractTopics("the is a an on"); + + expect(topics).toEqual([]); + }); + + it("should limit topics to maxTopics config", async () => { + const summarizer = new SessionSummarizer(mockLLM, { maxTopics: 3 }); + + // Mock keyword extraction + const candidates = ["topic1", "topic2", "topic3", "topic4", "topic5"]; + vi.spyOn(summarizer as never, "extractCandidateKeywords").mockReturnValue( + candidates as never, + ); + + // Mock embeddings with varying similarities + vi.spyOn(summarizer as never, "loadKeywordPipeline").mockResolvedValue(((texts: string[]) => + Promise.resolve( + texts.map((_, i) => ({ + data: new Float32Array(384).fill(1 - i * 0.1), + })), + )) as never); + + const topics = await summarizer.extractTopics("some text"); + + expect(topics.length).toBeLessThanOrEqual(3); + }); + }); +}); diff --git a/packages/search/src/services/session-summarizer.ts b/packages/search/src/services/session-summarizer.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e19bea26de6c6e1ec2e247a4c24de5614c50ee3 --- /dev/null +++ b/packages/search/src/services/session-summarizer.ts @@ -0,0 +1,538 @@ +/** + * Session Summarizer for hierarchical retrieval. + * + * Generates summaries for conversation sessions to enable two-stage retrieval: + * 1. Stage 1: Retrieve relevant sessions based on summaries + * 2. Stage 2: Retrieve turns within matched sessions + * + * Based on SGMem and LiCoMemory research. + * @see https://arxiv.org/html/2509.21212 (SGMem) + * @see https://arxiv.org/html/2511.01448 (LiCoMemory) + */ + +import { pipeline } from "@huggingface/transformers"; +import { TextEmbedder } from "./text-embedder"; + +/** + * A turn in a conversation session + */ +export interface Turn { + /** Unique turn ID */ + id: string; + /** Session this turn belongs to */ + sessionId: string; + /** Role of the speaker (user, assistant, system) */ + role: "user" | "assistant" | "system"; + /** Content of the turn */ + content: string; + /** Timestamp of the turn */ + timestamp: Date; +} + +/** + * Summary of a conversation session for hierarchical retrieval + */ +export interface SessionSummary { + /** Session ID */ + sessionId: string; + /** Generated summary of session content */ + summary: string; + /** Key topics discussed (extracted via keyword extraction) */ + topics: string[]; + /** Named entities mentioned (extracted via NER) */ + entities: string[]; + /** Start time of session */ + startTime: Date; + /** End time of session */ + endTime: Date; + /** Number of turns in session */ + turnCount: number; + /** Embedding of summary for retrieval */ + embedding: number[]; +} + +/** + * LLM provider interface for summarization + */ +export interface LLMProvider { + complete(prompt: string, options?: LLMOptions): Promise; +} + +export interface LLMOptions { + temperature?: number; + maxTokens?: number; + stopSequences?: string[]; +} + +export interface LLMResponse { + text: string; + usage?: { + inputTokens: number; + outputTokens: number; + }; +} + +/** + * Configuration for SessionSummarizer + */ +export interface SessionSummarizerConfig { + /** Maximum number of keywords/topics to extract (default: 5) */ + maxTopics: number; + /** NER model for entity extraction (default: Xenova/bert-base-NER) */ + nerModel: string; + /** Keyword extraction model (default: Xenova/all-MiniLM-L6-v2) */ + keywordModel: string; + /** Minimum entity score to include (default: 0.7) */ + minEntityScore: number; +} + +/** + * Default configuration for session summarization + */ +export const DEFAULT_SESSION_SUMMARIZER_CONFIG: SessionSummarizerConfig = { + maxTopics: 5, + nerModel: "Xenova/bert-base-NER", + keywordModel: "Xenova/all-MiniLM-L6-v2", + minEntityScore: 0.7, +}; + +/** + * NER result from HuggingFace pipeline + */ +interface NEREntity { + word: string; + entity: string; + score: number; + start: number; + end: number; +} + +/** + * NER pipeline function type + */ +type NERPipeline = (text: string) => Promise; + +/** + * Feature extraction pipeline for keyword extraction + */ +type FeatureExtractionPipeline = ( + texts: string[], + options: { pooling: string; normalize: boolean }, +) => Promise<{ data: Float32Array }[]>; + +/** + * SessionSummarizer generates session summaries for hierarchical retrieval. + * + * Features: + * - LLM-based summarization (2-3 sentences) + * - Keyword/topic extraction (KeyBERT-style) + * - Named entity recognition (NER) + * - Summary embedding for retrieval + * + * @example + * ```typescript + * const summarizer = new SessionSummarizer(llm); + * + * const summary = await summarizer.summarize(turns); + * console.log(summary.summary); // "Discussion about project setup..." + * console.log(summary.topics); // ["project setup", "deployment", ...] + * console.log(summary.entities); // ["AWS", "Docker", "John", ...] + * ``` + */ +export class SessionSummarizer { + private config: SessionSummarizerConfig; + private llm: LLMProvider; + private embedder: TextEmbedder; + private nerPipeline: NERPipeline | null = null; + private nerLoadingPromise: Promise | null = null; + private keywordPipeline: FeatureExtractionPipeline | null = null; + private keywordLoadingPromise: Promise | null = null; + + constructor(llm: LLMProvider, config: Partial = {}) { + this.config = { ...DEFAULT_SESSION_SUMMARIZER_CONFIG, ...config }; + this.llm = llm; + this.embedder = new TextEmbedder(); + } + + /** + * Generate a summary for a conversation session. + * + * @param turns - Array of turns in the session (should be chronologically ordered) + * @returns SessionSummary with summary text, topics, entities, and embedding + */ + async summarize(turns: Turn[]): Promise { + if (turns.length === 0) { + throw new Error("Cannot summarize empty session"); + } + + // Build conversation context + const context = turns.map((t) => `${t.role}: ${t.content}`).join("\n"); + + // Run summarization, topic extraction, and entity extraction in parallel + const [summary, topics, entities] = await Promise.all([ + this.generateSummary(context), + this.extractTopics(context), + this.extractEntities(context), + ]); + + // Generate embedding for the summary + const embedding = await this.embedder.embed(summary); + + return { + sessionId: turns[0].sessionId, + summary, + topics, + entities, + startTime: turns[0].timestamp, + endTime: turns[turns.length - 1].timestamp, + turnCount: turns.length, + embedding, + }; + } + + /** + * Generate a summary using the LLM. + * + * @param context - Full conversation text + * @returns 2-3 sentence summary + */ + private async generateSummary(context: string): Promise { + const prompt = `Summarize this conversation in 2-3 sentences, focusing on: +1. Main topics discussed +2. Key facts or decisions +3. Named entities mentioned + +Conversation: +${context} + +Summary:`; + + const response = await this.llm.complete(prompt, { + temperature: 0.3, // Low temp for factual summary + maxTokens: 150, + }); + + return response.text.trim(); + } + + /** + * Extract key topics/keywords from the conversation. + * + * Uses a KeyBERT-style approach: + * 1. Generate embeddings for the document and candidate keywords + * 2. Rank keywords by cosine similarity to document embedding + * + * @param text - Conversation text + * @returns Array of top keywords/topics + */ + async extractTopics(text: string): Promise { + // Extract candidate keywords using simple n-gram extraction + const candidates = this.extractCandidateKeywords(text); + + if (candidates.length === 0) { + return []; + } + + // Get embeddings for document and candidates + const featureExtractor = await this.loadKeywordPipeline(); + + // Embed document + const docEmbeddingResult = await featureExtractor([text], { + pooling: "mean", + normalize: true, + }); + const docEmbedding = Array.from(docEmbeddingResult[0].data); + + // Embed candidates in batch + const candidateEmbeddingsResult = await featureExtractor(candidates, { + pooling: "mean", + normalize: true, + }); + + // Calculate cosine similarity for each candidate + const scored = candidates.map((candidate, idx) => { + const candidateEmbedding = Array.from(candidateEmbeddingsResult[idx].data); + const similarity = this.cosineSimilarity(docEmbedding, candidateEmbedding); + return { keyword: candidate, score: similarity }; + }); + + // Sort by score and take top N + scored.sort((a, b) => b.score - a.score); + return scored.slice(0, this.config.maxTopics).map((s) => s.keyword); + } + + /** + * Extract named entities from the conversation using NER. + * + * @param text - Conversation text + * @returns Array of unique entity names + */ + async extractEntities(text: string): Promise { + const ner = await this.loadNERPipeline(); + const entities = await ner(text); + + // Filter by score and deduplicate + const filtered = entities + .filter((e) => e.score >= this.config.minEntityScore) + .map((e) => this.cleanEntityWord(e.word)); + + // Deduplicate (case-insensitive) + const seen = new Set(); + const unique: string[] = []; + for (const entity of filtered) { + const lower = entity.toLowerCase(); + if (!seen.has(lower) && entity.length > 1) { + seen.add(lower); + unique.push(entity); + } + } + + return unique; + } + + /** + * Extract candidate keywords using simple n-gram extraction. + * Focuses on nouns and noun phrases by filtering common stopwords. + */ + private extractCandidateKeywords(text: string): string[] { + // Common English stopwords + const stopwords = new Set([ + "a", + "an", + "the", + "and", + "or", + "but", + "in", + "on", + "at", + "to", + "for", + "of", + "with", + "by", + "from", + "as", + "is", + "was", + "are", + "were", + "been", + "be", + "have", + "has", + "had", + "do", + "does", + "did", + "will", + "would", + "could", + "should", + "may", + "might", + "must", + "shall", + "can", + "this", + "that", + "these", + "those", + "i", + "you", + "he", + "she", + "it", + "we", + "they", + "me", + "him", + "her", + "us", + "them", + "my", + "your", + "his", + "its", + "our", + "their", + "what", + "which", + "who", + "whom", + "when", + "where", + "why", + "how", + "all", + "each", + "every", + "both", + "few", + "more", + "most", + "other", + "some", + "such", + "no", + "not", + "only", + "own", + "same", + "so", + "than", + "too", + "very", + "just", + "also", + "now", + "here", + "there", + "then", + "user", + "assistant", + "system", + ]); + + // Tokenize and filter + const words = text + .toLowerCase() + .replace(/[^\w\s]/g, " ") + .split(/\s+/) + .filter((w) => w.length > 2 && !stopwords.has(w)); + + // Get unique words + const uniqueWords = [...new Set(words)]; + + // Generate bigrams (2-word phrases) + const bigrams: string[] = []; + for (let i = 0; i < words.length - 1; i++) { + const bigram = `${words[i]} ${words[i + 1]}`; + if (!stopwords.has(words[i]) && !stopwords.has(words[i + 1])) { + bigrams.push(bigram); + } + } + const uniqueBigrams = [...new Set(bigrams)]; + + // Combine unigrams and bigrams (prioritize bigrams) + return [...uniqueBigrams.slice(0, 20), ...uniqueWords.slice(0, 20)]; + } + + /** + * Calculate cosine similarity between two vectors. + */ + private cosineSimilarity(a: number[], b: number[]): number { + if (a.length !== b.length) { + throw new Error("Vectors must have same length"); + } + + let dotProduct = 0; + let normA = 0; + let normB = 0; + + for (let i = 0; i < a.length; i++) { + dotProduct += a[i] * b[i]; + normA += a[i] * a[i]; + normB += b[i] * b[i]; + } + + const denom = Math.sqrt(normA) * Math.sqrt(normB); + return denom === 0 ? 0 : dotProduct / denom; + } + + /** + * Clean entity word from NER (remove ## prefix from subword tokens). + */ + private cleanEntityWord(word: string): string { + // Remove BERT subword prefix + return word.replace(/^##/, ""); + } + + /** + * Lazy load the NER pipeline. + */ + private async loadNERPipeline(): Promise { + if (this.nerPipeline) { + return this.nerPipeline; + } + + if (this.nerLoadingPromise) { + return this.nerLoadingPromise; + } + + this.nerLoadingPromise = this.initNERPipeline(); + + try { + this.nerPipeline = await this.nerLoadingPromise; + return this.nerPipeline; + } finally { + this.nerLoadingPromise = null; + } + } + + /** + * Initialize the NER pipeline. + */ + private async initNERPipeline(): Promise { + const pipelineFn = pipeline as (task: string, model: string) => Promise; + return pipelineFn("token-classification", this.config.nerModel); + } + + /** + * Lazy load the keyword extraction pipeline. + */ + private async loadKeywordPipeline(): Promise { + if (this.keywordPipeline) { + return this.keywordPipeline; + } + + if (this.keywordLoadingPromise) { + return this.keywordLoadingPromise; + } + + this.keywordLoadingPromise = this.initKeywordPipeline(); + + try { + this.keywordPipeline = await this.keywordLoadingPromise; + return this.keywordPipeline; + } finally { + this.keywordLoadingPromise = null; + } + } + + /** + * Initialize the keyword extraction pipeline. + */ + private async initKeywordPipeline(): Promise { + const pipelineFn = pipeline as ( + task: string, + model: string, + ) => Promise; + return pipelineFn("feature-extraction", this.config.keywordModel); + } + + /** + * Preload models for faster first summarization. + */ + async preload(): Promise { + await Promise.all([ + this.loadNERPipeline(), + this.loadKeywordPipeline(), + this.embedder.preload(), + ]); + } + + /** + * Get current configuration. + */ + getConfig(): Readonly { + return this.config; + } + + /** + * Update configuration at runtime. + */ + updateConfig(config: Partial): void { + this.config = { ...this.config, ...config }; + } +} diff --git a/packages/search/src/services/snapshot-manager.test.ts b/packages/search/src/services/snapshot-manager.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d5b56e16165a64c699d425db61a966d34b116b7 --- /dev/null +++ b/packages/search/src/services/snapshot-manager.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it, vi } from "vitest"; +import { SnapshotManager } from "./snapshot-manager"; + +// Mock QdrantClient +vi.mock("@qdrant/js-client-rest", () => { + return { + QdrantClient: class { + async createSnapshot(_collection: string) { + return { name: "test-snapshot.snapshot", creation_time: "now" }; + } + async listSnapshots(_collection: string) { + return [ + { name: "snapshot-2024-01-01.snapshot", creation_time: "2024-01-01T00:00:00Z" }, + { name: "snapshot-2024-01-02.snapshot", creation_time: "2024-01-02T00:00:00Z" }, + ]; + } + async recoverSnapshot(_collection: string, _options: unknown) { + return true; + } + async deleteSnapshot(_collection: string, _snapshotName: string) { + return true; + } + }, + }; +}); + +describe("SnapshotManager", () => { + it("should create a snapshot", async () => { + const manager = new SnapshotManager(); + const result = await manager.createSnapshot(); + expect(result).toEqual({ name: "test-snapshot.snapshot", creation_time: "now" }); + }); + + it("should list snapshots", async () => { + const manager = new SnapshotManager(); + const result = await manager.listSnapshots(); + expect(result).toHaveLength(2); + expect(result[0].name).toBe("snapshot-2024-01-01.snapshot"); + }); + + it("should generate correct snapshot URL", () => { + const manager = new SnapshotManager("http://localhost:6333"); + const url = manager.getSnapshotUrl("test-snapshot.snapshot"); + expect(url).toBe( + "http://localhost:6333/collections/engram_memory/snapshots/test-snapshot.snapshot", + ); + }); + + it("should recover from a snapshot", async () => { + const manager = new SnapshotManager(); + const result = await manager.recoverSnapshot({ + location: "http://localhost:6333/collections/engram_memory/snapshots/test.snapshot", + priority: "snapshot", + }); + expect(result).toBe(true); + }); + + it("should recover from latest snapshot", async () => { + const manager = new SnapshotManager(); + const result = await manager.recoverFromLatest(); + // Should pick the most recent snapshot (2024-01-02) + expect(result).toBe(true); + }); + + it("should delete a snapshot", async () => { + const manager = new SnapshotManager(); + const result = await manager.deleteSnapshot("test-snapshot.snapshot"); + expect(result).toBe(true); + }); +}); diff --git a/packages/search/src/services/snapshot-manager.ts b/packages/search/src/services/snapshot-manager.ts new file mode 100644 index 0000000000000000000000000000000000000000..001ca5d5847bcea30e29ff5237dbe2a10be0144e --- /dev/null +++ b/packages/search/src/services/snapshot-manager.ts @@ -0,0 +1,109 @@ +import { QdrantClient } from "@qdrant/js-client-rest"; + +type RecoveryPriority = "replica" | "snapshot" | "no_sync"; + +export interface RecoverOptions { + /** URL or local path to the snapshot file */ + location: string; + /** + * Recovery priority: + * - replica: Default. Replicas recover from other replicas first + * - snapshot: Force recovery from snapshot only + * - no_sync: Skip sync with other replicas (fastest) + */ + priority?: RecoveryPriority; +} + +export class SnapshotManager { + private client: QdrantClient; + private collectionName = "engram_memory"; + private baseUrl: string; + + constructor(url: string = "http://localhost:6333") { + this.client = new QdrantClient({ url }); + this.baseUrl = url; + } + + /** + * Creates a snapshot of the memory collection. + * @returns The snapshot description (name, creation time, size). + */ + async createSnapshot() { + const result = await this.client.createSnapshot(this.collectionName); + return result; + } + + /** + * Lists all available snapshots for the memory collection. + */ + async listSnapshots() { + const result = await this.client.listSnapshots(this.collectionName); + return result; + } + + /** + * Gets the download URL for a specific snapshot. + * @param snapshotName - The name of the snapshot to download + * @returns The URL to download the snapshot + */ + getSnapshotUrl(snapshotName: string): string { + return `${this.baseUrl}/collections/${this.collectionName}/snapshots/${snapshotName}`; + } + + /** + * Recovers the collection from a snapshot. + * This will recreate the collection from the snapshot, replacing any existing data. + * + * WARNING: This is a destructive operation. Existing collection data will be overwritten. + * + * @param options - Recovery options including snapshot location and priority + * @returns Recovery result + */ + async recoverSnapshot(options: RecoverOptions) { + const { location, priority = "snapshot" } = options; + + // Use recoverSnapshot API to restore from URL or local path + const result = await this.client.recoverSnapshot(this.collectionName, { + location, + priority, + }); + + return result; + } + + /** + * Recovers the collection from the most recent snapshot. + * Convenience method that finds the latest snapshot and recovers from it. + * + * @param priority - Recovery priority (default: "snapshot") + * @returns Recovery result or null if no snapshots exist + */ + async recoverFromLatest(priority: RecoveryPriority = "snapshot") { + const snapshots = await this.listSnapshots(); + + if (!snapshots || snapshots.length === 0) { + return null; + } + + // Sort by creation time descending and get the latest + const sorted = [...snapshots].sort((a, b) => { + const timeA = typeof a.creation_time === "string" ? Date.parse(a.creation_time) : 0; + const timeB = typeof b.creation_time === "string" ? Date.parse(b.creation_time) : 0; + return timeB - timeA; + }); + + const latestSnapshot = sorted[0]; + const location = this.getSnapshotUrl(latestSnapshot.name); + + return this.recoverSnapshot({ location, priority }); + } + + /** + * Deletes a specific snapshot. + * @param snapshotName - The name of the snapshot to delete + */ + async deleteSnapshot(snapshotName: string) { + const result = await this.client.deleteSnapshot(this.collectionName, snapshotName); + return result; + } +} diff --git a/packages/search/src/services/splade-embedder.test.ts b/packages/search/src/services/splade-embedder.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0b2c505ca520b84a43d0d13c1bd4a5e6eb73083 --- /dev/null +++ b/packages/search/src/services/splade-embedder.test.ts @@ -0,0 +1,229 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { SpladeEmbedder } from "./splade-embedder"; + +// Simple hash function for deterministic "random" values based on input +function simpleHash(str: string): number { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; // Convert to 32bit integer + } + return Math.abs(hash); +} + +// Mock model that returns MLM logits +const mockModel = vi.fn(async (inputs: { input_ids: unknown; attention_mask: unknown }) => { + // Get input IDs to create deterministic output based on input + const inputIds = (inputs.input_ids as { data: number[] }).data; + const maskData = (inputs.attention_mask as { data: number[] }).data; + const seqLen = maskData.length; + const vocabSize = 30522; + + // Create a deterministic seed from input IDs + const inputKey = inputIds.join(","); + const seed = simpleHash(inputKey); + + // Generate mock logits: most are negative (will be zeroed by ReLU) + // A few positive values to simulate learned sparse representation + const logitsData = new Float32Array(seqLen * vocabSize); + + // Set some positive logits for specific token positions + // This simulates the model "activating" certain vocabulary terms + // Use different active tokens based on input to simulate different outputs + // Spread tokens across vocabulary using seed to create diverse patterns + const numTokens = 15; + const activeTokens: number[] = []; + for (let i = 0; i < numTokens; i++) { + // Use a multiplicative hash to spread tokens across vocabulary + activeTokens.push(((seed * (i + 1) * 2654435761) >>> 0) % vocabSize); + } + + for (let pos = 0; pos < seqLen; pos++) { + if (maskData[pos] === 0) continue; + for (let i = 0; i < activeTokens.length; i++) { + const tokenId = activeTokens[i]; + // Deterministic value based on position and token index + logitsData[pos * vocabSize + tokenId] = 1.5 + ((seed + pos + i) % 100) / 200; + } + } + + return { + logits: { + data: logitsData, + dims: [1, seqLen, vocabSize], + }, + }; +}); + +// Mock tokenizer - produces different IDs based on input text +const mockTokenizer = vi.fn((text: string, _options?: unknown) => { + const words = text.toLowerCase().split(/\s+/).filter(Boolean); + const seqLen = Math.min(words.length + 2, 512); // +2 for [CLS] and [SEP] + + // Generate input IDs based on actual text content for deterministic but varied output + const textHash = simpleHash(text); + const inputIds = new Array(seqLen).fill(0).map((_, i) => { + if (i === 0) return 101; // [CLS] + if (i === seqLen - 1) return 102; // [SEP] + // Use hash + position to create unique but deterministic IDs + return 1000 + ((textHash + i * 7) % 28000); + }); + const attentionMask = new Array(seqLen).fill(1); + + return { + input_ids: { data: inputIds, dims: [1, seqLen] }, + attention_mask: { data: attentionMask, dims: [1, seqLen] }, + }; +}); + +// Mock transformers module +vi.mock("@huggingface/transformers", () => ({ + AutoModel: { + from_pretrained: vi.fn(async () => mockModel), + }, + AutoTokenizer: { + from_pretrained: vi.fn(async () => mockTokenizer), + }, +})); + +describe("SpladeEmbedder", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("embed", () => { + it("should generate sparse vectors with indices and values", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embed("machine learning is great"); + + expect(sparse.indices).toBeInstanceOf(Array); + expect(sparse.values).toBeInstanceOf(Array); + expect(sparse.indices.length).toBeGreaterThan(0); + expect(sparse.indices.length).toBe(sparse.values.length); + }); + + it("should produce sparse output (< 1000 non-zero dimensions)", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embed("TypeScript is a typed superset of JavaScript"); + + // SPLADE should be highly sparse + expect(sparse.indices.length).toBeLessThan(1000); + // But should have some activations + expect(sparse.indices.length).toBeGreaterThan(0); + }); + + it("should have sorted indices for Qdrant compatibility", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embed("the quick brown fox jumps over the lazy dog"); + + for (let i = 1; i < sparse.indices.length; i++) { + expect(sparse.indices[i]).toBeGreaterThan(sparse.indices[i - 1]); + } + }); + + it("should have positive weights (ReLU + log1p output)", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embed("testing sparse vectors"); + + for (const value of sparse.values) { + expect(value).toBeGreaterThan(0); + } + }); + + it("should have indices within BERT vocabulary range", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embed("hello world"); + + for (const idx of sparse.indices) { + expect(idx).toBeGreaterThanOrEqual(0); + expect(idx).toBeLessThan(30522); + } + }); + }); + + describe("embedQuery", () => { + it("should generate sparse vectors for queries", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embedQuery("search query"); + + expect(sparse.indices.length).toBeGreaterThan(0); + expect(sparse.values.length).toBe(sparse.indices.length); + }); + + it("should use same format as document embedding", async () => { + const embedder = new SpladeEmbedder(); + const docSparse = await embedder.embed("test document"); + const querySparse = await embedder.embedQuery("test document"); + + // Both should have same structure + expect(docSparse.indices).toBeInstanceOf(Array); + expect(querySparse.indices).toBeInstanceOf(Array); + expect(docSparse.values).toBeInstanceOf(Array); + expect(querySparse.values).toBeInstanceOf(Array); + }); + }); + + describe("preload", () => { + it("should load model and tokenizer", async () => { + const embedder = new SpladeEmbedder(); + + // Preload should complete without error + await embedder.preload(); + + // After preload, model should be ready + expect(embedder.isReady()).toBe(true); + }); + + it("should allow embedding after preload", async () => { + const embedder = new SpladeEmbedder(); + await embedder.preload(); + + // Should be able to embed after preload + const sparse = await embedder.embed("test after preload"); + expect(sparse.indices.length).toBeGreaterThan(0); + }); + }); + + describe("consistency", () => { + it("should produce consistent results for same input", async () => { + const embedder = new SpladeEmbedder(); + const sparse1 = await embedder.embed("hello world"); + const sparse2 = await embedder.embed("hello world"); + + expect(sparse1.indices).toEqual(sparse2.indices); + expect(sparse1.values).toEqual(sparse2.values); + }); + + it("should produce deterministic results for same input", async () => { + // Note: Real differentiation between inputs is tested in integration tests + // with the actual SPLADE model. Here we verify the mock produces consistent + // structure for deterministic testing. + const embedder = new SpladeEmbedder(); + const sparse1 = await embedder.embed("hello world"); + const sparse2 = await embedder.embed("hello world"); + + // Same input should always produce same output + expect(sparse1.indices).toEqual(sparse2.indices); + expect(sparse1.values).toEqual(sparse2.values); + expect(sparse1.indices.length).toBeGreaterThan(0); + }); + }); + + describe("edge cases", () => { + it("should handle short input", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embed("hi"); + + expect(sparse.indices.length).toBeGreaterThan(0); + expect(sparse.values.length).toBe(sparse.indices.length); + }); + + it("should handle single word", async () => { + const embedder = new SpladeEmbedder(); + const sparse = await embedder.embed("test"); + + expect(sparse.indices.length).toBeGreaterThan(0); + }); + }); +}); diff --git a/packages/search/src/services/splade-embedder.ts b/packages/search/src/services/splade-embedder.ts new file mode 100644 index 0000000000000000000000000000000000000000..4d4bf0bcf0d4fe40be09d246d0be1a1be1555f21 --- /dev/null +++ b/packages/search/src/services/splade-embedder.ts @@ -0,0 +1,191 @@ +import { AutoModel, AutoTokenizer, type Tensor } from "@huggingface/transformers"; +import { BaseSparseEmbedder, type EmbedderConfig, type SparseVector } from "./base-embedder"; + +/** + * Configuration for SpladeEmbedder. + */ +export interface SpladeEmbedderConfig extends EmbedderConfig { + /** Maximum sequence length (default: 512) */ + maxLength?: number; + /** Model precision */ + dtype?: "fp32" | "fp16"; + /** Threshold for filtering near-zero values */ + sparseThreshold?: number; +} + +const DEFAULT_CONFIG: SpladeEmbedderConfig = { + model: "sparse-encoder-testing/splade-bert-tiny-nq-onnx", + dimensions: 30522, // BERT vocabulary size + maxLength: 512, + dtype: "fp32", + sparseThreshold: 1e-6, +}; + +/** + * SPLADE sparse embedder using ONNX model. + * Extends BaseSparseEmbedder for sparse vector output. + * + * Generates learned sparse representations for hybrid search. + * + * SPLADE (Sparse Lexical and Expansion Model) learns to expand queries/documents + * with semantically related terms while producing sparse vectors compatible with + * inverted index retrieval. + */ +export class SpladeEmbedder extends BaseSparseEmbedder { + // Singleton instances (lazy loaded) + private static model: Awaited> | null = null; + private static tokenizer: Awaited> | null = null; + private static modelPromise: Promise< + Awaited> + > | null = null; + private static tokenizerPromise: Promise< + Awaited> + > | null = null; + + constructor(config: Partial = {}) { + super({ ...DEFAULT_CONFIG, ...config }); + } + + /** + * Load the model and tokenizer (for preloading). + */ + protected async loadModel(): Promise { + await Promise.all([this.getModel(), this.getTokenizer()]); + } + + /** + * Get or initialize the ONNX model. + * Uses singleton pattern with lazy initialization for efficiency. + */ + private async getModel() { + if (SpladeEmbedder.model) { + return SpladeEmbedder.model; + } + if (!SpladeEmbedder.modelPromise) { + SpladeEmbedder.modelPromise = AutoModel.from_pretrained(this.config.model, { + dtype: this.config.dtype, + }); + } + SpladeEmbedder.model = await SpladeEmbedder.modelPromise; + return SpladeEmbedder.model; + } + + /** + * Get or initialize the tokenizer. + */ + private async getTokenizer() { + if (SpladeEmbedder.tokenizer) { + return SpladeEmbedder.tokenizer; + } + if (!SpladeEmbedder.tokenizerPromise) { + SpladeEmbedder.tokenizerPromise = AutoTokenizer.from_pretrained(this.config.model); + } + SpladeEmbedder.tokenizer = await SpladeEmbedder.tokenizerPromise; + return SpladeEmbedder.tokenizer; + } + + /** + * Apply SPLADE pooling to MLM logits. + * SPLADE pooling: max(log(1 + ReLU(logits)), dim=1) + * + * This produces sparse vectors where each dimension corresponds to a + * vocabulary token, with non-zero values indicating term importance. + * + * @param logits - MLM logits tensor of shape [batch, seq_len, vocab_size] + * @param attentionMask - Attention mask tensor of shape [batch, seq_len] + * @returns Sparse vector as {indices, values} for Qdrant + */ + private spladePooling(logits: Tensor, attentionMask: Tensor): SparseVector { + // Get dimensions + const logitsData = logits.data as Float32Array; + const maskData = attentionMask.data as BigInt64Array | Float32Array | Int32Array; + const [batchSize, seqLen, vocabSize] = logits.dims as [number, number, number]; + + // We only handle batch size 1 for now + if (batchSize !== 1) { + throw new Error("SpladeEmbedder only supports batch size 1"); + } + + // Apply ReLU + log1p and max pool across sequence dimension + const pooled = new Float32Array(vocabSize); + pooled.fill(-Infinity); + + for (let pos = 0; pos < seqLen; pos++) { + // Skip masked positions + if (Number(maskData[pos]) === 0) continue; + + const offset = pos * vocabSize; + for (let v = 0; v < vocabSize; v++) { + // ReLU: max(0, x) + const relu = Math.max(0, logitsData[offset + v]); + // log1p: log(1 + x) + const value = Math.log1p(relu); + // Max pooling across sequence + pooled[v] = Math.max(pooled[v], value); + } + } + + // Convert to sparse format - only keep non-zero values + const indexValuePairs: Array<[number, number]> = []; + const threshold = this.config.sparseThreshold ?? 1e-6; + + for (let v = 0; v < vocabSize; v++) { + const value = pooled[v]; + if (value > threshold && Number.isFinite(value)) { + indexValuePairs.push([v, value]); + } + } + + // Sort by index for consistent ordering (Qdrant expects sorted indices) + indexValuePairs.sort((a, b) => a[0] - b[0]); + + return { + indices: indexValuePairs.map(([idx]) => idx), + values: indexValuePairs.map(([, val]) => val), + }; + } + + /** + * Generate sparse embedding for text using SPLADE. + * Returns indices (vocabulary token IDs) and values (term importance weights). + * + * @param text - Input text to embed + * @returns Sparse vector in Qdrant format + */ + async embed(text: string): Promise { + const [model, tokenizer] = await Promise.all([this.getModel(), this.getTokenizer()]); + + // Tokenize input + const encoded = tokenizer(text, { + padding: true, + truncation: true, + max_length: this.config.maxLength, + return_tensors: "pt", + }); + + // Run model inference to get MLM logits + const output = await (model as (inputs: unknown) => Promise<{ logits: Tensor }>)(encoded); + + // Apply SPLADE pooling + return this.spladePooling(output.logits, encoded.attention_mask); + } + + /** + * Generate sparse embedding for a query. + * Currently identical to document embedding, but could be tuned differently + * (e.g., with query-specific prefix or different pooling). + * + * @param text - Query text to embed + * @returns Sparse vector in Qdrant format + */ + async embedQuery(text: string): Promise { + return this.embed(text); + } + + /** + * Check if the model is loaded and ready. + */ + isReady(): boolean { + return SpladeEmbedder.model !== null && SpladeEmbedder.tokenizer !== null; + } +} diff --git a/packages/search/src/services/temporal-parser.test.ts b/packages/search/src/services/temporal-parser.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..01e9f33b488c049b3f2c238949bc46d6355136a5 --- /dev/null +++ b/packages/search/src/services/temporal-parser.test.ts @@ -0,0 +1,171 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { applyRecencyBoost, buildTemporalFilter, TemporalQueryParser } from "./temporal-parser"; + +describe("TemporalQueryParser", () => { + let parser: TemporalQueryParser; + + beforeEach(() => { + // Use a fixed reference date for consistent tests + parser = new TemporalQueryParser(new Date("2024-12-18T12:00:00Z")); + }); + + describe("parse", () => { + it("should parse 'last week' as relative temporal expression", () => { + const result = parser.parse("What did we discuss last week?"); + + expect(result.temporalFilter).not.toBeNull(); + expect(result.temporalFilter?.expression).toBe("last week"); + expect(result.temporalFilter?.after).toBeInstanceOf(Date); + expect(result.temporalFilter?.before).toBeInstanceOf(Date); + expect(result.semanticQuery).toBe("What did we discuss?"); + expect(result.confidence).toBeGreaterThan(0); + }); + + it("should parse 'yesterday' as single day", () => { + const result = parser.parse("Show me yesterday's logs"); + + expect(result.temporalFilter).not.toBeNull(); + expect(result.temporalFilter?.expression).toBe("yesterday"); + }); + + it("should parse absolute date 'January 2024'", () => { + const result = parser.parse("What happened in January 2024?"); + + expect(result.temporalFilter).not.toBeNull(); + expect(result.temporalFilter?.after?.getMonth()).toBe(0); // January + expect(result.temporalFilter?.after?.getFullYear()).toBe(2024); + }); + + it("should return null filter for queries without temporal expressions", () => { + const result = parser.parse("How do I implement authentication?"); + + expect(result.temporalFilter).toBeNull(); + expect(result.semanticQuery).toBe("How do I implement authentication?"); + expect(result.confidence).toBe(0); + }); + + it("should detect recency intent with 'latest'", () => { + const result = parser.parse("Show me the latest updates from last week"); + + expect(result.temporalFilter?.sortByRecency).toBe(true); + }); + + it("should detect recency intent with 'recent'", () => { + // 'recent' alone may not be parsed as a temporal expression by chrono + // but the recency detection should still work when there's a temporal filter + const result = parser.parse("What are the most recent changes from last week?"); + + expect(result.temporalFilter?.sortByRecency).toBe(true); + }); + + it("should handle '3 days ago'", () => { + const result = parser.parse("What was discussed 3 days ago?"); + + expect(result.temporalFilter).not.toBeNull(); + expect(result.temporalFilter?.expression).toContain("3 days ago"); + }); + }); + + describe("setReferenceDate", () => { + it("should update reference date for relative expressions", () => { + const parser1 = new TemporalQueryParser(new Date("2024-12-18")); + const result1 = parser1.parse("What happened yesterday?"); + + const parser2 = new TemporalQueryParser(new Date("2024-01-01")); + const result2 = parser2.parse("What happened yesterday?"); + + // Different reference dates should produce different temporal filters + expect(result1.temporalFilter?.after?.getTime()).not.toBe( + result2.temporalFilter?.after?.getTime(), + ); + }); + }); +}); + +describe("buildTemporalFilter", () => { + it("should build Qdrant filter with after constraint", () => { + const filter = buildTemporalFilter({ + after: new Date("2024-12-11T00:00:00Z"), + }); + + expect(filter).not.toBeNull(); + expect(filter?.must).toHaveLength(1); + expect(filter?.must[0].key).toBe("valid_time"); + expect(filter?.must[0].range.gte).toBe("2024-12-11T00:00:00.000Z"); + }); + + it("should build Qdrant filter with before constraint", () => { + const filter = buildTemporalFilter({ + before: new Date("2024-12-18T00:00:00Z"), + }); + + expect(filter).not.toBeNull(); + expect(filter?.must).toHaveLength(1); + expect(filter?.must[0].range.lte).toBe("2024-12-18T00:00:00.000Z"); + }); + + it("should build Qdrant filter with both constraints", () => { + const filter = buildTemporalFilter({ + after: new Date("2024-12-11T00:00:00Z"), + before: new Date("2024-12-18T00:00:00Z"), + }); + + expect(filter?.must).toHaveLength(2); + }); + + it("should return null for empty filter", () => { + const filter = buildTemporalFilter({}); + + expect(filter).toBeNull(); + }); + + it("should use custom field name", () => { + const filter = buildTemporalFilter({ after: new Date("2024-12-11") }, "timestamp"); + + expect(filter?.must[0].key).toBe("timestamp"); + }); +}); + +describe("applyRecencyBoost", () => { + it("should boost recent results higher", () => { + const referenceDate = new Date("2024-12-18T12:00:00Z"); + const results = [ + { id: "old", score: 0.8, validTime: new Date("2024-11-01") }, + { id: "recent", score: 0.8, validTime: new Date("2024-12-17") }, + ]; + + const boosted = applyRecencyBoost(results, referenceDate); + + // Recent result should have higher score after boost + const recentResult = boosted.find((r) => r.id === "recent"); + const oldResult = boosted.find((r) => r.id === "old"); + + expect(recentResult?.score).toBeGreaterThan(oldResult?.score ?? 0); + }); + + it("should sort results by boosted score", () => { + const referenceDate = new Date("2024-12-18T12:00:00Z"); + const results = [ + { id: "old", score: 0.9, validTime: new Date("2024-10-01") }, + { id: "recent", score: 0.8, validTime: new Date("2024-12-17") }, + ]; + + const boosted = applyRecencyBoost(results, referenceDate, 0.2); + + // With high enough boost factor, recent should overtake old + expect(boosted[0].id).toBe("recent"); + }); + + it("should handle results without validTime", () => { + const referenceDate = new Date("2024-12-18T12:00:00Z"); + const results = [ + { id: "no-time", score: 0.8 }, + { id: "has-time", score: 0.8, validTime: new Date("2024-12-17") }, + ]; + + const boosted = applyRecencyBoost(results, referenceDate); + + // Should not throw, results without validTime should keep original score + expect(boosted.find((r) => r.id === "no-time")?.score).toBe(0.8); + }); +}); diff --git a/packages/search/src/services/temporal-parser.ts b/packages/search/src/services/temporal-parser.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f61ef93aeb7aad96a917d29a18c30176bf4431f --- /dev/null +++ b/packages/search/src/services/temporal-parser.ts @@ -0,0 +1,244 @@ +import * as chrono from "chrono-node"; + +/** + * Temporal filter constraints for time-filtered retrieval. + */ +export interface TemporalFilter { + /** Start of time range (inclusive) */ + after?: Date; + /** End of time range (inclusive) */ + before?: Date; + /** Whether to sort by recency */ + sortByRecency?: boolean; + /** Original temporal expression */ + expression?: string; +} + +/** + * Result of parsing temporal expressions from a query. + */ +export interface TemporalQueryResult { + /** Semantic part of query (temporal expressions removed) */ + semanticQuery: string; + /** Extracted temporal filter */ + temporalFilter: TemporalFilter | null; + /** Confidence in temporal extraction (0-1) */ + confidence: number; +} + +/** + * Qdrant filter condition for temporal queries. + */ +export interface QdrantTemporalFilter { + must: Array<{ + key: string; + range: { gte?: string; lte?: string }; + }>; +} + +/** + * Parses temporal expressions from queries using chrono-node. + * + * Supports: + * - Relative: "last week", "yesterday", "3 days ago" + * - Absolute: "January 2024", "on Dec 15" + * - Range: "between Jan and March" + * - Ordinal: "first meeting", "latest update" + * + * @example + * ```typescript + * const parser = new TemporalQueryParser(); + * const result = parser.parse("What did we discuss last week?"); + * // result.semanticQuery = "What did we discuss?" + * // result.temporalFilter = { after: Date, before: Date } + * ``` + */ +export class TemporalQueryParser { + private referenceDate: Date; + + constructor(referenceDate?: Date) { + this.referenceDate = referenceDate ?? new Date(); + } + + /** + * Update the reference date for relative temporal expressions. + */ + setReferenceDate(date: Date): void { + this.referenceDate = date; + } + + /** + * Parse temporal expressions from a query. + */ + parse(query: string): TemporalQueryResult { + // Parse temporal expressions with chrono-node + const results = chrono.parse(query, this.referenceDate, { + forwardDate: false, // Prefer past dates for "last X" + }); + + if (results.length === 0) { + return { + semanticQuery: query, + temporalFilter: null, + confidence: 0, + }; + } + + // Extract the most relevant temporal reference + const primary = results[0]; + const temporalFilter: TemporalFilter = { + expression: primary.text, + }; + + // Handle different result types + if (primary.start && primary.end) { + // Range: "between X and Y" + temporalFilter.after = primary.start.date(); + temporalFilter.before = primary.end.date(); + } else if (primary.start) { + // Single reference: "last week", "in January" + const start = primary.start.date(); + const end = primary.end?.date() ?? this.inferEndDate(primary, start); + temporalFilter.after = start; + temporalFilter.before = end; + } + + // Check for recency indicators + temporalFilter.sortByRecency = this.detectRecencyIntent(query); + + // Remove temporal expression from query for semantic search + const semanticQuery = this.removeTemporalExpression(query, primary.text); + + return { + semanticQuery: semanticQuery || query, + temporalFilter, + confidence: this.calculateConfidence(primary), + }; + } + + /** + * Check if query implies wanting recent results. + */ + private detectRecencyIntent(query: string): boolean { + const recencyPatterns = /\b(latest|recent|newest|current|most recent|last)\b/i; + return recencyPatterns.test(query); + } + + /** + * Remove temporal expression from query, cleaning up whitespace. + */ + private removeTemporalExpression(query: string, expression: string): string { + return query + .replace(expression, "") + .replace(/\s{2,}/g, " ") // Collapse multiple spaces to single space + .replace(/\s+([?!.,])/g, "$1") // Remove space before punctuation + .trim(); + } + + /** + * Infer end date based on granularity of the parsed result. + */ + private inferEndDate(result: chrono.ParsedResult, start: Date): Date { + const component = result.start; + + if (component.isCertain("day")) { + // Same day - end of day + const end = new Date(start); + end.setHours(23, 59, 59, 999); + return end; + } else if (component.isCertain("month") && !component.isCertain("day")) { + // End of month + const end = new Date(start); + end.setMonth(end.getMonth() + 1); + end.setDate(0); + end.setHours(23, 59, 59, 999); + return end; + } else if (component.isCertain("year") && !component.isCertain("month")) { + // End of year + return new Date(start.getFullYear(), 11, 31, 23, 59, 59, 999); + } + + // Default: 7 days from start (for expressions like "last week") + return new Date(start.getTime() + 7 * 24 * 60 * 60 * 1000); + } + + /** + * Calculate confidence based on how certain the parsed components are. + */ + private calculateConfidence(result: chrono.ParsedResult): number { + let certainty = 0; + const component = result.start; + + if (component.isCertain("year")) certainty += 0.3; + if (component.isCertain("month")) certainty += 0.3; + if (component.isCertain("day")) certainty += 0.3; + if (result.end) certainty += 0.1; // Explicit range + + return Math.min(certainty, 1.0); + } +} + +/** + * Build Qdrant filter from temporal constraints. + * + * @param filter - Temporal filter with date constraints + * @param fieldName - Name of the timestamp field in Qdrant (default: "valid_time") + * @returns Qdrant filter object or null if no constraints + */ +export function buildTemporalFilter( + filter: TemporalFilter, + fieldName: string = "valid_time", +): QdrantTemporalFilter | null { + if (!filter.after && !filter.before) { + return null; + } + + const conditions: Array<{ key: string; range: { gte?: string; lte?: string } }> = []; + + if (filter.after) { + conditions.push({ + key: fieldName, + range: { gte: filter.after.toISOString() }, + }); + } + + if (filter.before) { + conditions.push({ + key: fieldName, + range: { lte: filter.before.toISOString() }, + }); + } + + return { must: conditions }; +} + +/** + * Apply recency boost to search results. + * + * More recent results get higher scores when the query implies recency. + * + * @param results - Search results with validTime and score + * @param referenceDate - Reference date for calculating age + * @param boostFactor - How much to boost recent results (0-1, default 0.1) + * @param maxAgeDays - Maximum age for boost calculation (default 30) + */ +export function applyRecencyBoost( + results: T[], + referenceDate: Date, + boostFactor: number = 0.1, + maxAgeDays: number = 30, +): T[] { + const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000; + + return results + .map((result) => { + if (!result.validTime) return result; + + const age = referenceDate.getTime() - result.validTime.getTime(); + const recencyScore = Math.max(0, 1 - age / maxAgeMs); + const boostedScore = result.score * (1 + boostFactor * recencyScore); + + return { ...result, score: boostedScore }; + }) + .sort((a, b) => b.score - a.score); +} diff --git a/packages/search/src/services/text-embedder.test.ts b/packages/search/src/services/text-embedder.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e281eec3d9df3c9ba582ddc19d1f70993b4ce2f4 --- /dev/null +++ b/packages/search/src/services/text-embedder.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, it, vi } from "vitest"; +import { TextEmbedder } from "./text-embedder"; + +const { mockPipeline, mockExtractor, mockAutoTokenizer, mockAutoModel, mockSpladeModel } = + vi.hoisted(() => { + const mockExtractor = vi.fn(async (_input: string) => { + return { + data: new Float32Array([0.1, 0.2, 0.3]), + dims: [1, 3], + size: 3, + }; + }); + + const mockPipeline = vi.fn(async (task: string, _model: string) => { + if (task === "feature-extraction") { + return mockExtractor; + } + throw new Error("Unknown task"); + }); + + // Mock tokenizer for SPLADE + const mockTokenizer = (_text: string, _options?: { add_special_tokens?: boolean }) => { + const words = _text.toLowerCase().split(/\s+/).filter(Boolean); + const ids = words.map((w, i) => { + let hash = 0; + for (const c of w) hash = (hash * 31 + c.charCodeAt(0)) % 30000; + return hash || i + 100; + }); + const fullIds = [101, ...ids, 102]; + const attentionMask = new Array(fullIds.length).fill(1); + return { + input_ids: { data: fullIds, dims: [1, fullIds.length] }, + attention_mask: { data: attentionMask, dims: [1, fullIds.length] }, + }; + }; + + const mockAutoTokenizer = { + from_pretrained: vi.fn(async () => mockTokenizer), + }; + + // Mock SPLADE model + const mockSpladeModel = vi.fn( + async (inputs: { input_ids: unknown; attention_mask: unknown }) => { + const maskData = (inputs.attention_mask as { data: number[] }).data; + const seqLen = maskData.length; + const vocabSize = 30522; + const logitsData = new Float32Array(seqLen * vocabSize); + const activeTokens = [100, 200, 1000]; + for (let pos = 0; pos < seqLen; pos++) { + if (maskData[pos] === 0) continue; + for (const tokenId of activeTokens) { + logitsData[pos * vocabSize + tokenId] = 1.5; + } + } + return { logits: { data: logitsData, dims: [1, seqLen, vocabSize] } }; + }, + ); + + const mockAutoModel = { + from_pretrained: vi.fn(async () => mockSpladeModel), + }; + + return { mockPipeline, mockExtractor, mockAutoTokenizer, mockAutoModel, mockSpladeModel }; + }); + +vi.mock("@huggingface/transformers", () => ({ + pipeline: mockPipeline, + AutoTokenizer: mockAutoTokenizer, + AutoModel: mockAutoModel, +})); + +describe("TextEmbedder", () => { + it("should embed document (passage)", async () => { + const embedder = new TextEmbedder(); + const vector = await embedder.embed("hello world"); + + expect(mockPipeline).toHaveBeenCalledWith( + "feature-extraction", + expect.stringContaining("e5-small"), + expect.objectContaining({ dtype: expect.any(String) }), + ); + expect(mockExtractor).toHaveBeenCalledWith("passage: hello world", expect.any(Object)); + expect(vector).toHaveLength(3); + expect(vector[0]).toBeCloseTo(0.1); + }); + + it("should embed query", async () => { + const embedder = new TextEmbedder(); + await embedder.embedQuery("search term"); + + expect(mockExtractor).toHaveBeenCalledWith("query: search term", expect.any(Object)); + }); + + describe("sparse embedding (SPLADE)", () => { + it("should generate sparse vectors with indices and values", async () => { + const embedder = new TextEmbedder(); + const sparse = await embedder.embedSparse("hello world test"); + + expect(sparse.indices).toBeInstanceOf(Array); + expect(sparse.values).toBeInstanceOf(Array); + expect(sparse.indices.length).toBeGreaterThan(0); + expect(sparse.indices.length).toBe(sparse.values.length); + }); + + it("should have sorted indices", async () => { + const embedder = new TextEmbedder(); + const sparse = await embedder.embedSparse("the quick brown fox"); + + for (let i = 1; i < sparse.indices.length; i++) { + expect(sparse.indices[i]).toBeGreaterThan(sparse.indices[i - 1]); + } + }); + + it("should have positive weights", async () => { + const embedder = new TextEmbedder(); + const sparse = await embedder.embedSparse("testing sparse vectors"); + + for (const value of sparse.values) { + expect(value).toBeGreaterThan(0); + } + }); + + it("should generate sparse query vectors", async () => { + const embedder = new TextEmbedder(); + const sparse = await embedder.embedSparseQuery("search query"); + + expect(sparse.indices.length).toBeGreaterThan(0); + expect(sparse.values.length).toBe(sparse.indices.length); + }); + }); +}); diff --git a/packages/search/src/services/text-embedder.ts b/packages/search/src/services/text-embedder.ts new file mode 100644 index 0000000000000000000000000000000000000000..225904fc748fdc7b6e2185e64919649198e00bff --- /dev/null +++ b/packages/search/src/services/text-embedder.ts @@ -0,0 +1,113 @@ +import { pipeline } from "@huggingface/transformers"; +import { + BasePipelineEmbedder, + type EmbedderConfig, + getDefaultDevice, + getDefaultDtype, +} from "./base-embedder"; +import { SpladeEmbedder } from "./splade-embedder"; + +/** + * Configuration for TextEmbedder. + */ +export interface TextEmbedderConfig extends EmbedderConfig { + /** Task prefix for passages (default: "passage:") */ + passagePrefix?: string; + /** Task prefix for queries (default: "query:") */ + queryPrefix?: string; +} + +const DEFAULT_CONFIG: TextEmbedderConfig = { + model: "Xenova/multilingual-e5-small", + dimensions: 384, + maxTokens: 512, + passagePrefix: "passage:", + queryPrefix: "query:", +}; + +type ExtractorFn = ( + text: string, + opts: { pooling: string; normalize: boolean }, +) => Promise<{ data: Float32Array }>; + +/** + * Text embedder using multilingual-e5-small model. + * Extends BasePipelineEmbedder for common functionality. + * + * Features: + * - Dense embeddings via HuggingFace pipeline + * - Sparse embeddings via SPLADE delegation + * - Task prefix support for retrieval optimization + */ +export class TextEmbedder extends BasePipelineEmbedder { + private static instance: unknown = null; + private sparseEmbedder = new SpladeEmbedder(); + + constructor(config: Partial = {}) { + super({ ...DEFAULT_CONFIG, ...config }); + } + + /** + * Get or create singleton pipeline instance. + */ + protected async getInstance(): Promise { + if (!TextEmbedder.instance) { + TextEmbedder.instance = await pipeline("feature-extraction", this.config.model, { + dtype: this.config.dtype ?? getDefaultDtype(), + device: this.config.device ?? getDefaultDevice(), + }); + } + return TextEmbedder.instance as ExtractorFn; + } + + /** + * Load the model (for preloading). + */ + protected async loadModel(): Promise { + await this.getInstance(); + } + + /** + * Embed document (passage) for storage/indexing. + */ + async embed(text: string): Promise { + return this.callEmbeddingAPI(text, { + prefix: this.config.passagePrefix, + pooling: "mean", + normalize: true, + }); + } + + /** + * Embed query for searching. + */ + async embedQuery(text: string): Promise { + return this.callEmbeddingAPI(text, { + prefix: this.config.queryPrefix, + pooling: "mean", + normalize: true, + }); + } + + /** + * Generate sparse vector using SPLADE learned sparse embeddings. + * Returns indices (vocabulary token IDs) and values (term importance weights). + */ + async embedSparse(text: string): Promise<{ indices: number[]; values: number[] }> { + return this.sparseEmbedder.embed(text); + } + + /** + * Generate sparse vector for queries using SPLADE. + */ + async embedSparseQuery(text: string): Promise<{ indices: number[]; values: number[] }> { + return this.sparseEmbedder.embedQuery(text); + } + + /** + * Preload the SPLADE model for faster first embedding. + */ + async preloadSparse(): Promise { + await this.sparseEmbedder.preload(); + } +} diff --git a/packages/search/test/evaluate-reranker.ts b/packages/search/test/evaluate-reranker.ts new file mode 100644 index 0000000000000000000000000000000000000000..49c888ddc07c10962b85832b16499c8cbd53b626 --- /dev/null +++ b/packages/search/test/evaluate-reranker.ts @@ -0,0 +1,371 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { createLogger } from "@engram/logger"; +import type { BatchedReranker } from "../src/services/batched-reranker"; + +const logger = createLogger({ component: "RerankerEvaluation" }); + +/** + * Relevance judgment for a single query-document pair. + */ +export interface RelevanceJudgment { + category: string; + query: string; + documents: Array<{ + id: string; + content: string; + relevance: number; // 0-3 scale + }>; +} + +/** + * Dataset of relevance judgments. + */ +export interface JudgmentDataset { + version: string; + description: string; + judgments: RelevanceJudgment[]; +} + +/** + * Evaluation metrics for reranker performance. + */ +export interface RerankerEvaluationMetrics { + /** Normalized Discounted Cumulative Gain (measures ranking quality) */ + ndcg: number; + /** Mean Average Precision (measures precision across all positions) */ + map: number; + /** Precision at specific positions */ + precision: { + at1: number; // Precision at position 1 + at5: number; // Precision at position 5 + at10: number; // Precision at position 10 + }; + /** Mean Reciprocal Rank (average of reciprocal ranks of first relevant item) */ + mrr: number; + /** Per-category breakdown */ + byCategory: { + [category: string]: { + ndcg: number; + map: number; + precision: { at1: number; at5: number; at10: number }; + mrr: number; + queryCount: number; + }; + }; +} + +/** + * Load relevance judgments from JSON file. + * + * @param filePath - Path to relevance judgments JSON file + * @returns Parsed judgment dataset + */ +export function loadJudgments(filePath: string): JudgmentDataset { + const content = readFileSync(filePath, "utf-8"); + return JSON.parse(content); +} + +/** + * Calculate Discounted Cumulative Gain at position k. + * + * DCG = rel[0] + sum(rel[i] / log2(i+1) for i=1 to k-1) + */ +function calculateDCG(relevanceScores: number[], k: number): number { + let dcg = 0; + + for (let i = 0; i < Math.min(k, relevanceScores.length); i++) { + const relevance = relevanceScores[i]; + if (i === 0) { + dcg += relevance; + } else { + dcg += relevance / Math.log2(i + 1); + } + } + + return dcg; +} + +/** + * Calculate Normalized Discounted Cumulative Gain at position k. + * + * NDCG normalizes DCG by the ideal DCG (DCG of perfect ranking). + * Returns value between 0 and 1, where 1 is perfect ranking. + */ +function calculateNDCG(actualRelevance: number[], idealRelevance: number[], k: number): number { + const dcg = calculateDCG(actualRelevance, k); + const idcg = calculateDCG(idealRelevance, k); + + if (idcg === 0) { + return 0; + } + + return dcg / idcg; +} + +/** + * Calculate Precision at k. + * + * Precision@k = (number of relevant items in top k) / k + */ +function calculatePrecisionAtK(relevanceScores: number[], k: number): number { + const topK = relevanceScores.slice(0, k); + const relevantCount = topK.filter((score) => score >= 2).length; // 2+ is relevant + return relevantCount / k; +} + +/** + * Calculate Average Precision for a single query. + * + * AP = sum(Precision@k * rel[k]) / number of relevant items + */ +function calculateAveragePrecision(relevanceScores: number[]): number { + const relevantCount = relevanceScores.filter((score) => score >= 2).length; + + if (relevantCount === 0) { + return 0; + } + + let sumPrecision = 0; + + for (let k = 1; k <= relevanceScores.length; k++) { + const relevance = relevanceScores[k - 1]; + if (relevance >= 2) { + // Item is relevant + const precision = calculatePrecisionAtK(relevanceScores, k); + sumPrecision += precision; + } + } + + return sumPrecision / relevantCount; +} + +/** + * Calculate Mean Reciprocal Rank for a single query. + * + * MRR = 1 / rank of first relevant item + */ +function calculateReciprocalRank(relevanceScores: number[]): number { + for (let i = 0; i < relevanceScores.length; i++) { + if (relevanceScores[i] >= 2) { + // First relevant item + return 1 / (i + 1); + } + } + return 0; // No relevant items found +} + +/** + * Evaluate reranker performance on a dataset of relevance judgments. + * + * @param reranker - The BatchedReranker instance to evaluate + * @param judgments - Array of relevance judgments + * @returns Evaluation metrics including NDCG, MAP, Precision@k, and MRR + */ +export async function evaluateReranker( + reranker: BatchedReranker, + judgments: RelevanceJudgment[], +): Promise { + logger.info({ + msg: "Starting reranker evaluation", + queryCount: judgments.length, + model: reranker.getModel(), + }); + + const allNDCG: number[] = []; + const allAP: number[] = []; + const allP1: number[] = []; + const allP5: number[] = []; + const allP10: number[] = []; + const allRR: number[] = []; + + // Per-category metrics + const categoryMetrics: { + [category: string]: { + ndcg: number[]; + ap: number[]; + p1: number[]; + p5: number[]; + p10: number[]; + rr: number[]; + }; + } = {}; + + for (const judgment of judgments) { + const { category, query, documents } = judgment; + + // Prepare candidates + const candidates = documents.map((doc) => ({ + id: doc.id, + content: doc.content, + })); + + // Ground truth: sorted by relevance (highest first) + const groundTruth = [...documents].sort((a, b) => b.relevance - a.relevance); + const idealRelevance = groundTruth.map((doc) => doc.relevance); + + // Rerank + const results = await reranker.rerank(query, candidates, documents.length); + + // Get actual relevance scores in reranked order + const actualRelevance = results.map((result) => { + const doc = documents.find((d) => d.id === result.id); + return doc?.relevance ?? 0; + }); + + // Calculate metrics for this query + const ndcg = calculateNDCG(actualRelevance, idealRelevance, documents.length); + const ap = calculateAveragePrecision(actualRelevance); + const p1 = calculatePrecisionAtK(actualRelevance, 1); + const p5 = calculatePrecisionAtK(actualRelevance, 5); + const p10 = calculatePrecisionAtK(actualRelevance, 10); + const rr = calculateReciprocalRank(actualRelevance); + + // Aggregate overall metrics + allNDCG.push(ndcg); + allAP.push(ap); + allP1.push(p1); + allP5.push(p5); + allP10.push(p10); + allRR.push(rr); + + // Aggregate per-category metrics + if (!categoryMetrics[category]) { + categoryMetrics[category] = { + ndcg: [], + ap: [], + p1: [], + p5: [], + p10: [], + rr: [], + }; + } + categoryMetrics[category].ndcg.push(ndcg); + categoryMetrics[category].ap.push(ap); + categoryMetrics[category].p1.push(p1); + categoryMetrics[category].p5.push(p5); + categoryMetrics[category].p10.push(p10); + categoryMetrics[category].rr.push(rr); + + logger.debug({ + msg: "Query evaluated", + query: query.substring(0, 50), + ndcg: ndcg.toFixed(3), + ap: ap.toFixed(3), + }); + } + + // Calculate mean metrics + const mean = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length; + + const overallMetrics: RerankerEvaluationMetrics = { + ndcg: mean(allNDCG), + map: mean(allAP), + precision: { + at1: mean(allP1), + at5: mean(allP5), + at10: mean(allP10), + }, + mrr: mean(allRR), + byCategory: {}, + }; + + // Calculate per-category means + for (const [category, metrics] of Object.entries(categoryMetrics)) { + overallMetrics.byCategory[category] = { + ndcg: mean(metrics.ndcg), + map: mean(metrics.ap), + precision: { + at1: mean(metrics.p1), + at5: mean(metrics.p5), + at10: mean(metrics.p10), + }, + mrr: mean(metrics.rr), + queryCount: metrics.ndcg.length, + }; + } + + logger.info({ + msg: "Reranker evaluation completed", + ndcg: overallMetrics.ndcg.toFixed(3), + map: overallMetrics.map.toFixed(3), + mrr: overallMetrics.mrr.toFixed(3), + p1: overallMetrics.precision.at1.toFixed(3), + p5: overallMetrics.precision.at5.toFixed(3), + p10: overallMetrics.precision.at10.toFixed(3), + }); + + return overallMetrics; +} + +/** + * Run evaluation from command line. + * + * Usage: + * bun run test/evaluate-reranker.ts [judgments-file] [tier] + * + * Example: + * bun run test/evaluate-reranker.ts test/fixtures/relevance-judgments.json fast + */ +export async function main() { + const args = process.argv.slice(2); + + const judgmentsFile = args[0] || join(__dirname, "fixtures", "relevance-judgments.json"); + const tier = (args[1] || "fast") as "fast" | "accurate" | "code"; + + logger.info({ + msg: "Loading judgments", + file: judgmentsFile, + tier, + }); + + // Load judgments + const dataset = loadJudgments(judgmentsFile); + + logger.info({ + msg: "Dataset loaded", + version: dataset.version, + queryCount: dataset.judgments.length, + }); + + // Import BatchedReranker + const { BatchedReranker } = await import("../src/services/batched-reranker"); + + // Create reranker for specified tier + const reranker = BatchedReranker.forTier(tier); + + // Run evaluation + const metrics = await evaluateReranker(reranker, dataset.judgments); + + // Print results + console.log("\n=== Reranker Evaluation Results ===\n"); + console.log(`Model: ${reranker.getModel()}`); + console.log(`Tier: ${tier}`); + console.log(`Queries: ${dataset.judgments.length}\n`); + + console.log("Overall Metrics:"); + console.log(` NDCG: ${(metrics.ndcg * 100).toFixed(2)}%`); + console.log(` MAP: ${(metrics.map * 100).toFixed(2)}%`); + console.log(` MRR: ${(metrics.mrr * 100).toFixed(2)}%`); + console.log(` P@1: ${(metrics.precision.at1 * 100).toFixed(2)}%`); + console.log(` P@5: ${(metrics.precision.at5 * 100).toFixed(2)}%`); + console.log(` P@10: ${(metrics.precision.at10 * 100).toFixed(2)}%\n`); + + console.log("By Category:"); + for (const [category, categoryMetrics] of Object.entries(metrics.byCategory)) { + console.log(` ${category} (n=${categoryMetrics.queryCount}):`); + console.log(` NDCG: ${(categoryMetrics.ndcg * 100).toFixed(2)}%`); + console.log(` MAP: ${(categoryMetrics.map * 100).toFixed(2)}%`); + console.log(` MRR: ${(categoryMetrics.mrr * 100).toFixed(2)}%`); + } + + console.log("\n=== Evaluation Complete ===\n"); +} + +// Run if called directly +if (require.main === module) { + main().catch((error) => { + console.error("Evaluation failed:", error); + process.exit(1); + }); +} diff --git a/packages/search/test/fixtures/relevance-judgments.json b/packages/search/test/fixtures/relevance-judgments.json new file mode 100644 index 0000000000000000000000000000000000000000..6e7b4722dc137e5faa49bdb7457ca04b0d22bcbb --- /dev/null +++ b/packages/search/test/fixtures/relevance-judgments.json @@ -0,0 +1,682 @@ +{ + "version": "1.0", + "description": "Relevance judgments for reranker evaluation. Relevance scale: 0=Not relevant, 1=Marginally relevant, 2=Relevant, 3=Highly relevant", + "judgments": [ + { + "category": "code", + "query": "how to implement authentication in Express", + "documents": [ + { + "id": "doc-code-1", + "content": "To implement authentication in Express, use passport.js with a local strategy. First, install passport and passport-local: npm install passport passport-local. Then configure the strategy with your user verification logic. Example: passport.use(new LocalStrategy(async (username, password, done) => { const user = await User.findOne({ username }); if (!user || !await bcrypt.compare(password, user.password)) return done(null, false); return done(null, user); }));", + "relevance": 3 + }, + { + "id": "doc-code-2", + "content": "Express.js is a minimal web application framework for Node.js. It provides a robust set of features for web and mobile applications.", + "relevance": 0 + }, + { + "id": "doc-code-3", + "content": "Authentication middleware in Express can be implemented using JWT tokens. Install jsonwebtoken and create a middleware function that verifies the token on protected routes.", + "relevance": 2 + }, + { + "id": "doc-code-4", + "content": "You can use express-session for session-based authentication. Configure it with a secret and store: app.use(session({ secret: 'your-secret', resave: false, saveUninitialized: false }));", + "relevance": 2 + } + ] + }, + { + "category": "code", + "query": "async/await error handling patterns", + "documents": [ + { + "id": "doc-code-5", + "content": "For async/await error handling, use try-catch blocks: async function fetchData() { try { const response = await fetch(url); return await response.json(); } catch (error) { console.error('Failed to fetch:', error); throw error; } }. For Express routes, use a wrapper function or async error middleware.", + "relevance": 3 + }, + { + "id": "doc-code-6", + "content": "JavaScript promises can be chained with .then() and .catch() methods for handling success and error cases.", + "relevance": 1 + }, + { + "id": "doc-code-7", + "content": "The async-await syntax is syntactic sugar over promises, making asynchronous code look synchronous. Use await keyword inside async functions.", + "relevance": 1 + }, + { + "id": "doc-code-8", + "content": "Best practice: Create a higher-order function to wrap async route handlers: const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next). Then use: router.get('/users', asyncHandler(async (req, res) => { const users = await User.find(); res.json(users); }));", + "relevance": 3 + } + ] + }, + { + "category": "code", + "query": "React hooks useEffect cleanup function", + "documents": [ + { + "id": "doc-code-9", + "content": "The useEffect cleanup function is returned from the effect and runs before the component unmounts or before the effect runs again. Example: useEffect(() => { const subscription = subscribeToData(); return () => { subscription.unsubscribe(); }; }, [dependency]);", + "relevance": 3 + }, + { + "id": "doc-code-10", + "content": "React hooks are functions that let you use state and other React features in functional components. Common hooks include useState, useEffect, and useContext.", + "relevance": 1 + }, + { + "id": "doc-code-11", + "content": "Memory leaks in React can occur when you forget to clean up subscriptions, timers, or event listeners. Always return a cleanup function from useEffect when needed.", + "relevance": 2 + }, + { + "id": "doc-code-12", + "content": "useEffect runs after every render by default. To control when it runs, pass a dependency array as the second argument. Empty array [] means it runs once on mount.", + "relevance": 1 + } + ] + }, + { + "category": "code", + "query": "TypeScript generic constraints", + "documents": [ + { + "id": "doc-code-13", + "content": "TypeScript generic constraints allow you to restrict the types that can be used with a generic. Use the 'extends' keyword: function getProperty(obj: T, key: K) { return obj[key]; }. This ensures K is a valid key of T.", + "relevance": 3 + }, + { + "id": "doc-code-14", + "content": "Generics in TypeScript provide a way to create reusable components that work with multiple types. Syntax: function identity(arg: T): T { return arg; }", + "relevance": 1 + }, + { + "id": "doc-code-15", + "content": "You can constrain generics to types with specific properties: interface HasLength { length: number; } function logLength(arg: T): void { console.log(arg.length); }", + "relevance": 3 + }, + { + "id": "doc-code-16", + "content": "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing and class-based object-oriented programming.", + "relevance": 0 + } + ] + }, + { + "category": "code", + "query": "SQL query optimization indexes", + "documents": [ + { + "id": "doc-code-17", + "content": "SQL query optimization with indexes: CREATE INDEX idx_user_email ON users(email); Use indexes on columns frequently used in WHERE, JOIN, and ORDER BY clauses. Check query performance with EXPLAIN ANALYZE. Composite indexes for multi-column queries: CREATE INDEX idx_user_name_age ON users(last_name, first_name, age);", + "relevance": 3 + }, + { + "id": "doc-code-18", + "content": "SQL indexes speed up data retrieval but slow down INSERT, UPDATE, and DELETE operations. Balance is key.", + "relevance": 2 + }, + { + "id": "doc-code-19", + "content": "SQL is a standard language for storing, manipulating and retrieving data in relational databases. Common commands include SELECT, INSERT, UPDATE, DELETE.", + "relevance": 0 + }, + { + "id": "doc-code-20", + "content": "EXPLAIN and EXPLAIN ANALYZE commands show the query execution plan, revealing if indexes are being used and identifying performance bottlenecks.", + "relevance": 2 + } + ] + }, + { + "category": "code", + "query": "Python list comprehension nested loops", + "documents": [ + { + "id": "doc-code-21", + "content": "Python list comprehension with nested loops: result = [(x, y) for x in range(3) for y in range(3)]. This creates all combinations. With conditions: result = [(x, y) for x in range(5) for y in range(5) if x != y]. Equivalent to nested for loops but more concise.", + "relevance": 3 + }, + { + "id": "doc-code-22", + "content": "List comprehensions in Python provide a concise way to create lists: squares = [x**2 for x in range(10)]", + "relevance": 1 + }, + { + "id": "doc-code-23", + "content": "Python supports nested loops like any programming language: for x in range(3): for y in range(3): print(x, y)", + "relevance": 1 + }, + { + "id": "doc-code-24", + "content": "List comprehensions are generally faster than equivalent for loops in Python due to internal optimization.", + "relevance": 1 + } + ] + }, + { + "category": "conceptual", + "query": "difference between REST and GraphQL", + "documents": [ + { + "id": "doc-concept-1", + "content": "REST vs GraphQL: REST uses multiple endpoints (one per resource) while GraphQL uses a single endpoint with flexible queries. REST can over-fetch or under-fetch data, requiring multiple requests. GraphQL allows clients to request exactly the data they need in one query. REST is resource-based, GraphQL is query-based. Example: REST needs /users/1 and /users/1/posts for user and posts, GraphQL gets both in one query: { user(id: 1) { name posts { title } } }", + "relevance": 3 + }, + { + "id": "doc-concept-2", + "content": "REST (Representational State Transfer) is an architectural style for designing networked applications using HTTP methods: GET, POST, PUT, DELETE.", + "relevance": 1 + }, + { + "id": "doc-concept-3", + "content": "GraphQL is a query language for APIs developed by Facebook. It provides a complete description of the data in your API.", + "relevance": 1 + }, + { + "id": "doc-concept-4", + "content": "Both REST and GraphQL are API design patterns used for client-server communication over HTTP. The choice depends on your use case and requirements.", + "relevance": 2 + } + ] + }, + { + "category": "conceptual", + "query": "how does event loop work in Node.js", + "documents": [ + { + "id": "doc-concept-5", + "content": "The Node.js event loop has 6 phases: timers (setTimeout/setInterval), pending callbacks, idle/prepare, poll (I/O operations), check (setImmediate), close callbacks. Each phase has a FIFO queue of callbacks. The poll phase is where most I/O callbacks are executed. process.nextTick() and promises are executed between phases. Event loop enables non-blocking I/O despite JavaScript being single-threaded.", + "relevance": 3 + }, + { + "id": "doc-concept-6", + "content": "Node.js is built on Chrome's V8 JavaScript engine and uses an event-driven, non-blocking I/O model.", + "relevance": 1 + }, + { + "id": "doc-concept-7", + "content": "The event loop allows Node.js to perform non-blocking operations by offloading operations to the system kernel whenever possible.", + "relevance": 2 + }, + { + "id": "doc-concept-8", + "content": "Callback queue, microtask queue, and macrotask queue are all part of JavaScript's concurrency model in browsers and Node.js.", + "relevance": 2 + } + ] + }, + { + "category": "conceptual", + "query": "CAP theorem distributed systems", + "documents": [ + { + "id": "doc-concept-9", + "content": "CAP theorem states distributed systems can only guarantee 2 of 3: Consistency (all nodes see same data), Availability (every request receives a response), Partition tolerance (system continues despite network partitions). In practice, partition tolerance is required, so choose between CP (consistent but may be unavailable) or AP (available but may be inconsistent). Examples: MongoDB is CP by default, Cassandra is AP.", + "relevance": 3 + }, + { + "id": "doc-concept-10", + "content": "Distributed systems are systems whose components are located on different networked computers that communicate and coordinate by passing messages.", + "relevance": 1 + }, + { + "id": "doc-concept-11", + "content": "Network partitions occur when network failures prevent some nodes from communicating with others in a distributed system.", + "relevance": 1 + }, + { + "id": "doc-concept-12", + "content": "Consistency models in distributed systems include strong consistency, eventual consistency, and causal consistency, each with different trade-offs.", + "relevance": 2 + } + ] + }, + { + "category": "conceptual", + "query": "what is closure in JavaScript", + "documents": [ + { + "id": "doc-concept-13", + "content": "A closure in JavaScript is a function that has access to variables in its outer (enclosing) lexical scope, even after the outer function has returned. Example: function outer() { let count = 0; return function inner() { count++; return count; }; } const counter = outer(); counter(); // 1, counter(); // 2. The inner function 'closes over' the count variable, maintaining access to it.", + "relevance": 3 + }, + { + "id": "doc-concept-14", + "content": "JavaScript functions are first-class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions.", + "relevance": 1 + }, + { + "id": "doc-concept-15", + "content": "Scope in JavaScript determines the accessibility of variables. There are function scope, block scope (let/const), and global scope.", + "relevance": 1 + }, + { + "id": "doc-concept-16", + "content": "Closures are commonly used for data privacy, creating factory functions, and implementing partial application or currying in functional programming.", + "relevance": 2 + } + ] + }, + { + "category": "conceptual", + "query": "microservices vs monolithic architecture", + "documents": [ + { + "id": "doc-concept-17", + "content": "Microservices vs Monolithic: Monolithic apps are single unified units where all components are interconnected and interdependent. Microservices break apps into small, independent services that communicate via APIs. Microservices benefits: independent deployment, technology flexibility, fault isolation, easier scaling. Drawbacks: increased complexity, network latency, distributed system challenges. Monolithic benefits: simpler development and deployment initially, easier testing, no network overhead. Choose based on team size, complexity, and scaling needs.", + "relevance": 3 + }, + { + "id": "doc-concept-18", + "content": "Software architecture patterns define the overall structure of software systems and how components interact with each other.", + "relevance": 1 + }, + { + "id": "doc-concept-19", + "content": "Service-oriented architecture (SOA) predates microservices and shares some concepts but differs in implementation and scope.", + "relevance": 1 + }, + { + "id": "doc-concept-20", + "content": "Domain-driven design (DDD) principles are often used when designing microservices to define bounded contexts and service boundaries.", + "relevance": 2 + } + ] + }, + { + "category": "api", + "query": "how to use Array.reduce in JavaScript", + "documents": [ + { + "id": "doc-api-1", + "content": "Array.reduce() executes a reducer function on each array element, resulting in a single output value. Syntax: array.reduce((accumulator, currentValue, currentIndex, array) => { return accumulator; }, initialValue). Example sum: [1,2,3,4].reduce((sum, num) => sum + num, 0) // 10. Example grouping: items.reduce((acc, item) => { acc[item.category] = acc[item.category] || []; acc[item.category].push(item); return acc; }, {})", + "relevance": 3 + }, + { + "id": "doc-api-2", + "content": "JavaScript Array methods include map, filter, reduce, forEach, find, some, every, and more. These are higher-order functions for array manipulation.", + "relevance": 1 + }, + { + "id": "doc-api-3", + "content": "The accumulator in reduce() is the value returned from the previous iteration. The initial value is optional but recommended to avoid errors on empty arrays.", + "relevance": 2 + }, + { + "id": "doc-api-4", + "content": "Functional programming in JavaScript emphasizes pure functions, immutability, and function composition. Array methods like reduce are key tools.", + "relevance": 1 + } + ] + }, + { + "category": "api", + "query": "Fetch API error handling", + "documents": [ + { + "id": "doc-api-5", + "content": "Fetch API error handling: fetch() only rejects on network errors, not HTTP errors (4xx, 5xx). Check response.ok: fetch(url).then(response => { if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return response.json(); }).catch(error => console.error('Fetch error:', error)). For timeout: use AbortController with setTimeout.", + "relevance": 3 + }, + { + "id": "doc-api-6", + "content": "The Fetch API provides a JavaScript interface for accessing and manipulating HTTP requests and responses. It returns a Promise.", + "relevance": 1 + }, + { + "id": "doc-api-7", + "content": "HTTP status codes: 2xx (success), 3xx (redirection), 4xx (client errors), 5xx (server errors). Common codes: 200 OK, 404 Not Found, 500 Internal Server Error.", + "relevance": 1 + }, + { + "id": "doc-api-8", + "content": "Alternative to fetch: axios library provides automatic error handling for HTTP errors and has a simpler API. It throws on any error status code.", + "relevance": 2 + } + ] + }, + { + "category": "api", + "query": "React Router useNavigate hook", + "documents": [ + { + "id": "doc-api-9", + "content": "useNavigate hook (React Router v6+) enables programmatic navigation. Usage: const navigate = useNavigate(); navigate('/path'); navigate('/path', { replace: true }); navigate(-1) // go back; navigate(2) // go forward 2 pages. Pass state: navigate('/path', { state: { from: 'login' } }). Replaces useHistory from v5.", + "relevance": 3 + }, + { + "id": "doc-api-10", + "content": "React Router is a standard library for routing in React applications. It keeps your UI in sync with the URL.", + "relevance": 1 + }, + { + "id": "doc-api-11", + "content": "React Router v6 introduced several breaking changes from v5, including replacing Switch with Routes and useHistory with useNavigate.", + "relevance": 2 + }, + { + "id": "doc-api-12", + "content": "Navigation in single-page applications can be done programmatically (using functions) or declaratively (using Link components).", + "relevance": 1 + } + ] + }, + { + "category": "api", + "query": "Express middleware order and next()", + "documents": [ + { + "id": "doc-api-13", + "content": "Express middleware executes in the order defined. Each middleware must call next() to pass control to the next middleware or send a response. Order matters: app.use(cors()); app.use(express.json()); app.use(auth); Routes are also middleware. Error-handling middleware has 4 parameters: (err, req, res, next) and must be defined last. If next(err) is called, it skips to error middleware.", + "relevance": 3 + }, + { + "id": "doc-api-14", + "content": "Express.js middleware functions have access to request (req), response (res), and next function. They can execute code, modify req/res, end the request, or call next().", + "relevance": 2 + }, + { + "id": "doc-api-15", + "content": "Common Express middleware includes body-parser, cors, helmet for security, morgan for logging, and serve-static for serving files.", + "relevance": 1 + }, + { + "id": "doc-api-16", + "content": "The Express request-response cycle ends when a middleware sends a response using res.send(), res.json(), res.render(), etc.", + "relevance": 1 + } + ] + }, + { + "category": "api", + "query": "MongoDB aggregation pipeline", + "documents": [ + { + "id": "doc-api-17", + "content": "MongoDB aggregation pipeline processes documents through stages. Common stages: $match (filter), $group (group by field), $project (reshape documents), $sort, $limit, $lookup (join), $unwind (deconstruct arrays). Example: db.orders.aggregate([{ $match: { status: 'completed' }}, { $group: { _id: '$customerId', total: { $sum: '$amount' }}}, { $sort: { total: -1 }}, { $limit: 10 }]). Each stage transforms documents, output becomes input for next stage.", + "relevance": 3 + }, + { + "id": "doc-api-18", + "content": "MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents. It's designed for scalability and developer agility.", + "relevance": 0 + }, + { + "id": "doc-api-19", + "content": "Aggregation frameworks in databases allow for complex data processing and analysis beyond simple CRUD operations.", + "relevance": 1 + }, + { + "id": "doc-api-20", + "content": "The $lookup stage in MongoDB aggregation is similar to SQL JOIN, allowing you to combine documents from different collections.", + "relevance": 2 + } + ] + }, + { + "category": "debugging", + "query": "debugging CORS errors in development", + "documents": [ + { + "id": "doc-debug-1", + "content": "CORS errors occur when browser blocks requests from different origins. Solutions: 1) Backend: Install cors middleware: npm i cors; app.use(cors({ origin: 'http://localhost:3000', credentials: true })); 2) Development proxy: In package.json add \"proxy\": \"http://localhost:5000\" or use http-proxy-middleware. 3) Check Access-Control-Allow-Origin header in response. Browser console shows specific CORS error (missing header, credentials, method not allowed).", + "relevance": 3 + }, + { + "id": "doc-debug-2", + "content": "CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers to restrict cross-origin HTTP requests initiated from scripts.", + "relevance": 1 + }, + { + "id": "doc-debug-3", + "content": "Same-origin policy is a critical security mechanism that restricts how a document or script from one origin can interact with resources from another origin.", + "relevance": 1 + }, + { + "id": "doc-debug-4", + "content": "Preflight requests (OPTIONS) are sent by browsers before certain CORS requests to check if the actual request is safe to send.", + "relevance": 2 + } + ] + }, + { + "category": "debugging", + "query": "memory leak detection in Node.js", + "documents": [ + { + "id": "doc-debug-5", + "content": "Detect Node.js memory leaks: 1) Use --inspect flag: node --inspect app.js, open chrome://inspect, take heap snapshots over time, compare snapshots in Memory tab. 2) clinic.js: npm i -g clinic; clinic doctor -- node app.js. 3) Process monitoring: process.memoryUsage() to log heap usage. Common causes: global variables, event listeners not removed, closures holding references, timers not cleared. Look for detached DOM nodes, abandoned callbacks, growing arrays.", + "relevance": 3 + }, + { + "id": "doc-debug-6", + "content": "Memory leaks occur when allocated memory is not freed after it's no longer needed, gradually consuming available memory until the program crashes.", + "relevance": 1 + }, + { + "id": "doc-debug-7", + "content": "Node.js uses V8's garbage collector which automatically frees memory for objects that are no longer referenced.", + "relevance": 1 + }, + { + "id": "doc-debug-8", + "content": "Tools for profiling Node.js applications include Chrome DevTools, clinic.js, 0x for flame graphs, and autocannon for load testing.", + "relevance": 2 + } + ] + }, + { + "category": "debugging", + "query": "fixing TypeError: Cannot read property of undefined", + "documents": [ + { + "id": "doc-debug-9", + "content": "TypeError: Cannot read property 'x' of undefined means you're trying to access property 'x' on undefined. Solutions: 1) Optional chaining: obj?.prop?.subprop instead of obj.prop.subprop. 2) Check existence: if (obj && obj.prop) { ... }. 3) Default values: const value = obj?.prop ?? 'default'. 4) Nullish coalescing: const x = obj?.prop ?? fallback. Check API response structure, ensure data is loaded before accessing, use TypeScript for compile-time checks.", + "relevance": 3 + }, + { + "id": "doc-debug-10", + "content": "JavaScript TypeError is thrown when an operation could not be performed because a value is not of the expected type.", + "relevance": 1 + }, + { + "id": "doc-debug-11", + "content": "undefined in JavaScript means a variable has been declared but not assigned a value, or a property doesn't exist on an object.", + "relevance": 1 + }, + { + "id": "doc-debug-12", + "content": "Defensive programming techniques include input validation, null checks, default values, and graceful error handling to prevent runtime errors.", + "relevance": 2 + } + ] + }, + { + "category": "debugging", + "query": "React useState not updating immediately", + "documents": [ + { + "id": "doc-debug-13", + "content": "React useState updates are asynchronous and batched. The state variable doesn't update immediately after setState. Solutions: 1) Use functional update form: setCount(prev => prev + 1) for updates based on previous state. 2) Use useEffect to respond to state changes: useEffect(() => { console.log(count); }, [count]). 3) Multiple setState calls in same render are batched. Don't rely on state value immediately after setState. If you need the new value, calculate it: const newCount = count + 1; setCount(newCount); use newCount.", + "relevance": 3 + }, + { + "id": "doc-debug-14", + "content": "React useState is a Hook that lets you add state to functional components. It returns an array with current state and a setter function.", + "relevance": 1 + }, + { + "id": "doc-debug-15", + "content": "React batches state updates for performance, meaning multiple setState calls in the same event handler are processed together in a single re-render.", + "relevance": 2 + }, + { + "id": "doc-debug-16", + "content": "React 18 introduced automatic batching for all updates, including those in promises, setTimeout, and native event handlers.", + "relevance": 1 + } + ] + }, + { + "category": "debugging", + "query": "SQL query running slow performance issues", + "documents": [ + { + "id": "doc-debug-17", + "content": "SQL query slow? Diagnose and fix: 1) Use EXPLAIN ANALYZE to see execution plan. 2) Add indexes on WHERE, JOIN, ORDER BY columns. 3) Avoid SELECT *, only fetch needed columns. 4) Use LIMIT for pagination. 5) Check for table scans (bad), want index scans (good). 6) Optimize JOINs: ensure foreign keys have indexes. 7) Use UNION ALL instead of UNION if duplicates ok. 8) Check for N+1 queries, use JOINs or batch loading. 9) Denormalize for read-heavy workloads. 10) Consider query result caching.", + "relevance": 3 + }, + { + "id": "doc-debug-18", + "content": "Database performance tuning involves optimizing queries, indexes, schema design, and configuration to improve response times.", + "relevance": 2 + }, + { + "id": "doc-debug-19", + "content": "Table scans are expensive operations where the database reads every row. Indexes help avoid full table scans by providing quick lookup paths.", + "relevance": 2 + }, + { + "id": "doc-debug-20", + "content": "EXPLAIN shows the query execution plan without running the query, while EXPLAIN ANALYZE actually executes it and shows real timing data.", + "relevance": 2 + } + ] + }, + { + "category": "general", + "query": "best practices for API versioning", + "documents": [ + { + "id": "doc-general-1", + "content": "API versioning strategies: 1) URI versioning: /api/v1/users (most common, clear). 2) Header versioning: Accept: application/vnd.api.v1+json (cleaner URLs). 3) Query parameter: /api/users?version=1 (flexible). Best practices: Use semantic versioning, support old versions with deprecation timeline, version breaking changes only, document changes clearly, use API gateway for routing. Don't version too frequently. Stripe and GitHub use URI versioning with date-based versions.", + "relevance": 3 + }, + { + "id": "doc-general-2", + "content": "API design involves creating interfaces that are easy to use, understand, and maintain. Good APIs are consistent, well-documented, and follow standards.", + "relevance": 1 + }, + { + "id": "doc-general-3", + "content": "Breaking changes in APIs include removing endpoints, changing response structure, requiring new required fields, or changing data types.", + "relevance": 2 + }, + { + "id": "doc-general-4", + "content": "Semantic versioning uses MAJOR.MINOR.PATCH format where MAJOR is for breaking changes, MINOR for backwards-compatible features, PATCH for bug fixes.", + "relevance": 2 + } + ] + }, + { + "category": "general", + "query": "git rebase vs merge when to use", + "documents": [ + { + "id": "doc-general-5", + "content": "Git rebase vs merge: Merge creates a merge commit, preserving branch history (branching structure visible). Rebase moves commits to new base, creating linear history (cleaner but rewrites history). Use merge for: public branches, preserving exact history, feature branches merged to main. Use rebase for: updating feature branch with main changes, cleaning up local commits before PR, maintaining linear history. Golden rule: NEVER rebase public/shared branches. Workflow: rebase locally, merge to main. Example: git checkout feature; git rebase main; git checkout main; git merge feature.", + "relevance": 3 + }, + { + "id": "doc-general-6", + "content": "Git is a distributed version control system for tracking changes in source code. It enables collaboration and maintains project history.", + "relevance": 0 + }, + { + "id": "doc-general-7", + "content": "Merge conflicts occur when Git cannot automatically resolve differences between branches. They must be resolved manually.", + "relevance": 1 + }, + { + "id": "doc-general-8", + "content": "Git workflow strategies include Git Flow, GitHub Flow, and Trunk-Based Development, each with different branching patterns.", + "relevance": 1 + } + ] + }, + { + "category": "general", + "query": "difference between unit and integration tests", + "documents": [ + { + "id": "doc-general-9", + "content": "Unit vs Integration tests: Unit tests test individual functions/components in isolation, mocking dependencies. Fast, numerous (70-80% of tests), catch logic errors early. Example: testing a pure function with different inputs. Integration tests test how multiple components work together with real dependencies. Slower, fewer (20-30%), catch interface issues. Example: testing API endpoint with real database. Use test pyramid: many unit tests, some integration tests, few E2E tests. Jest/Mocha for unit, Supertest/TestContainers for integration.", + "relevance": 3 + }, + { + "id": "doc-general-10", + "content": "Software testing ensures code quality and correctness. Types include unit, integration, end-to-end, performance, and security testing.", + "relevance": 1 + }, + { + "id": "doc-general-11", + "content": "Test-driven development (TDD) is a methodology where tests are written before implementation code. The cycle is: write test, fail, implement, pass, refactor.", + "relevance": 1 + }, + { + "id": "doc-general-12", + "content": "Mocking and stubbing are techniques used in testing to replace real dependencies with controlled test doubles.", + "relevance": 2 + } + ] + }, + { + "category": "general", + "query": "OAuth 2.0 flow explained", + "documents": [ + { + "id": "doc-general-13", + "content": "OAuth 2.0 authorization flow: 1) Client redirects user to authorization server with client_id, redirect_uri, scope. 2) User authenticates and grants permission. 3) Auth server redirects back with authorization code. 4) Client exchanges code for access token (with client_secret, server-side only). 5) Client uses access token to access protected resources. Grant types: Authorization Code (web apps), Implicit (deprecated), Client Credentials (machine-to-machine), PKCE (mobile/SPA). Refresh tokens for long-lived access. OAuth is for authorization, not authentication (use OpenID Connect for auth).", + "relevance": 3 + }, + { + "id": "doc-general-14", + "content": "OAuth 2.0 is an authorization framework that enables applications to obtain limited access to user accounts on HTTP services.", + "relevance": 2 + }, + { + "id": "doc-general-15", + "content": "Access tokens are credentials used to access protected resources. They should be short-lived and stored securely.", + "relevance": 1 + }, + { + "id": "doc-general-16", + "content": "OpenID Connect is an authentication layer built on top of OAuth 2.0, adding identity verification through ID tokens.", + "relevance": 2 + } + ] + }, + { + "category": "general", + "query": "Docker vs virtual machines", + "documents": [ + { + "id": "doc-general-17", + "content": "Docker vs VMs: VMs virtualize hardware, include full OS, managed by hypervisor. Heavy (GBs), slow startup (minutes), strong isolation. Docker uses containerization, shares host OS kernel, lightweight (MBs), fast startup (seconds), process-level isolation. Containers are portable across any host running Docker. VMs better for: running different OS, maximum isolation, running legacy apps. Containers better for: microservices, CI/CD, dev/prod parity, resource efficiency. Can combine: run Docker inside VMs for extra isolation.", + "relevance": 3 + }, + { + "id": "doc-general-18", + "content": "Virtualization technology allows multiple operating systems to run on a single physical machine by abstracting hardware resources.", + "relevance": 1 + }, + { + "id": "doc-general-19", + "content": "Docker is a platform for developing, shipping, and running applications in containers. It packages applications with dependencies.", + "relevance": 1 + }, + { + "id": "doc-general-20", + "content": "Container orchestration platforms like Kubernetes manage deployment, scaling, and networking of containerized applications.", + "relevance": 2 + } + ] + } + ] +} diff --git a/packages/search/tsconfig.json b/packages/search/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..641a81dc7930b9224a4c9e017be08450bf43e9f0 --- /dev/null +++ b/packages/search/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@engram/tsconfig/base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "baseUrl": "." + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/storage/README.md b/packages/storage/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6d73024d69ef702a88f96c1f56e4418152ec74a4 --- /dev/null +++ b/packages/storage/README.md @@ -0,0 +1,142 @@ +# @engram/storage + +Unified interfaces and implementations for all storage backends. + +## Overview + +Decouples application code from infrastructure via clean interfaces, enabling easy swapping of storage backends and comprehensive dependency injection for testing. + +## Installation + +```bash +npm install @engram/storage +``` + +## Interfaces + +### GraphClient + +```typescript +import type { GraphClient } from "@engram/storage"; + +interface GraphClient { + connect(): Promise; + disconnect(): Promise; + query(cypher: string, params?: Record): Promise; +} +``` + +### MessageClient + +```typescript +import type { MessageClient, Producer, Consumer } from "@engram/storage"; + +interface Producer { + send(topic: string, messages: Message[]): Promise; +} + +interface Consumer { + subscribe(topics: string[]): Promise; + run(handler: MessageHandler): Promise; +} +``` + +### BlobStore + +```typescript +import type { BlobStore } from "@engram/storage"; + +interface BlobStore { + save(content: Buffer): Promise; // Returns content hash + load(hash: string): Promise; + exists(hash: string): Promise; +} +``` + +### RedisPublisher + +```typescript +import type { RedisPublisher } from "@engram/storage"; + +interface RedisPublisher { + publish(channel: string, message: string): Promise; + subscribe(channel: string, handler: MessageHandler): Promise; +} +``` + +## Implementations + +### FalkorDB (Graph) + +```typescript +import { createFalkorClient } from "@engram/storage/falkor"; + +const client = await createFalkorClient({ + url: "redis://localhost:6379", + graph: "engram", +}); + +const results = await client.query( + "MATCH (s:Session) RETURN s LIMIT 10" +); +``` + +### Kafka/Redpanda (Messaging) + +```typescript +import { createKafkaClient } from "@engram/storage/kafka"; + +const kafka = createKafkaClient({ + brokers: ["localhost:19092"], + clientId: "my-service", +}); + +const producer = kafka.producer(); +await producer.send("events", [{ value: JSON.stringify(event) }]); + +const consumer = kafka.consumer({ groupId: "my-group" }); +await consumer.subscribe(["events"]); +await consumer.run(async (message) => { + console.log(message.value); +}); +``` + +### Blob Storage + +```typescript +import { createBlobStore } from "@engram/storage/blob"; + +// Google Cloud Storage +const gcsStore = createBlobStore({ + type: "gcs", + bucket: "my-bucket", +}); + +// Local filesystem +const fsStore = createBlobStore({ + type: "filesystem", + directory: "./data", +}); +``` + +### Redis + +```typescript +import { createRedisClient } from "@engram/storage/redis"; + +const redis = await createRedisClient({ + url: "redis://localhost:6379", +}); + +await redis.publish("updates", JSON.stringify({ type: "event" })); +``` + +## Consumer Utilities + +```typescript +import { checkConsumerReadiness } from "@engram/storage"; + +const ready = await checkConsumerReadiness(consumer, { + timeout: 5000, +}); +``` diff --git a/packages/storage/package.json b/packages/storage/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a317faa3deb8af5246424c8a2b38a8e7a059ac1c --- /dev/null +++ b/packages/storage/package.json @@ -0,0 +1,28 @@ +{ + "name": "@engram/storage", + "version": "0.0.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./falkor": "./src/falkor.ts", + "./kafka": "./src/kafka.ts", + "./blob": "./src/blob.ts", + "./redis": "./src/redis.ts" + }, + "devDependencies": { + "typescript": "^5.9.3", + "@types/node": "^24.10.1", + "@engram/tsconfig": "*" + }, + "dependencies": { + "@google-cloud/storage": "^7.14.0", + "falkordb": "^6.3.1", + "redis": "^5.10.0" + }, + "scripts": { + "build": "echo 'Build success'", + "typecheck": "tsc --noEmit" + } +} diff --git a/packages/storage/src/blob.test.ts b/packages/storage/src/blob.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..efce7e14a30819f5bed3f1d037b8a1f86a87d086 --- /dev/null +++ b/packages/storage/src/blob.test.ts @@ -0,0 +1,228 @@ +import * as fs from "node:fs/promises"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createBlobStore, FileSystemBlobStore, GCSBlobStore } from "./blob"; + +// Mock functions for GCS operations +const mockSave = vi.fn(); +const mockDownload = vi.fn(); +const mockExists = vi.fn(); +const mockFile = vi.fn(() => ({ + save: mockSave, + download: mockDownload, + exists: mockExists, +})); +const mockBucket = vi.fn(() => ({ + file: mockFile, +})); + +// Mock the @google-cloud/storage module +vi.mock("@google-cloud/storage", () => ({ + Storage: vi.fn(() => ({ + bucket: mockBucket, + })), +})); + +describe("Blob Storage", () => { + const testDir = `/tmp/engram-blob-test-${Date.now()}`; + + afterEach(async () => { + // Clean up test directory + try { + await fs.rm(testDir, { recursive: true }); + } catch { + // Directory may not exist, ignore + } + }); + + describe("FileSystemBlobStore", () => { + it("should save content and return file URI", async () => { + const store = new FileSystemBlobStore(testDir); + const content = "Hello World"; + const uri = await store.save(content); + + expect(uri).toMatch(/^file:\/\//); + expect(uri).toContain(testDir); + }); + + it("should generate deterministic hash-based filenames", async () => { + const store = new FileSystemBlobStore(testDir); + + const uri1 = await store.save("same content"); + const uri2 = await store.save("same content"); + + expect(uri1).toBe(uri2); + }); + + it("should generate different filenames for different content", async () => { + const store = new FileSystemBlobStore(testDir); + + const uri1 = await store.save("content 1"); + const uri2 = await store.save("content 2"); + + expect(uri1).not.toBe(uri2); + }); + + it("should read saved content", async () => { + const store = new FileSystemBlobStore(testDir); + const content = "hello world"; + + const uri = await store.save(content); + const readContent = await store.read(uri); + + expect(readContent).toBe(content); + }); + + it("should create directory if it does not exist", async () => { + const nestedDir = `${testDir}/nested/dir`; + const store = new FileSystemBlobStore(nestedDir); + + await store.save("content"); + + const stat = await fs.stat(nestedDir); + expect(stat.isDirectory()).toBe(true); + }); + + it("should throw on invalid URI scheme", async () => { + const store = new FileSystemBlobStore(testDir); + + await expect(store.read("gs://bucket/hash")).rejects.toThrow("Invalid URI scheme"); + }); + + it("should throw on non-existent file read", async () => { + const store = new FileSystemBlobStore(testDir); + + await expect(store.read("file:///nonexistent/file")).rejects.toThrow(); + }); + + it("should handle empty content", async () => { + const store = new FileSystemBlobStore(testDir); + + const uri = await store.save(""); + const content = await store.read(uri); + + expect(content).toBe(""); + }); + + it("should handle large content", async () => { + const store = new FileSystemBlobStore(testDir); + const largeContent = "x".repeat(100000); + + const uri = await store.save(largeContent); + const content = await store.read(uri); + + expect(content).toBe(largeContent); + }); + + it("should handle unicode content", async () => { + const store = new FileSystemBlobStore(testDir); + const unicodeContent = "Hello World! Special chars"; + + const uri = await store.save(unicodeContent); + const content = await store.read(uri); + + expect(content).toBe(unicodeContent); + }); + + it("should handle JSON content", async () => { + const store = new FileSystemBlobStore(testDir); + const jsonContent = JSON.stringify({ key: "value", nested: { array: [1, 2, 3] } }); + + const uri = await store.save(jsonContent); + const content = await store.read(uri); + + expect(JSON.parse(content)).toEqual({ key: "value", nested: { array: [1, 2, 3] } }); + }); + }); + + describe("GCSBlobStore", () => { + beforeEach(() => { + vi.clearAllMocks(); + // Reset default mock implementations + mockSave.mockResolvedValue(undefined); + mockExists.mockResolvedValue([true]); + mockDownload.mockResolvedValue([Buffer.from("test content")]); + }); + + it("should generate GCS URI on save", async () => { + const store = new GCSBlobStore("test-bucket"); + + const uri = await store.save("test content"); + + expect(uri).toMatch(/^gs:\/\/test-bucket\/[a-f0-9]+$/); + expect(mockSave).toHaveBeenCalledWith("test content", { contentType: "application/json" }); + }); + + it("should generate deterministic hash-based filenames", async () => { + const store = new GCSBlobStore("test-bucket"); + + const uri1 = await store.save("same content"); + const uri2 = await store.save("same content"); + + expect(uri1).toBe(uri2); + }); + + it("should throw on invalid URI scheme", async () => { + const store = new GCSBlobStore("test-bucket"); + + await expect(store.read("file:///local/file")).rejects.toThrow("Invalid URI scheme"); + }); + + it("should throw on invalid GCS URI format", async () => { + const store = new GCSBlobStore("test-bucket"); + + await expect(store.read("gs://bucket-only")).rejects.toThrow("Invalid GCS URI format"); + }); + + it("should throw StorageError on GCS read failure", async () => { + const store = new GCSBlobStore("test-bucket"); + mockExists.mockRejectedValueOnce(new Error("Network error")); + + await expect(store.read("gs://test-bucket/somefile")).rejects.toThrow( + "Failed to read blob from GCS", + ); + }); + + it("should throw StorageError on GCS save failure", async () => { + const store = new GCSBlobStore("test-bucket"); + mockSave.mockRejectedValueOnce(new Error("Network error")); + + await expect(store.save("test content")).rejects.toThrow("Failed to upload blob to GCS"); + }); + + it("should throw StorageError when blob not found", async () => { + const store = new GCSBlobStore("test-bucket"); + mockExists.mockResolvedValueOnce([false]); + + await expect(store.read("gs://test-bucket/somefile")).rejects.toThrow("Blob not found"); + }); + + it("should read content successfully", async () => { + const store = new GCSBlobStore("test-bucket"); + mockExists.mockResolvedValueOnce([true]); + mockDownload.mockResolvedValueOnce([Buffer.from("loaded content")]); + + const content = await store.read("gs://test-bucket/somefile"); + + expect(content).toBe("loaded content"); + }); + }); + + describe("Factory", () => { + it("should create FS store by default", () => { + const store = createBlobStore(); + expect(store.save).toBeDefined(); + expect((store as any).basePath).toBeDefined(); + }); + + it("should create FS store when type is fs", () => { + const store = createBlobStore("fs"); + expect((store as any).basePath).toBeDefined(); + }); + + it("should create GCS store when requested", () => { + const store = createBlobStore("gcs"); + expect(store.save).toBeDefined(); + expect((store as any).bucket).toBeDefined(); + }); + }); +}); diff --git a/packages/storage/src/blob.ts b/packages/storage/src/blob.ts new file mode 100644 index 0000000000000000000000000000000000000000..1dc21d4db536df46f020ed9cc1c59c3a638bf1f0 --- /dev/null +++ b/packages/storage/src/blob.ts @@ -0,0 +1,196 @@ +import * as crypto from "node:crypto"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { ErrorCodes, StorageError } from "@engram/common"; +import type { BlobStore } from "./interfaces"; + +// Re-export the interface for backward compatibility +export type { BlobStore } from "./interfaces"; + +export class FileSystemBlobStore implements BlobStore { + private basePath: string; + + constructor(basePath: string) { + this.basePath = basePath; + } + + async save(content: string | Buffer): Promise { + const hash = crypto.createHash("sha256").update(content).digest("hex"); + const filePath = path.join(this.basePath, hash); + // Ensure directory exists + await fs.mkdir(this.basePath, { recursive: true }); + await fs.writeFile(filePath, content, "utf-8"); + return `file://${filePath}`; + } + + async load(uri: string): Promise { + if (!uri.startsWith("file://")) { + throw new Error(`Invalid URI scheme for FileSystemBlobStore: ${uri}`); + } + + // Extract and decode the file path from URI + let filePath = uri.slice(7); // Remove 'file://' + filePath = decodeURIComponent(filePath); + + // Get just the filename (should be a SHA-256 hash) + const filename = path.basename(filePath); + + // Validate filename format (must be a 64-character hex string) + if (!/^[a-f0-9]{64}$/.test(filename)) { + throw new StorageError( + `Invalid blob filename format: ${filename}`, + ErrorCodes.STORAGE_INVALID_PATH, + uri, + undefined, + "read", + ); + } + + // Construct safe path using only the validated filename + const safePath = path.join(this.basePath, filename); + const resolvedPath = path.resolve(safePath); + const resolvedBase = path.resolve(this.basePath); + + // Double-check containment (defense in depth) + if (!resolvedPath.startsWith(resolvedBase + path.sep) && resolvedPath !== resolvedBase) { + throw new StorageError( + `Path traversal detected in URI: ${uri}`, + ErrorCodes.STORAGE_INVALID_PATH, + uri, + undefined, + "read", + ); + } + + return fs.readFile(resolvedPath, "utf-8"); + } + + /** + * @deprecated Use load(uri) instead + */ + async read(uri: string): Promise { + return this.load(uri); + } +} + +export class GCSBlobStore implements BlobStore { + private bucket: string; + private storage: unknown; // Lazy loaded @google-cloud/storage client + + constructor(bucket: string) { + this.bucket = bucket; + } + + /** + * Lazily initialize the Google Cloud Storage client. + * Uses Application Default Credentials or GOOGLE_APPLICATION_CREDENTIALS env var. + */ + private async getStorage() { + if (!this.storage) { + // Dynamic import to avoid bundling issues and make GCS optional + const { Storage } = await import("@google-cloud/storage"); + this.storage = new Storage(); + } + return this.storage as { + bucket: (name: string) => { + file: (name: string) => { + save: (content: string, options?: { contentType?: string }) => Promise; + download: () => Promise<[Buffer]>; + exists: () => Promise<[boolean]>; + }; + }; + }; + } + + async save(content: string | Buffer): Promise { + const hash = crypto.createHash("sha256").update(content).digest("hex"); + const fileName = hash; + const contentStr = typeof content === "string" ? content : content.toString("utf-8"); + const uri = `gs://${this.bucket}/${fileName}`; + + try { + const storage = await this.getStorage(); + const bucket = storage.bucket(this.bucket); + const file = bucket.file(fileName); + + await file.save(contentStr, { + contentType: "application/json", + }); + + return uri; + } catch (error) { + // Throw StorageError instead of returning stub URI - silent failures are dangerous + const cause = error instanceof Error ? error : undefined; + throw new StorageError( + `Failed to upload blob to GCS: ${cause?.message || "unknown error"}`, + ErrorCodes.STORAGE_WRITE_FAILED, + uri, + cause, + "write", + ); + } + } + + async load(uri: string): Promise { + if (!uri.startsWith("gs://")) { + throw new Error(`Invalid URI scheme for GCSBlobStore: ${uri}`); + } + + // Parse gs://bucket/filename + const withoutScheme = uri.slice(5); // Remove 'gs://' + const slashIndex = withoutScheme.indexOf("/"); + if (slashIndex === -1) { + throw new Error(`Invalid GCS URI format: ${uri}`); + } + const bucketName = withoutScheme.slice(0, slashIndex); + const fileName = withoutScheme.slice(slashIndex + 1); + + try { + const storage = await this.getStorage(); + const bucket = storage.bucket(bucketName); + const file = bucket.file(fileName); + + const [exists] = await file.exists(); + if (!exists) { + throw new StorageError( + `Blob not found: ${uri}`, + ErrorCodes.STORAGE_NOT_FOUND, + uri, + undefined, + "read", + ); + } + + const [contents] = await file.download(); + return contents.toString("utf-8"); + } catch (error) { + // Re-throw StorageErrors as-is + if (error instanceof StorageError) { + throw error; + } + // Throw StorageError instead of returning empty string - silent failures are dangerous + const cause = error instanceof Error ? error : undefined; + throw new StorageError( + `Failed to read blob from GCS: ${cause?.message || "unknown error"}`, + ErrorCodes.STORAGE_READ_FAILED, + uri, + cause, + "read", + ); + } + } + + /** + * @deprecated Use load(uri) instead + */ + async read(uri: string): Promise { + return this.load(uri); + } +} + +export const createBlobStore = (type: "fs" | "gcs" = "fs"): BlobStore => { + if (type === "gcs") { + return new GCSBlobStore(process.env.GCS_BUCKET || "engram-blobs"); + } + return new FileSystemBlobStore(process.env.BLOB_STORAGE_PATH || "./data/blobs"); +}; diff --git a/packages/storage/src/consumer-readiness.ts b/packages/storage/src/consumer-readiness.ts new file mode 100644 index 0000000000000000000000000000000000000000..b604757958779d52aab079ccb4b668da19287cd0 --- /dev/null +++ b/packages/storage/src/consumer-readiness.ts @@ -0,0 +1,301 @@ +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const Kafka = require("@confluentinc/kafka-javascript"); + +/** + * Consumer group state from Kafka Admin API. + * Maps to librdkafka ConsumerGroupStates. + */ +export const ConsumerGroupStates = { + UNKNOWN: 0, + PREPARING_REBALANCE: 1, + COMPLETING_REBALANCE: 2, + STABLE: 3, + DEAD: 4, + EMPTY: 5, +} as const; + +export type ConsumerGroupState = (typeof ConsumerGroupStates)[keyof typeof ConsumerGroupStates]; + +/** + * Result of checking a consumer group's readiness. + */ +export interface ConsumerGroupStatus { + groupId: string; + state: ConsumerGroupState; + stateName: string; + memberCount: number; + isReady: boolean; +} + +/** + * Configuration for waitForConsumers. + */ +export interface WaitForConsumersConfig { + /** Consumer group IDs to wait for */ + groupIds: string[]; + /** Kafka broker addresses (default: localhost:19092) */ + brokers?: string; + /** Maximum time to wait in ms (default: 60000) */ + timeoutMs?: number; + /** Polling interval in ms (default: 2000) */ + pollIntervalMs?: number; + /** Minimum number of members required per group (default: 1) */ + minMembers?: number; + /** Optional logger function */ + logger?: (message: string) => void; +} + +/** + * Result of waitForConsumers. + */ +export interface WaitResult { + success: boolean; + groups: ConsumerGroupStatus[]; + elapsedMs: number; + error?: string; +} + +// Admin client wrapper type +type AdminClient = { + connect: () => void; + disconnect: () => void; + listGroups: ( + options: Record, + callback: (err: Error | null, groups: unknown[]) => void, + ) => void; + describeGroups: ( + groupIds: string[], + options: Record, + callback: (err: Error | null, descriptions: GroupDescription[]) => void, + ) => void; +}; + +interface GroupDescription { + groupId: string; + state: ConsumerGroupState; + members: unknown[]; + error?: { message: string }; +} + +/** + * Get the string name for a consumer group state. + */ +function getStateName(state: ConsumerGroupState): string { + const names: Record = { + [ConsumerGroupStates.UNKNOWN]: "UNKNOWN", + [ConsumerGroupStates.PREPARING_REBALANCE]: "PREPARING_REBALANCE", + [ConsumerGroupStates.COMPLETING_REBALANCE]: "COMPLETING_REBALANCE", + [ConsumerGroupStates.STABLE]: "STABLE", + [ConsumerGroupStates.DEAD]: "DEAD", + [ConsumerGroupStates.EMPTY]: "EMPTY", + }; + return names[state] ?? "UNKNOWN"; +} + +/** + * Check if a consumer group is ready for message processing. + * A group is considered ready when it's in STABLE state with at least minMembers. + */ +function isGroupReady(description: GroupDescription, minMembers: number): boolean { + return ( + description.state === ConsumerGroupStates.STABLE && description.members.length >= minMembers + ); +} + +/** + * Create an AdminClient instance. + */ +function createAdminClient(brokers: string): AdminClient { + const client = Kafka.AdminClient.create({ + "client.id": "consumer-readiness-checker", + "bootstrap.servers": brokers, + }); + return client; +} + +/** + * Describe consumer groups using the Admin API. + */ +async function describeGroups(admin: AdminClient, groupIds: string[]): Promise { + return new Promise((resolve, reject) => { + admin.describeGroups(groupIds, { timeout: 10000 }, (err, descriptions) => { + if (err) { + reject(err); + } else { + resolve(descriptions); + } + }); + }); +} + +/** + * Wait for all specified consumer groups to be ready. + * + * This function polls the Kafka Admin API to check if consumer groups + * have at least minMembers active members in a STABLE state. + * + * @example + * ```ts + * import { waitForConsumers } from "@engram/storage"; + * + * // Wait for downstream consumers before starting producer + * const result = await waitForConsumers({ + * groupIds: ["memory-group", "search-group", "control-group"], + * timeoutMs: 30000, + * logger: console.log, + * }); + * + * if (result.success) { + * console.log("All consumers ready, starting ingestion..."); + * await startIngestion(); + * } else { + * console.error("Consumers not ready:", result.error); + * } + * ``` + */ +export async function waitForConsumers(config: WaitForConsumersConfig): Promise { + const { + groupIds, + brokers = process.env.REDPANDA_BROKERS || "localhost:19092", + timeoutMs = 60000, + pollIntervalMs = 2000, + minMembers = 1, + logger = () => {}, + } = config; + + if (groupIds.length === 0) { + return { + success: true, + groups: [], + elapsedMs: 0, + }; + } + + const startTime = Date.now(); + let admin: AdminClient | null = null; + + try { + admin = createAdminClient(brokers); + admin.connect(); + + logger(`[ConsumerReadiness] Waiting for consumer groups: ${groupIds.join(", ")}`); + logger(`[ConsumerReadiness] Timeout: ${timeoutMs}ms, Poll interval: ${pollIntervalMs}ms`); + + while (Date.now() - startTime < timeoutMs) { + try { + const descriptions = await describeGroups(admin, groupIds); + + const statuses: ConsumerGroupStatus[] = descriptions.map((desc) => ({ + groupId: desc.groupId, + state: desc.state, + stateName: getStateName(desc.state), + memberCount: desc.members?.length ?? 0, + isReady: isGroupReady(desc, minMembers), + })); + + // Log current status + for (const status of statuses) { + logger( + `[ConsumerReadiness] Group "${status.groupId}": ${status.stateName} ` + + `(${status.memberCount} members) - ${status.isReady ? "READY" : "NOT READY"}`, + ); + } + + // Check if all groups are ready + const allReady = statuses.every((s) => s.isReady); + if (allReady) { + const elapsedMs = Date.now() - startTime; + logger(`[ConsumerReadiness] All consumer groups ready after ${elapsedMs}ms`); + admin.disconnect(); + return { + success: true, + groups: statuses, + elapsedMs, + }; + } + + // Wait before next poll + await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + } catch (pollError) { + // Log error but continue polling + const errorMessage = pollError instanceof Error ? pollError.message : String(pollError); + logger(`[ConsumerReadiness] Poll error (retrying): ${errorMessage}`); + await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + } + } + + // Timeout reached + const elapsedMs = Date.now() - startTime; + const finalDescriptions = await describeGroups(admin, groupIds); + const finalStatuses: ConsumerGroupStatus[] = finalDescriptions.map((desc) => ({ + groupId: desc.groupId, + state: desc.state, + stateName: getStateName(desc.state), + memberCount: desc.members?.length ?? 0, + isReady: isGroupReady(desc, minMembers), + })); + + const notReady = finalStatuses.filter((s) => !s.isReady); + const errorMsg = `Timeout waiting for consumer groups: ${notReady.map((s) => s.groupId).join(", ")}`; + logger(`[ConsumerReadiness] ${errorMsg}`); + + admin.disconnect(); + return { + success: false, + groups: finalStatuses, + elapsedMs, + error: errorMsg, + }; + } catch (error) { + const elapsedMs = Date.now() - startTime; + const errorMessage = error instanceof Error ? error.message : String(error); + logger(`[ConsumerReadiness] Fatal error: ${errorMessage}`); + + if (admin) { + try { + admin.disconnect(); + } catch { + // Ignore disconnect errors + } + } + + return { + success: false, + groups: [], + elapsedMs, + error: errorMessage, + }; + } +} + +/** + * Check consumer group readiness without waiting. + * Returns the current status of all specified groups. + */ +export async function checkConsumerGroups( + groupIds: string[], + brokers: string = process.env.REDPANDA_BROKERS || "localhost:19092", +): Promise { + if (groupIds.length === 0) { + return []; + } + + const admin = createAdminClient(brokers); + admin.connect(); + + try { + const descriptions = await describeGroups(admin, groupIds); + + return descriptions.map((desc) => ({ + groupId: desc.groupId, + state: desc.state, + stateName: getStateName(desc.state), + memberCount: desc.members?.length ?? 0, + isReady: isGroupReady(desc, 1), + })); + } finally { + admin.disconnect(); + } +} diff --git a/packages/storage/src/falkor.test.ts b/packages/storage/src/falkor.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc4c9b976450963cd61d8b515c507595edc2639e --- /dev/null +++ b/packages/storage/src/falkor.test.ts @@ -0,0 +1,45 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { createFalkorClient } from "./falkor"; + +const client = createFalkorClient(); + +describe("FalkorClient", () => { + beforeAll(async () => { + await client.connect(); + }); + + afterAll(async () => { + await client.disconnect(); + }); + + it("should execute a query and return typed objects", async () => { + // Setup + await client.query("CREATE (:TestNode {id: 'test-1', value: 123})"); + + // Query + const res: any = await client.query("MATCH (n:TestNode {id: 'test-1'}) RETURN n"); + + expect(Array.isArray(res)).toBe(true); + expect(res.length).toBeGreaterThan(0); + + const row = res[0]; + expect(row).toHaveProperty("n"); + expect(row.n.labels).toContain("TestNode"); + expect(row.n.properties.id).toBe("test-1"); + expect(row.n.properties.value).toBe(123); + + // Cleanup + await client.query("MATCH (n:TestNode {id: 'test-1'}) DELETE n"); + }); + + it("should handle parameters correctly", async () => { + const id = "param-test"; + await client.query("CREATE (:ParamNode {id: $id})", { id }); + + const res: any = await client.query("MATCH (n:ParamNode) WHERE n.id = $id RETURN n", { id }); + expect(res.length).toBe(1); + expect(res[0].n.properties.id).toBe(id); + + await client.query("MATCH (n:ParamNode {id: $id}) DELETE n", { id }); + }); +}); diff --git a/packages/storage/src/falkor.ts b/packages/storage/src/falkor.ts new file mode 100644 index 0000000000000000000000000000000000000000..f89dbc578d378487c5c1fd65ee9f51663710cd22 --- /dev/null +++ b/packages/storage/src/falkor.ts @@ -0,0 +1,321 @@ +import { FalkorDB, type Graph } from "falkordb"; +import type { GraphClient } from "./interfaces"; + +// ============================================================================= +// FalkorDB Query Parameter Types +// ============================================================================= + +/** + * FalkorDB query parameter types (matches library's QueryParams) + */ +export type QueryParam = null | string | number | boolean | QueryParams | Array; +export type QueryParams = { [key: string]: QueryParam }; + +// ============================================================================= +// FalkorDB Response Types (Infrastructure Layer) +// ============================================================================= + +/** + * Generic FalkorDB node type with typed properties. + * This is the raw node structure returned by FalkorDB queries. + * + * @template T - The shape of the node's properties + * + * @example + * // Use with domain types from @engram/graph + * import type { SessionNode } from '@engram/graph'; + * const result = await falkor.query<{ s: FalkorNode }>('MATCH (s:Session) RETURN s'); + */ +export interface FalkorNode = Record> { + id: number; + labels: string[]; + properties: T; +} + +/** + * Generic FalkorDB edge type with typed properties. + * This is the raw edge structure returned by FalkorDB queries. + * + * Note: FalkorDB returns edge metadata in multiple formats depending on query type. + * Use the appropriate field: relationshipType, relation, or type. + * + * @template T - The shape of the edge's properties + */ +export interface FalkorEdge = Record> { + id: number; + relationshipType?: string; + relation?: string; + type?: string; + sourceId?: number; + srcNodeId?: number; + destinationId?: number; + destNodeId?: number; + properties: T; +} + +/** + * Generic row type for FalkorDB query results + */ +export type FalkorRow> = T; + +/** + * Generic result type for FalkorDB queries + */ +export type FalkorResult> = FalkorRow[]; + +// ============================================================================= +// FalkorDB Client Implementation +// ============================================================================= + +export class FalkorClient implements GraphClient { + private dbPromise: Promise | null = null; + private db: FalkorDB | null = null; + private graph: Graph | null = null; + private graphName = "EngramGraph"; + private connected = false; + private connectionConfig: { username: string; password: string; host: string; port: number }; + + constructor(url: string = "redis://localhost:6379") { + const urlObj = new URL(url); + // Store config but don't connect yet (lazy initialization) + this.connectionConfig = { + username: urlObj.username, + password: urlObj.password, + host: urlObj.hostname, + port: Number(urlObj.port) || 6379, + }; + } + + async connect(): Promise { + if (this.connected && this.db) { + return; // Already connected + } + + // If already connecting, wait for that attempt + if (this.dbPromise) { + await this.dbPromise; + return; + } + + // Start connection (deferred until first call to connect()) + this.dbPromise = FalkorDB.connect({ + username: this.connectionConfig.username, + password: this.connectionConfig.password, + socket: { + host: this.connectionConfig.host, + port: this.connectionConfig.port, + }, + }); + + try { + this.db = await this.dbPromise; + this.graph = this.db.selectGraph(this.graphName); + this.connected = true; + } catch (err) { + this.dbPromise = null; // Reset on failure for retry + throw err; + } + } + + isConnected(): boolean { + return this.connected && this.db !== null; + } + + /** + * Execute a typed Cypher query + * @template T - The expected row shape of the result + * @param cypher - The Cypher query string + * @param params - Query parameters + * @returns Typed array of result rows + * + * @example + * // Query returning session nodes + * interface SessionRow { s: FalkorNode } + * const result = await falkor.query('MATCH (s:Session) RETURN s'); + * result[0].s.properties.id; // typed as string + * + * @example + * // Query returning scalar values + * interface CountRow { cnt: number } + * const result = await falkor.query('MATCH (n) RETURN count(n) as cnt'); + * result[0].cnt; // typed as number + */ + async query>( + cypher: string, + params: QueryParams = {}, + ): Promise> { + if (!this.graph) await this.connect(); + // After connect(), graph is guaranteed to be set + if (!this.graph) throw new Error("Graph connection failed"); + const result = await this.graph.query(cypher, { params }); + return result.data as FalkorResult; + } + + async disconnect(): Promise { + if (this.db) { + await this.db.close(); + this.db = null; + this.graph = null; + this.connected = false; + } + } +} + +export const createFalkorClient = () => { + const url = process.env.FALKORDB_URL || "redis://localhost:6379"; + return new FalkorClient(url); +}; + +// ============================================================================= +// DEPRECATED: Domain Types +// ============================================================================= +// These types are deprecated and will be removed in a future version. +// Import domain types from @engram/graph instead. +// ============================================================================= + +/** + * @deprecated Import BitemporalProperties from @engram/graph + */ +export interface BitemporalProperties { + vt_start: number; + vt_end: number; + tt_start: number; + tt_end: number; +} + +/** + * @deprecated Import SessionNode from @engram/graph and use FalkorNode + */ +export interface SessionProperties extends Partial { + id: string; + started_at?: number; + last_event_at?: number; + title?: string; + user_id?: string; + preview?: string; + working_dir?: string; + git_remote?: string; + agent_type?: string; + summary?: string; + embedding?: number[]; + [key: string]: unknown; +} + +/** + * @deprecated Use TurnProperties instead + */ +export interface ThoughtProperties extends Partial { + id: string; + type: string; + role: string; + content: string; + timestamp?: string; + preview?: string; + [key: string]: unknown; +} + +/** + * @deprecated Import TurnNode from @engram/graph and use FalkorNode + */ +export interface TurnProperties extends Partial { + id: string; + user_content: string; + user_content_hash: string; + assistant_preview: string; + assistant_blob_ref?: string; + embedding?: number[]; + sequence_index: number; + files_touched?: string[]; + tool_calls_count?: number; + input_tokens?: number; + output_tokens?: number; + cache_read_tokens?: number; + cache_write_tokens?: number; + reasoning_tokens?: number; + cost_usd?: number; + duration_ms?: number; + git_commit?: string; + [key: string]: unknown; +} + +/** + * @deprecated Import ReasoningNode from @engram/graph and use FalkorNode + */ +export interface ReasoningProperties extends Partial { + id: string; + content_hash: string; + preview: string; + blob_ref?: string; + reasoning_type?: string; + sequence_index: number; + embedding?: number[]; + [key: string]: unknown; +} + +/** + * @deprecated Import FileTouchNode from @engram/graph and use FalkorNode + */ +export interface FileTouchProperties extends Partial { + id: string; + file_path: string; + action: string; + tool_call_id?: string; + sequence_index?: number; + diff_preview?: string; + lines_added?: number; + lines_removed?: number; + match_count?: number; + matched_files?: string[]; + [key: string]: unknown; +} + +/** + * @deprecated Import ToolCallNode from @engram/graph and use FalkorNode + */ +export interface ToolCallProperties extends Partial { + id: string; + call_id: string; + tool_name: string; + tool_type: string; + arguments_json: string; + arguments_preview?: string; + status: string; + error_message?: string; + sequence_index: number; + reasoning_sequence?: number; + [key: string]: unknown; +} + +/** + * @deprecated Import ObservationNode from @engram/graph and use FalkorNode + */ +export interface ObservationProperties extends Partial { + id: string; + tool_call_id: string; + content: string; + content_preview?: string; + content_hash?: string; + is_error: boolean; + error_type?: string; + execution_time_ms?: number; + [key: string]: unknown; +} + +// ============================================================================= +// DEPRECATED: Domain Node Aliases +// ============================================================================= + +/** @deprecated Import from @engram/graph */ +export type SessionNode = FalkorNode; +/** @deprecated */ +export type ThoughtNode = FalkorNode; +/** @deprecated Import from @engram/graph */ +export type TurnNode = FalkorNode; +/** @deprecated Import from @engram/graph */ +export type ReasoningNode = FalkorNode; +/** @deprecated Import from @engram/graph */ +export type FileTouchNode = FalkorNode; +/** @deprecated Import from @engram/graph */ +export type ToolCallNode = FalkorNode; +/** @deprecated Import from @engram/graph */ +export type ObservationNode = FalkorNode; diff --git a/packages/storage/src/index.test.ts b/packages/storage/src/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6085a0946a64e9b4c6ee5af5f2369803b7714d17 --- /dev/null +++ b/packages/storage/src/index.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import { createFalkorClient, FalkorClient } from "./falkor"; +import { createKafkaClient, KafkaClient } from "./kafka"; + +/** + * Storage Package Unit Tests + * + * These tests verify the interface contracts of the storage clients. + * Integration tests requiring actual database connections should be run separately + * with real FalkorDB and Kafka instances. + */ +describe("Storage Package", () => { + describe("FalkorClient", () => { + it("should create a client with default URL", () => { + const client = createFalkorClient(); + expect(client).toBeDefined(); + expect(typeof client.connect).toBe("function"); + expect(typeof client.query).toBe("function"); + expect(typeof client.disconnect).toBe("function"); + expect(typeof client.isConnected).toBe("function"); + }); + + it("should implement GraphClient interface", () => { + const client = new FalkorClient(); + // Verify interface compliance + expect(client).toHaveProperty("connect"); + expect(client).toHaveProperty("disconnect"); + expect(client).toHaveProperty("query"); + expect(client).toHaveProperty("isConnected"); + }); + + it("should report not connected initially", () => { + const client = new FalkorClient(); + expect(client.isConnected()).toBe(false); + }); + }); + + describe("KafkaClient", () => { + it("should create a client with defaults", () => { + const client = createKafkaClient("test-client"); + expect(client).toBeDefined(); + expect(typeof client.getProducer).toBe("function"); + expect(typeof client.getConsumer).toBe("function"); + expect(typeof client.sendEvent).toBe("function"); + expect(typeof client.disconnect).toBe("function"); + }); + + it("should implement MessageClient interface", () => { + const client = new KafkaClient(); + // Verify interface compliance + expect(client).toHaveProperty("getProducer"); + expect(client).toHaveProperty("getConsumer"); + expect(client).toHaveProperty("disconnect"); + }); + }); +}); diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc6a3d3432116668a13d9350508b49236fd26288 --- /dev/null +++ b/packages/storage/src/index.ts @@ -0,0 +1,19 @@ +// Interface exports (must come first to avoid circular dependencies) + +// Implementation exports +export * from "./blob"; +export * from "./consumer-readiness"; +export * from "./falkor"; +export type { + BlobStore, + Consumer, + ConsumerConfig, + GraphClient, + KafkaMessage, + MessageClient, + Producer, + RedisPublisher, +} from "./interfaces"; +export * from "./interfaces"; +export * from "./kafka"; +export * from "./redis"; diff --git a/packages/storage/src/interfaces.ts b/packages/storage/src/interfaces.ts new file mode 100644 index 0000000000000000000000000000000000000000..cdeb91d7f0685716a1871ebdbfc542dc81ff9e19 --- /dev/null +++ b/packages/storage/src/interfaces.ts @@ -0,0 +1,162 @@ +/** + * Storage Interface Layer + * + * These interfaces decouple application components from concrete storage implementations, + * enabling dependency injection, testing, and future infrastructure changes. + */ + +// ============================================================================= +// Message Queue Types (defined here to avoid circular dependencies) +// ============================================================================= + +/** + * Kafka message structure + */ +export type KafkaMessage = { + key?: Buffer; + value: Buffer; + offset: string; + timestamp?: string; +}; + +/** + * Kafka consumer interface with KafkaJS-compatible API + */ +export type Consumer = { + connect(): Promise; + disconnect(): Promise; + subscribe(opts: { topic: string; fromBeginning?: boolean }): Promise; + run(opts: { + eachMessage: (payload: { + topic: string; + partition: number; + message: KafkaMessage; + }) => Promise; + }): void; +}; + +/** + * Kafka producer interface + */ +export type Producer = { + connect(): Promise; + disconnect(): Promise; + send(opts: { topic: string; messages: Array<{ key: string; value: string }> }): Promise; +}; + +// ============================================================================= +// Graph Database Interface +// ============================================================================= + +/** + * GraphClient abstracts graph database operations (e.g., FalkorDB). + * Enables switching between graph backends without changing consumer code. + */ +export interface GraphClient { + /** + * Establish connection to the graph database. + */ + connect(): Promise; + + /** + * Close the graph database connection. + */ + disconnect(): Promise; + + /** + * Execute a typed Cypher query against the graph. + * @template T - The expected row shape of the result + * @param cypher - The Cypher query string + * @param params - Optional query parameters + * @returns Typed array of result rows + */ + query>( + cypher: string, + params?: Record, + ): Promise; + + /** + * Check if the client is currently connected. + */ + isConnected(): boolean; +} + +// ============================================================================= +// Message Queue Interface +// ============================================================================= + +/** + * Configuration for creating a consumer. + */ +export interface ConsumerConfig { + groupId: string; +} + +/** + * MessageClient abstracts message queue operations (e.g., Kafka/Redpanda). + * Enables switching between message brokers without changing consumer code. + */ +export interface MessageClient { + /** + * Get or create a producer instance. + * The producer is typically a singleton per client. + */ + getProducer(): Promise; + + /** + * Create a new consumer with the specified configuration. + * @param config - Consumer configuration including group ID + */ + getConsumer(config: ConsumerConfig): Promise; + + /** + * Disconnect all producers and consumers. + */ + disconnect(): Promise; +} + +// ============================================================================= +// Blob Storage Interface +// ============================================================================= + +/** + * BlobStore abstracts blob/file storage operations (e.g., filesystem, GCS, S3). + * Content is stored by hash for deduplication. + */ +export interface BlobStore { + /** + * Save content to blob storage. + * @param content - The content to store (string or binary) + * @returns URI pointing to the stored blob (e.g., file://, gs://) + */ + save(content: string | Buffer): Promise; + + /** + * Load content from blob storage. + * @param uri - The URI returned from save() + * @returns The stored content + */ + load(uri: string): Promise; +} + +// ============================================================================= +// Redis Pub/Sub Interface +// ============================================================================= + +/** + * RedisPublisher abstracts Redis pub/sub publishing operations. + * Used for real-time session updates to connected clients. + */ +export interface RedisPublisher { + /** + * Publish an update to a session-specific channel. + * @param sessionId - The session to publish to + * @param event - The event payload + */ + publishSessionUpdate(sessionId: string, event: unknown): Promise; + + /** + * Close the Redis connection. + */ + disconnect(): Promise; +} diff --git a/packages/storage/src/kafka.ts b/packages/storage/src/kafka.ts new file mode 100644 index 0000000000000000000000000000000000000000..f673db060881db1590b095ce492a6079d63afb58 --- /dev/null +++ b/packages/storage/src/kafka.ts @@ -0,0 +1,121 @@ +import { createRequire } from "node:module"; +import type { Consumer, ConsumerConfig, KafkaMessage, MessageClient, Producer } from "./interfaces"; + +// Re-export types for backward compatibility +export type { Consumer, KafkaMessage, Producer } from "./interfaces"; + +const require = createRequire(import.meta.url); +const { Kafka } = require("@confluentinc/kafka-javascript").KafkaJS; + +// Internal consumer type from the library (different from public interface) +type InternalConsumer = { + connect(): Promise; + disconnect(): Promise; + subscribe(opts: { topics: string[] }): Promise; + run(opts: { + eachMessage: (payload: { + topic: string; + partition: number; + message: KafkaMessage; + }) => Promise; + }): void; +}; + +export class KafkaClient implements MessageClient { + private kafka: unknown; + private producer: Producer | null = null; + private consumers: Consumer[] = []; + private brokers: string; + + constructor(brokers: string[] = ["localhost:19092"], _clientId: string = "engram-client") { + this.brokers = brokers.join(","); + this.kafka = new Kafka({}); + } + + public async getProducer(): Promise { + if (!this.producer) { + const kafka = this.kafka as { producer: (config: Record) => Producer }; + this.producer = kafka.producer({ + "bootstrap.servers": this.brokers, + "client.id": "engram-producer", + "allow.auto.create.topics": true, + }); + await this.producer.connect(); + } + return this.producer; + } + + /** + * Create a new consumer with the specified configuration. + * Implements MessageClient interface. + * @param config - Consumer configuration including group ID + */ + public async getConsumer(config: ConsumerConfig): Promise { + const kafka = this.kafka as { consumer: (config: Record) => InternalConsumer }; + const internalConsumer = kafka.consumer({ + "bootstrap.servers": this.brokers, + "group.id": config.groupId, + "auto.offset.reset": "earliest", + "enable.auto.commit": true, + "session.timeout.ms": 120000, // 2 minutes + "max.poll.interval.ms": 180000, // 3 minutes + }) as InternalConsumer; + await internalConsumer.connect(); + + // Wrap to provide KafkaJS-compatible API + const wrappedConsumer: Consumer = { + connect: () => internalConsumer.connect(), + disconnect: () => internalConsumer.disconnect(), + subscribe: (opts: { topic: string; fromBeginning?: boolean }) => + internalConsumer.subscribe({ topics: [opts.topic] }), + run: (opts) => internalConsumer.run(opts), + }; + + this.consumers.push(wrappedConsumer); + return wrappedConsumer; + } + + /** + * @deprecated Use getConsumer(config) instead + */ + public async createConsumer(groupId: string): Promise { + return this.getConsumer({ groupId }); + } + + /** + * Sends an event to a topic with a specific key to ensure partitioning order. + * This effectively acts as the Stream Multiplexer/De-multiplexer entry point. + */ + public async sendEvent(topic: string, key: string, message: unknown): Promise { + const producer = await this.getProducer(); + await producer.send({ + topic, + messages: [ + { + key, // Ensures all events with same key go to same partition + value: JSON.stringify(message), + }, + ], + }); + } + + public async disconnect(): Promise { + // Disconnect all consumers + for (const consumer of this.consumers) { + await consumer.disconnect(); + } + this.consumers = []; + + // Disconnect producer + if (this.producer) { + await this.producer.disconnect(); + this.producer = null; + } + } +} + +export const createKafkaClient = (clientId: string) => { + // Use port 19092 for local dev - this is the external listener that advertises localhost:19092 + const brokers = (process.env.REDPANDA_BROKERS || "localhost:19092").split(","); + return new KafkaClient(brokers, clientId); +}; diff --git a/packages/storage/src/redis.test.ts b/packages/storage/src/redis.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..176dc4981c8b4cacd204120c2b22a9ef3b001e60 --- /dev/null +++ b/packages/storage/src/redis.test.ts @@ -0,0 +1,612 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// Mock the redis module before importing the code under test +const mockPublish = vi.fn().mockResolvedValue(undefined); +const mockSubscribe = vi.fn().mockResolvedValue(undefined); +const mockUnsubscribe = vi.fn().mockResolvedValue(undefined); +const mockConnect = vi.fn().mockResolvedValue(undefined); +const mockQuit = vi.fn().mockResolvedValue(undefined); +const mockOn = vi.fn(); + +let mockIsOpen = false; + +vi.mock("redis", () => ({ + createClient: vi.fn(() => ({ + connect: mockConnect, + quit: mockQuit, + publish: mockPublish, + subscribe: mockSubscribe, + unsubscribe: mockUnsubscribe, + on: mockOn, + get isOpen() { + return mockIsOpen; + }, + })), +})); + +import { createRedisPublisher, createRedisSubscriber, type SessionUpdate } from "./redis"; + +describe("Redis Storage", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockIsOpen = false; + process.env.REDIS_URL = "redis://localhost:6379"; + }); + + afterEach(() => { + delete process.env.REDIS_URL; + }); + + describe("createRedisPublisher", () => { + describe("connect", () => { + it("should connect to Redis successfully", async () => { + const publisher = createRedisPublisher(); + + await publisher.connect(); + + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(mockOn).toHaveBeenCalledWith("error", expect.any(Function)); + }); + + it("should reuse existing connection if already open", async () => { + const publisher = createRedisPublisher(); + + // First connect + await publisher.connect(); + mockIsOpen = true; + + // Second connect should reuse + await publisher.connect(); + + expect(mockConnect).toHaveBeenCalledTimes(1); + }); + + it("should wait for existing connection attempt if connecting", async () => { + const publisher = createRedisPublisher(); + + // Slow down the connect to simulate in-progress connection + mockConnect.mockImplementationOnce(async () => { + await new Promise((r) => setTimeout(r, 100)); + mockIsOpen = true; + }); + + // Start two concurrent connections + const p1 = publisher.connect(); + const p2 = publisher.connect(); + + await Promise.all([p1, p2]); + + // Only one actual connect call should be made + expect(mockConnect).toHaveBeenCalledTimes(1); + }); + + it("should throw if REDIS_URL is not set", async () => { + delete process.env.REDIS_URL; + const publisher = createRedisPublisher(); + + await expect(publisher.connect()).rejects.toThrow( + "REDIS_URL environment variable is required", + ); + }); + + it("should register error handler on client", async () => { + const publisher = createRedisPublisher(); + await publisher.connect(); + + expect(mockOn).toHaveBeenCalledWith("error", expect.any(Function)); + + // Simulate error callback + const errorHandler = mockOn.mock.calls.find((call) => call[0] === "error")?.[1]; + const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + + errorHandler(new Error("Test error")); + + expect(consoleSpy).toHaveBeenCalledWith("[Redis Publisher] Error:", expect.any(Error)); + consoleSpy.mockRestore(); + }); + }); + + describe("publishSessionUpdate", () => { + it("should publish session update to correct channel", async () => { + const publisher = createRedisPublisher(); + const sessionId = "test-session-123"; + const update = { type: "lineage" as const, data: { foo: "bar" } }; + + await publisher.publishSessionUpdate(sessionId, update); + + expect(mockPublish).toHaveBeenCalledTimes(1); + const [channel, message] = mockPublish.mock.calls[0]; + expect(channel).toBe(`session:${sessionId}:updates`); + + const parsed = JSON.parse(message); + expect(parsed.type).toBe("lineage"); + expect(parsed.sessionId).toBe(sessionId); + expect(parsed.data).toEqual({ foo: "bar" }); + expect(typeof parsed.timestamp).toBe("number"); + }); + + it("should connect automatically if not connected", async () => { + const publisher = createRedisPublisher(); + + await publisher.publishSessionUpdate("session-1", { + type: "timeline", + data: null, + }); + + expect(mockConnect).toHaveBeenCalled(); + expect(mockPublish).toHaveBeenCalled(); + }); + + it("should handle various update types", async () => { + const publisher = createRedisPublisher(); + const types: Array = [ + "lineage", + "timeline", + "node_created", + "graph_node_created", + "session_created", + "session_updated", + "session_closed", + ]; + + for (const type of types) { + await publisher.publishSessionUpdate("session", { type, data: {} }); + } + + expect(mockPublish).toHaveBeenCalledTimes(types.length); + }); + + it("should include timestamp in published message", async () => { + const publisher = createRedisPublisher(); + const beforeTime = Date.now(); + + await publisher.publishSessionUpdate("session", { + type: "node_created", + data: { nodeId: "123" }, + }); + + const afterTime = Date.now(); + const [, message] = mockPublish.mock.calls[0]; + const parsed = JSON.parse(message); + + expect(parsed.timestamp).toBeGreaterThanOrEqual(beforeTime); + expect(parsed.timestamp).toBeLessThanOrEqual(afterTime); + }); + }); + + describe("publishGlobalSessionEvent", () => { + it("should publish to global sessions channel", async () => { + const publisher = createRedisPublisher(); + const sessionData = { id: "session-1", name: "Test Session" }; + + await publisher.publishGlobalSessionEvent("session_created", sessionData); + + expect(mockPublish).toHaveBeenCalledTimes(1); + const [channel, message] = mockPublish.mock.calls[0]; + expect(channel).toBe("sessions:updates"); + + const parsed = JSON.parse(message); + expect(parsed.type).toBe("session_created"); + expect(parsed.sessionId).toBe(""); + expect(parsed.data).toEqual(sessionData); + expect(typeof parsed.timestamp).toBe("number"); + }); + + it("should handle session_updated event type", async () => { + const publisher = createRedisPublisher(); + + await publisher.publishGlobalSessionEvent("session_updated", { updated: true }); + + const [, message] = mockPublish.mock.calls[0]; + const parsed = JSON.parse(message); + expect(parsed.type).toBe("session_updated"); + }); + + it("should handle session_closed event type", async () => { + const publisher = createRedisPublisher(); + + await publisher.publishGlobalSessionEvent("session_closed", { id: "closed-1" }); + + const [, message] = mockPublish.mock.calls[0]; + const parsed = JSON.parse(message); + expect(parsed.type).toBe("session_closed"); + }); + }); + + describe("disconnect", () => { + it("should disconnect when connected", async () => { + const publisher = createRedisPublisher(); + + await publisher.connect(); + mockIsOpen = true; + + await publisher.disconnect(); + + expect(mockQuit).toHaveBeenCalledTimes(1); + }); + + it("should be idempotent when not connected", async () => { + const publisher = createRedisPublisher(); + + await publisher.disconnect(); + await publisher.disconnect(); + + expect(mockQuit).not.toHaveBeenCalled(); + }); + + it("should be idempotent when already disconnected", async () => { + const publisher = createRedisPublisher(); + + await publisher.connect(); + mockIsOpen = true; + await publisher.disconnect(); + mockIsOpen = false; + + await publisher.disconnect(); + + expect(mockQuit).toHaveBeenCalledTimes(1); + }); + }); + }); + + describe("createRedisSubscriber", () => { + describe("connect", () => { + it("should connect to Redis successfully", async () => { + const subscriber = createRedisSubscriber(); + + await subscriber.connect(); + + expect(mockConnect).toHaveBeenCalledTimes(1); + expect(mockOn).toHaveBeenCalledWith("error", expect.any(Function)); + }); + + it("should reuse existing connection if already open", async () => { + const subscriber = createRedisSubscriber(); + + await subscriber.connect(); + mockIsOpen = true; + + await subscriber.connect(); + + expect(mockConnect).toHaveBeenCalledTimes(1); + }); + + it("should register error handler on client", async () => { + const subscriber = createRedisSubscriber(); + await subscriber.connect(); + + const errorHandler = mockOn.mock.calls.find((call) => call[0] === "error")?.[1]; + const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + + errorHandler(new Error("Subscriber error")); + + expect(consoleSpy).toHaveBeenCalledWith("[Redis Subscriber] Error:", expect.any(Error)); + consoleSpy.mockRestore(); + }); + }); + + describe("subscribe", () => { + it("should subscribe to session-specific channel", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + + await subscriber.subscribe("session-123", callback); + + expect(mockSubscribe).toHaveBeenCalledWith( + "session:session-123:updates", + expect.any(Function), + ); + }); + + it("should subscribe to full channel name if contains colon", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + + await subscriber.subscribe("sessions:updates", callback); + + expect(mockSubscribe).toHaveBeenCalledWith("sessions:updates", expect.any(Function)); + }); + + it("should invoke callback when message is received", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + const testMessage: SessionUpdate = { + type: "lineage", + sessionId: "session-123", + data: { test: true }, + timestamp: Date.now(), + }; + + // Capture the message handler + let messageHandler: (message: string) => void; + mockSubscribe.mockImplementationOnce((_channel, handler) => { + messageHandler = handler; + return Promise.resolve(); + }); + + await subscriber.subscribe("session-123", callback); + + // Simulate receiving a message + messageHandler?.(JSON.stringify(testMessage)); + + expect(callback).toHaveBeenCalledWith(testMessage); + }); + + it("should handle multiple callbacks for same channel", async () => { + const subscriber = createRedisSubscriber(); + const callback1 = vi.fn(); + const callback2 = vi.fn(); + const testMessage: SessionUpdate = { + type: "timeline", + sessionId: "session-123", + data: null, + timestamp: Date.now(), + }; + + let messageHandler: (message: string) => void; + mockSubscribe.mockImplementationOnce((_channel, handler) => { + messageHandler = handler; + return Promise.resolve(); + }); + + await subscriber.subscribe("session-123", callback1); + await subscriber.subscribe("session-123", callback2); + + // Should only subscribe once to the channel + expect(mockSubscribe).toHaveBeenCalledTimes(1); + + // Both callbacks should be invoked + messageHandler?.(JSON.stringify(testMessage)); + + expect(callback1).toHaveBeenCalledWith(testMessage); + expect(callback2).toHaveBeenCalledWith(testMessage); + }); + + it("should handle JSON parse errors gracefully", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + + let messageHandler: (message: string) => void; + mockSubscribe.mockImplementationOnce((_channel, handler) => { + messageHandler = handler; + return Promise.resolve(); + }); + + await subscriber.subscribe("session-123", callback); + + // Send invalid JSON + messageHandler?.("not valid json"); + + expect(callback).not.toHaveBeenCalled(); + expect(consoleSpy).toHaveBeenCalledWith( + "[Redis Subscriber] Failed to parse message:", + expect.any(Error), + ); + consoleSpy.mockRestore(); + }); + + it("should return unsubscribe function", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + + mockSubscribe.mockImplementationOnce(() => Promise.resolve()); + + const unsubscribe = await subscriber.subscribe("session-123", callback); + + expect(typeof unsubscribe).toBe("function"); + }); + + it("should unsubscribe single callback without affecting others", async () => { + const subscriber = createRedisSubscriber(); + const callback1 = vi.fn(); + const callback2 = vi.fn(); + + let messageHandler: (message: string) => void; + mockSubscribe.mockImplementationOnce((_channel, handler) => { + messageHandler = handler; + return Promise.resolve(); + }); + + const unsubscribe1 = await subscriber.subscribe("session-123", callback1); + await subscriber.subscribe("session-123", callback2); + + // Unsubscribe first callback + await unsubscribe1(); + + // Should not unsubscribe from Redis channel yet + expect(mockUnsubscribe).not.toHaveBeenCalled(); + + // Only callback2 should receive messages + const testMessage: SessionUpdate = { + type: "node_created", + sessionId: "session-123", + data: {}, + timestamp: Date.now(), + }; + messageHandler?.(JSON.stringify(testMessage)); + + expect(callback1).not.toHaveBeenCalled(); + expect(callback2).toHaveBeenCalledWith(testMessage); + }); + + it("should unsubscribe from Redis when last callback removed", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + + mockSubscribe.mockImplementationOnce(() => Promise.resolve()); + mockIsOpen = true; + + const unsubscribe = await subscriber.subscribe("session-123", callback); + await unsubscribe(); + + expect(mockUnsubscribe).toHaveBeenCalledWith("session:session-123:updates"); + }); + }); + + describe("disconnect", () => { + it("should disconnect and unsubscribe from all channels", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + + await subscriber.subscribe("session-1", callback); + await subscriber.subscribe("session-2", callback); + mockIsOpen = true; + + await subscriber.disconnect(); + + expect(mockUnsubscribe).toHaveBeenCalledWith("session:session-1:updates"); + expect(mockUnsubscribe).toHaveBeenCalledWith("session:session-2:updates"); + expect(mockQuit).toHaveBeenCalledTimes(1); + }); + + it("should be idempotent when not connected", async () => { + const subscriber = createRedisSubscriber(); + + await subscriber.disconnect(); + + expect(mockQuit).not.toHaveBeenCalled(); + }); + + it("should clear subscriptions on disconnect", async () => { + const subscriber = createRedisSubscriber(); + const callback = vi.fn(); + + let messageHandler: (message: string) => void; + mockSubscribe.mockImplementation((_channel, handler) => { + messageHandler = handler; + return Promise.resolve(); + }); + + await subscriber.subscribe("session-1", callback); + mockIsOpen = true; + + await subscriber.disconnect(); + mockIsOpen = false; + + // Re-subscribing should require a new Redis subscription + mockSubscribe.mockClear(); + await subscriber.subscribe("session-1", callback); + + expect(mockSubscribe).toHaveBeenCalled(); + }); + }); + }); + + describe("SessionUpdate type", () => { + it("should have correct structure", async () => { + const publisher = createRedisPublisher(); + + await publisher.publishSessionUpdate("test", { + type: "graph_node_created", + data: { nodeType: "Entity", properties: { name: "Test" } }, + }); + + const [, message] = mockPublish.mock.calls[0]; + const parsed: SessionUpdate = JSON.parse(message); + + expect(parsed).toHaveProperty("type"); + expect(parsed).toHaveProperty("sessionId"); + expect(parsed).toHaveProperty("data"); + expect(parsed).toHaveProperty("timestamp"); + }); + }); + + describe("Error scenarios", () => { + it("should handle publish failure", async () => { + const publisher = createRedisPublisher(); + mockPublish.mockRejectedValueOnce(new Error("Publish failed")); + + await expect( + publisher.publishSessionUpdate("session", { type: "lineage", data: null }), + ).rejects.toThrow("Publish failed"); + }); + + it("should handle subscribe failure", async () => { + const subscriber = createRedisSubscriber(); + mockSubscribe.mockRejectedValueOnce(new Error("Subscribe failed")); + + await expect(subscriber.subscribe("session", vi.fn())).rejects.toThrow("Subscribe failed"); + }); + + it("should handle connect failure in publisher", async () => { + const publisher = createRedisPublisher(); + mockConnect.mockRejectedValueOnce(new Error("Connection refused")); + + await expect(publisher.connect()).rejects.toThrow("Connection refused"); + }); + + it("should handle connect failure in subscriber", async () => { + const subscriber = createRedisSubscriber(); + mockConnect.mockRejectedValueOnce(new Error("Connection refused")); + + await expect(subscriber.connect()).rejects.toThrow("Connection refused"); + }); + + it("should handle quit failure gracefully", async () => { + const publisher = createRedisPublisher(); + mockQuit.mockRejectedValueOnce(new Error("Quit failed")); + + await publisher.connect(); + mockIsOpen = true; + + await expect(publisher.disconnect()).rejects.toThrow("Quit failed"); + }); + }); + + describe("Edge cases", () => { + it("should handle empty session ID", async () => { + const publisher = createRedisPublisher(); + + await publisher.publishSessionUpdate("", { type: "lineage", data: null }); + + const [channel] = mockPublish.mock.calls[0]; + expect(channel).toBe("session::updates"); + }); + + it("should handle special characters in session ID", async () => { + const publisher = createRedisPublisher(); + const specialId = "session-with:special/chars&symbols"; + + await publisher.publishSessionUpdate(specialId, { type: "timeline", data: null }); + + const [channel] = mockPublish.mock.calls[0]; + expect(channel).toBe(`session:${specialId}:updates`); + }); + + it("should handle complex nested data in updates", async () => { + const publisher = createRedisPublisher(); + const complexData = { + nested: { + array: [1, 2, { deep: true }], + object: { key: "value" }, + }, + nullValue: null, + undefinedBecomes: undefined, + }; + + await publisher.publishSessionUpdate("session", { + type: "node_created", + data: complexData, + }); + + const [, message] = mockPublish.mock.calls[0]; + const parsed = JSON.parse(message); + + expect(parsed.data.nested.array).toEqual([1, 2, { deep: true }]); + expect(parsed.data.nested.object).toEqual({ key: "value" }); + expect(parsed.data.nullValue).toBeNull(); + }); + + it("should handle large data payloads", async () => { + const publisher = createRedisPublisher(); + const largeData = { content: "x".repeat(100000) }; + + await publisher.publishSessionUpdate("session", { type: "lineage", data: largeData }); + + const [, message] = mockPublish.mock.calls[0]; + const parsed = JSON.parse(message); + expect(parsed.data.content.length).toBe(100000); + }); + }); +}); diff --git a/packages/storage/src/redis.ts b/packages/storage/src/redis.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d9bfea9d09c6d35187051dd5562a8bd97b1c528 --- /dev/null +++ b/packages/storage/src/redis.ts @@ -0,0 +1,223 @@ +import { createClient, type RedisClientType } from "redis"; + +function getRedisUrl(): string { + const url = process.env.REDIS_URL; + if (!url) { + throw new Error("REDIS_URL environment variable is required"); + } + return url; +} + +export interface SessionUpdate { + type: + | "lineage" + | "timeline" + | "node_created" + | "graph_node_created" + | "session_created" + | "session_updated" + | "session_closed"; + sessionId: string; + data: unknown; + timestamp: number; +} + +export interface ConsumerStatusUpdate { + type: "consumer_ready" | "consumer_disconnected" | "consumer_heartbeat"; + groupId: string; + serviceId: string; + timestamp: number; +} + +// Global channel for homepage session list updates +const SESSIONS_CHANNEL = "sessions:updates"; + +// Global channel for consumer status updates +const CONSUMERS_CHANNEL = "consumers:status"; + +export function createRedisPublisher() { + let client: ReturnType | null = null; + let connectPromise: Promise> | null = null; + + const connect = async () => { + // Return existing open client + if (client?.isOpen) return client; + + // If already connecting, wait for that attempt + if (connectPromise) { + return connectPromise; + } + + // Start new connection attempt + connectPromise = (async () => { + try { + const newClient = createClient({ url: getRedisUrl() }); + newClient.on("error", (err) => console.error("[Redis Publisher] Error:", err)); + await newClient.connect(); + client = newClient; + console.log("[Redis Publisher] Connected"); + return newClient; + } catch (err) { + // Reset state on failure so next call can retry + connectPromise = null; + throw err; + } + })(); + + try { + const result = await connectPromise; + return result; + } finally { + // Clear promise after completion (success or failure) + connectPromise = null; + } + }; + + const publishSessionUpdate = async ( + sessionId: string, + update: Omit, + ) => { + const conn = await connect(); + const channel = `session:${sessionId}:updates`; + const message: SessionUpdate = { + ...update, + sessionId, + timestamp: Date.now(), + }; + await conn.publish(channel, JSON.stringify(message)); + }; + + // Publish to the global sessions channel for homepage updates + const publishGlobalSessionEvent = async ( + eventType: "session_created" | "session_updated" | "session_closed", + sessionData: unknown, + ) => { + const conn = await connect(); + const message: SessionUpdate = { + type: eventType, + sessionId: "", // Global event, not tied to specific session + data: sessionData, + timestamp: Date.now(), + }; + await conn.publish(SESSIONS_CHANNEL, JSON.stringify(message)); + }; + + // Publish consumer status event (ready/disconnected/heartbeat) + const publishConsumerStatus = async ( + eventType: "consumer_ready" | "consumer_disconnected" | "consumer_heartbeat", + groupId: string, + serviceId: string, + ) => { + const conn = await connect(); + const message: ConsumerStatusUpdate = { + type: eventType, + groupId, + serviceId, + timestamp: Date.now(), + }; + await conn.publish(CONSUMERS_CHANNEL, JSON.stringify(message)); + }; + + const disconnect = async () => { + if (client?.isOpen) { + await client.quit(); + client = null; + } + }; + + return { + connect, + publishSessionUpdate, + publishGlobalSessionEvent, + publishConsumerStatus, + disconnect, + }; +} + +// Type for RedisPublisher return +export type RedisPublisher = ReturnType; + +export function createRedisSubscriber() { + let client: RedisClientType | null = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const subscriptions = new Map void>>(); + + const connect = async () => { + if (client?.isOpen) return client; + + client = createClient({ url: getRedisUrl() }); + client.on("error", (err) => console.error("[Redis Subscriber] Error:", err)); + await client.connect(); + console.log("[Redis Subscriber] Connected"); + return client; + }; + + const subscribe = async ( + channelOrSessionId: string, + callback: (message: T) => void, + ) => { + const conn = await connect(); + // Support both session-specific channels and global channels + const channel = channelOrSessionId.includes(":") + ? channelOrSessionId // Already a full channel name (e.g., "sessions:updates") + : `session:${channelOrSessionId}:updates`; // Session ID, build channel name + + // Track callbacks per channel + if (!subscriptions.has(channel)) { + subscriptions.set(channel, new Set()); + + // Subscribe to the channel (only once per channel) + await conn.subscribe(channel, (message) => { + try { + const parsed = JSON.parse(message) as T; + const callbacks = subscriptions.get(channel); + if (callbacks) { + for (const cb of callbacks) { + cb(parsed); + } + } + } catch (e) { + console.error("[Redis Subscriber] Failed to parse message:", e); + } + }); + } + + subscriptions.get(channel)?.add(callback); + + // Return unsubscribe function + return async () => { + const callbacks = subscriptions.get(channel); + if (callbacks) { + callbacks.delete(callback); + if (callbacks.size === 0) { + subscriptions.delete(channel); + await conn.unsubscribe(channel); + } + } + }; + }; + + // Subscribe specifically to consumer status updates + const subscribeToConsumerStatus = async (callback: (message: ConsumerStatusUpdate) => void) => { + return subscribe(CONSUMERS_CHANNEL, callback); + }; + + const disconnect = async () => { + if (client?.isOpen) { + // Unsubscribe from all channels + for (const channel of subscriptions.keys()) { + await client.unsubscribe(channel); + } + subscriptions.clear(); + await client.quit(); + client = null; + } + }; + + return { + connect, + subscribe, + subscribeToConsumerStatus, + disconnect, + }; +} diff --git a/packages/storage/tsconfig.json b/packages/storage/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..641a81dc7930b9224a4c9e017be08450bf43e9f0 --- /dev/null +++ b/packages/storage/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@engram/tsconfig/base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "baseUrl": "." + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/temporal/README.md b/packages/temporal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00be501b302e0a83dbaefdf37fe3da4fae1a8fea --- /dev/null +++ b/packages/temporal/README.md @@ -0,0 +1,104 @@ +# @engram/temporal + +Bitemporal state management and time-travel capabilities. + +## Overview + +Enables the system to query and reconstruct state at any historical point (valid time) and any point in transaction history (transaction time). Essential for debugging, auditing, and recovery. + +## Installation + +```bash +npm install @engram/temporal +``` + +## Core Components + +### Rehydrator + +Reconstructs session VFS state at any point in time from graph snapshots. + +```typescript +import { Rehydrator } from "@engram/temporal"; + +const rehydrator = new Rehydrator(graphClient); + +// Reconstruct file system state at a specific time +const vfs = await rehydrator.rehydrate({ + sessionId: "session-123", + asOf: new Date("2024-01-15T10:00:00Z"), +}); + +// Access files as they existed at that time +const content = vfs.readFile("/src/index.ts"); +``` + +### TimeTravelManager + +Enables querying and replaying system state. + +```typescript +import { TimeTravelManager } from "@engram/temporal"; + +const manager = new TimeTravelManager(graphClient); + +// Query state at valid time +const state = await manager.queryAtValidTime({ + sessionId: "session-123", + validTime: new Date("2024-01-15T10:00:00Z"), +}); + +// Query state at transaction time +const historicalView = await manager.queryAtTransactionTime({ + sessionId: "session-123", + transactionTime: new Date("2024-01-16T12:00:00Z"), +}); +``` + +### ReplayManager + +Replay historical operations for debugging. + +```typescript +import { ReplayManager } from "@engram/temporal"; + +const replay = new ReplayManager(graphClient); + +// Replay all operations in a session +await replay.replaySession({ + sessionId: "session-123", + fromTime: startTime, + toTime: endTime, + onOperation: (op) => console.log(op), +}); +``` + +## Error Handling + +```typescript +import { RehydrationError } from "@engram/temporal"; + +try { + await rehydrator.rehydrate({ sessionId: "missing" }); +} catch (err) { + if (err instanceof RehydrationError) { + console.error("Failed to rehydrate:", err.message); + } +} +``` + +## Bitemporal Concepts + +| Concept | Description | +|:--------|:------------| +| **Valid Time** | When the fact was true in the real world | +| **Transaction Time** | When we recorded the fact in the system | +| **As-Of Query** | What was true at a given valid time? | +| **As-Known Query** | What did we know at a given transaction time? | + +## Use Cases + +- **Debugging**: See exact file state when a bug was introduced +- **Auditing**: Review what the system knew at any point +- **Recovery**: Restore state from before an error +- **Analysis**: Compare state across time periods diff --git a/packages/temporal/package.json b/packages/temporal/package.json new file mode 100644 index 0000000000000000000000000000000000000000..54b8b0db453c84a08b0690b7030e6d508891fdb0 --- /dev/null +++ b/packages/temporal/package.json @@ -0,0 +1,21 @@ +{ + "name": "@engram/temporal", + "version": "0.0.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "devDependencies": { + "typescript": "^5.9.3", + "@types/node": "^24.10.1", + "@engram/tsconfig": "*" + }, + "dependencies": { + "zod": "^3.25.76", + "@engram/storage": "*", + "@engram/vfs": "*" + }, + "scripts": { + "build": "echo 'Build success'", + "typecheck": "tsc --noEmit" + } +} diff --git a/packages/temporal/src/errors.test.ts b/packages/temporal/src/errors.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..14f62c5e5410f8825ad13c7d1efa457dae7090df --- /dev/null +++ b/packages/temporal/src/errors.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { type ExecutionError, isUserError } from "./errors"; + +describe("Execution Errors", () => { + it("isUserError should return true by default", () => { + expect(isUserError(new Error("test"))).toBe(true); + }); + + it("should define ExecutionError interface", () => { + const err: ExecutionError = { + type: "UserError", + message: "Something went wrong", + }; + expect(err.type).toBe("UserError"); + expect(err.message).toBe("Something went wrong"); + }); +}); diff --git a/packages/temporal/src/errors.ts b/packages/temporal/src/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..c3874d93365f637a47d792aa03cab56aadcc6b85 --- /dev/null +++ b/packages/temporal/src/errors.ts @@ -0,0 +1,12 @@ +export type ExecutionErrorType = "UserError" | "SystemError"; + +export interface ExecutionError { + type: ExecutionErrorType; + message: string; + details?: unknown; +} + +export const isUserError = (_err: unknown): boolean => { + // Logic to distinguish syntax/runtime errors from sandbox crashes + return true; // Default +}; diff --git a/packages/temporal/src/index.ts b/packages/temporal/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..ddd0e831857dedcbfbed499f77b72b8ae0ba624d --- /dev/null +++ b/packages/temporal/src/index.ts @@ -0,0 +1,4 @@ +export * from "./errors"; +export * from "./rehydrator"; +export * from "./replay"; +export * from "./time-travel"; diff --git a/packages/temporal/src/rehydrator.test.ts b/packages/temporal/src/rehydrator.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c77dfe89105a7fd49484a8539dc7e19825e8d9c --- /dev/null +++ b/packages/temporal/src/rehydrator.test.ts @@ -0,0 +1,118 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// Mock @engram/storage before importing the unit under test +const mockBlobStoreLoad = vi.fn(async () => "{}"); +vi.mock("@engram/storage", () => ({ + createBlobStore: () => ({ + load: mockBlobStoreLoad, + save: vi.fn(async () => "blob://ref"), + }), + createFalkorClient: () => ({ + query: vi.fn(async () => []), + }), +})); + +import type { FalkorClient } from "@engram/storage"; +import { Rehydrator } from "./rehydrator"; + +describe("Rehydrator", () => { + let mockFalkorQuery: ReturnType; + let mockFalkor: FalkorClient; + let rehydrator: Rehydrator; + + beforeEach(() => { + mockFalkorQuery = vi.fn(async () => []); + mockFalkor = { + query: mockFalkorQuery, + } as unknown as FalkorClient; + rehydrator = new Rehydrator(mockFalkor); + mockBlobStoreLoad.mockClear(); + }); + + it("should return empty VFS if no snapshots found", async () => { + // First call (snapshot query) returns empty, second call (diff query) returns empty + mockFalkorQuery.mockResolvedValueOnce([]).mockResolvedValueOnce([]); + const vfs = await rehydrator.rehydrate("session-1"); + expect(vfs).toBeDefined(); + expect(vfs.root).toEqual({ + name: "", + type: "directory", + children: {}, + }); + }); + + it("should filter diffs by session_id", async () => { + // First call: snapshot query returns empty + // Second call: diff query (should include sessionId filter) + mockFalkorQuery.mockResolvedValueOnce([]).mockResolvedValueOnce([]); + + await rehydrator.rehydrate("test-session-123"); + + // Verify the diff query includes session filtering + const calls = mockFalkorQuery.mock.calls; + expect(calls.length).toBe(2); + + // Second call should be the diff query with session filter + const diffQueryCall = calls[1]; + const queryString = diffQueryCall[0] as string; + const params = diffQueryCall[1] as Record; + + expect(queryString).toContain("Session {id: $sessionId}"); + expect(params.sessionId).toBe("test-session-123"); + }); + + it("should attempt to load snapshot if found", async () => { + const mockSnapshot = ["blob-ref-123", 1000]; + // First call: snapshot found, second call: no diffs + mockFalkorQuery.mockResolvedValueOnce([mockSnapshot]).mockResolvedValueOnce([]); + mockBlobStoreLoad.mockResolvedValueOnce( + JSON.stringify({ root: { name: "", type: "directory", children: {} } }), + ); + + await rehydrator.rehydrate("session-1"); + + expect(mockFalkorQuery).toHaveBeenCalled(); + expect(mockBlobStoreLoad).toHaveBeenCalledWith("blob-ref-123"); + }); + + it("should apply diffs in order after snapshot", async () => { + // No snapshot + mockFalkorQuery.mockResolvedValueOnce([]); + + // Diffs returned from session-filtered query + const mockDiffs = [ + { + file_path: "/src/app.ts", + patch_content: "@@ -1,0 +1,1 @@\n+console.log('hello');", + vt_start: 1000, + }, + { + file_path: "/src/app.ts", + patch_content: "@@ -1,1 +1,2 @@\n console.log('hello');\n+console.log('world');", + vt_start: 2000, + }, + ]; + mockFalkorQuery.mockResolvedValueOnce(mockDiffs); + + // Note: PatchManager.applyPatch may fail on malformed patches + // but rehydrator catches those errors and continues + const vfs = await rehydrator.rehydrate("session-1"); + expect(vfs).toBeDefined(); + }); + + it("should pass lastSnapshotTime to diff query", async () => { + const mockSnapshot = ["blob-ref-123", 5000]; + mockFalkorQuery.mockResolvedValueOnce([mockSnapshot]).mockResolvedValueOnce([]); + mockBlobStoreLoad.mockResolvedValueOnce( + JSON.stringify({ root: { name: "", type: "directory", children: {} } }), + ); + + await rehydrator.rehydrate("session-1", 10000); + + const diffQueryCall = mockFalkorQuery.mock.calls[1]; + const params = diffQueryCall[1] as Record; + + expect(params.lastSnapshotTime).toBe(5000); + expect(params.targetTime).toBe(10000); + }); +}); diff --git a/packages/temporal/src/rehydrator.ts b/packages/temporal/src/rehydrator.ts new file mode 100644 index 0000000000000000000000000000000000000000..b499c61b4c98bd632a52d54671e94db5eab153f3 --- /dev/null +++ b/packages/temporal/src/rehydrator.ts @@ -0,0 +1,169 @@ +import { RehydrationError } from "@engram/common"; +import { + type BlobStore, + createBlobStore, + createFalkorClient, + type FalkorClient, + type GraphClient, +} from "@engram/storage"; +import { PatchManager, VirtualFileSystem } from "@engram/vfs"; + +/** + * Dependencies for Rehydrator construction. + * Supports dependency injection for testability. + */ +export interface RehydratorDeps { + /** Graph client for querying session state. Defaults to FalkorClient. */ + graphClient?: GraphClient; + /** Blob store for loading VFS snapshots. Defaults to createBlobStore(). */ + blobStore?: BlobStore; +} + +export class Rehydrator { + private graphClient: GraphClient; + private blobStore: BlobStore; + + /** + * Create a Rehydrator with injectable dependencies. + * @param deps - Optional dependencies. Defaults are used when not provided. + */ + constructor(deps?: RehydratorDeps); + /** @deprecated Use RehydratorDeps object instead */ + constructor(falkor: FalkorClient); + constructor(depsOrFalkor?: RehydratorDeps | FalkorClient) { + if (depsOrFalkor === undefined) { + // No args: use defaults + this.graphClient = createFalkorClient(); + this.blobStore = createBlobStore(); + } else if ("query" in depsOrFalkor && typeof depsOrFalkor.query === "function") { + // Legacy constructor: FalkorClient directly + this.graphClient = depsOrFalkor as GraphClient; + this.blobStore = createBlobStore(); + } else { + // New deps object constructor + const deps = depsOrFalkor as RehydratorDeps; + this.graphClient = deps.graphClient ?? createFalkorClient(); + this.blobStore = deps.blobStore ?? createBlobStore(); + } + } + + async rehydrate(sessionId: string, targetTime: number = Date.now()): Promise { + const vfs = new VirtualFileSystem(); + const patchManager = new PatchManager(vfs); + + // 1. Find latest Snapshot before targetTime for this session + const snapshotQuery = ` + MATCH (s:Snapshot)-[:SNAPSHOT_OF]->(sess:Session {id: $sessionId}) + WHERE s.snapshot_at <= $targetTime + RETURN s.vfs_state_blob_ref, s.snapshot_at + ORDER BY s.snapshot_at DESC + LIMIT 1 + `; + const snapshots = await this.graphClient.query(snapshotQuery, { sessionId, targetTime }); + let lastSnapshotTime = 0; + + if (snapshots && Array.isArray(snapshots) && snapshots.length > 0) { + const snap = snapshots[0]; + const blobRef = snap[0] as string; + lastSnapshotTime = snap[1] as number; + + // Load Blob + const blobContent = await this.blobStore.load(blobRef); + try { + await vfs.loadSnapshot(Buffer.from(blobContent)); + } catch (_snapshotError) { + // If gzip fails, try loading as JSON directly + try { + const parsed = JSON.parse(blobContent); + if (parsed.root) { + vfs.root = parsed.root; + } + } catch (jsonErr) { + // Both gzip and JSON parsing failed - throw RehydrationError + const cause = jsonErr instanceof Error ? jsonErr : undefined; + throw new RehydrationError( + `Failed to load VFS snapshot for session ${sessionId}: neither gzip nor JSON parsing succeeded`, + sessionId, + cause, + "VFSSnapshot", + ); + } + } + } + + // 2. Apply Diffs from Snapshot Time to Target Time + // Filter by session: DiffHunks linked to session through the thought chain + // Session -[:TRIGGERS]-> Thought -[:NEXT*]-> Thought -[:YIELDS]-> ToolCall -[:YIELDS]-> DiffHunk + // OR via direct PART_OF relationship if exists + const diffQuery = ` + MATCH (sess:Session {id: $sessionId})-[:TRIGGERS]->(t:Thought) + OPTIONAL MATCH (t)-[:NEXT*0..]->(linked:Thought) + WITH COALESCE(linked, t) as thought + OPTIONAL MATCH (thought)-[:YIELDS]->(tc:ToolCall)-[:YIELDS]->(d:DiffHunk) + WHERE d IS NOT NULL + AND d.vt_start > $lastSnapshotTime + AND d.vt_start <= $targetTime + RETURN DISTINCT d.file_path as file_path, d.patch_content as patch_content, d.vt_start + ORDER BY d.vt_start ASC + `; + + const diffs = await this.graphClient.query<{ file_path: string; patch_content: string }>( + diffQuery, + { + sessionId, + lastSnapshotTime, + targetTime, + }, + ); + + // Apply patches in order, tracking failures + const patchFailures: Array<{ filePath: string; error: Error }> = []; + if (diffs && Array.isArray(diffs)) { + for (const diff of diffs) { + if (diff.file_path && diff.patch_content) { + try { + patchManager.applyUnifiedDiff(diff.file_path, diff.patch_content); + } catch (e) { + // Track patch failure but continue - patches may be outdated or conflicts + const error = e instanceof Error ? e : new Error(String(e)); + patchFailures.push({ filePath: diff.file_path, error }); + console.warn( + `[Rehydrator] Failed to apply patch to ${diff.file_path}: ${error.message}`, + ); + } + } + } + } + + // If all patches failed and we had patches to apply, something is likely wrong + if (patchFailures.length > 0 && diffs && patchFailures.length === diffs.length) { + throw new RehydrationError( + `All ${patchFailures.length} patches failed to apply for session ${sessionId}`, + sessionId, + patchFailures[0]?.error, + "DiffPatches", + ); + } + + return vfs; + } +} + +/** + * Factory function for creating Rehydrator instances. + * Supports dependency injection for testability. + * + * @example + * // Production usage (uses defaults) + * const rehydrator = createRehydrator(); + * + * @example + * // Test usage (inject mocks) + * const rehydrator = createRehydrator({ + * graphClient: mockGraphClient, + * blobStore: mockBlobStore, + * }); + */ +export function createRehydrator(deps?: RehydratorDeps): Rehydrator { + return new Rehydrator(deps); +} diff --git a/packages/temporal/src/replay.test.ts b/packages/temporal/src/replay.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0858aadb7a5d7f34ad06e9a678d0ac63456ea878 --- /dev/null +++ b/packages/temporal/src/replay.test.ts @@ -0,0 +1,125 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// Mock @engram/storage before importing +const mockBlobStoreRead = vi.fn(async () => "{}"); +vi.mock("@engram/storage", () => ({ + createBlobStore: () => ({ + read: mockBlobStoreRead, + write: vi.fn(async () => {}), + }), +})); + +import type { FalkorClient } from "@engram/storage"; +import { ReplayEngine } from "./replay"; + +describe("ReplayEngine", () => { + let mockFalkorQuery: ReturnType; + let mockFalkor: FalkorClient; + let engine: ReplayEngine; + + beforeEach(() => { + mockFalkorQuery = vi.fn(async () => []); + mockFalkor = { + query: mockFalkorQuery, + } as unknown as FalkorClient; + engine = new ReplayEngine(mockFalkor); + }); + + it("should return error when event not found", async () => { + // All queries return empty + mockFalkorQuery.mockResolvedValue([]); + + const result = await engine.replay("session-1", "event-1"); + + expect(result.success).toBe(false); + expect(result.error).toContain("not found"); + }); + + it("should replay a tool call event", async () => { + // First call: fetchToolCallEvent query returns the tool call + // Second call: rehydrator's snapshot query returns empty + // Third call: rehydrator's diff query returns empty + // Note: Using write_file because read_file would fail with empty VFS + mockFalkorQuery + .mockResolvedValueOnce([ + { + id: "event-1", + name: "write_file", + arguments: JSON.stringify({ path: "/test.txt", content: "hello" }), + result: JSON.stringify({ success: true }), + vt_start: 1000, + }, + ]) // tool call event + .mockResolvedValueOnce([]) // snapshot + .mockResolvedValueOnce([]); // diffs + + const result = await engine.replay("session-1", "event-1"); + + expect(result.success).toBe(true); + }); + + it("should mock Date.now during replay", async () => { + const originalNow = Date.now(); + + // Setup mock to return a tool call + mockFalkorQuery + .mockResolvedValueOnce([ + { + id: "event-1", + name: "unknown_tool", + arguments: "{}", + result: null, + vt_start: 5000, + }, + ]) // tool call + .mockResolvedValueOnce([]) // snapshot + .mockResolvedValueOnce([]); // diffs + + await engine.replay("session-1", "event-1"); + + // Date.now should be restored after replay + expect(Date.now()).toBeGreaterThanOrEqual(originalNow); + }); + + it("should compare outputs correctly", async () => { + // Setup for a write_file tool with matching output + mockFalkorQuery + .mockResolvedValueOnce([ + { + id: "event-1", + name: "write_file", + arguments: JSON.stringify({ path: "/new.txt", content: "test" }), + result: JSON.stringify({ success: true }), + vt_start: 1000, + }, + ]) // tool call + .mockResolvedValueOnce([]) // snapshot + .mockResolvedValueOnce([]); // diffs + + const result = await engine.replay("session-1", "event-1"); + + expect(result.success).toBe(true); + expect(result.matches).toBe(true); + }); + + it("should detect mismatched outputs", async () => { + // Setup where original result differs from replay + mockFalkorQuery + .mockResolvedValueOnce([ + { + id: "event-1", + name: "write_file", + arguments: JSON.stringify({ path: "/new.txt", content: "test" }), + result: JSON.stringify({ success: false }), // Different from actual replay (which returns { success: true }) + vt_start: 1000, + }, + ]) // tool call + .mockResolvedValueOnce([]) // snapshot + .mockResolvedValueOnce([]); // diffs + + const result = await engine.replay("session-1", "event-1"); + + expect(result.success).toBe(true); + expect(result.matches).toBe(false); + }); +}); diff --git a/packages/temporal/src/replay.ts b/packages/temporal/src/replay.ts new file mode 100644 index 0000000000000000000000000000000000000000..68e71e2222190f644d25df1a791d1e7b8c662538 --- /dev/null +++ b/packages/temporal/src/replay.ts @@ -0,0 +1,213 @@ +import type { FalkorClient } from "@engram/storage"; +import type { VirtualFileSystem } from "@engram/vfs"; +import { Rehydrator } from "./rehydrator"; + +interface ToolCallEvent { + id: string; + name: string; + arguments: string; // JSON string + result?: string; // Original observation/result + vt_start: number; + session_id: string; +} + +interface ReplayResult { + success: boolean; + matches: boolean; + originalOutput: unknown; + replayOutput: unknown; + error?: string; +} + +/** + * Time and random providers for dependency injection. + * Used to make replay deterministic without polluting globals. + */ +export interface DeterministicProviders { + now: () => number; + random: () => number; +} + +/** + * Create a seeded pseudo-random number generator. + * Uses LCG (Linear Congruential Generator) for reproducibility. + */ +function createSeededRandom(seed: number): () => number { + let state = seed; + return () => { + state = (state * 1103515245 + 12345) & 0x7fffffff; + return state / 0x7fffffff; + }; +} + +/** + * Deterministic Replay Engine + * + * Replays tool executions with the exact same state as the original execution. + * Used for debugging, verification, and understanding past agent decisions. + * + * Note: Uses dependency injection for time/random to avoid global pollution. + */ +export class ReplayEngine { + private rehydrator: Rehydrator; + + constructor(private falkor: FalkorClient) { + this.rehydrator = new Rehydrator(falkor); + } + + /** + * Replay a specific tool call event and compare outputs. + * + * @param sessionId - The session containing the event + * @param eventId - The ToolCall event ID to replay + * @returns ReplayResult with comparison details + */ + async replay(sessionId: string, eventId: string): Promise { + try { + // 1. Fetch the original ToolCall event + const event = await this.fetchToolCallEvent(sessionId, eventId); + if (!event) { + return { + success: false, + matches: false, + originalOutput: null, + replayOutput: null, + error: `ToolCall event ${eventId} not found in session ${sessionId}`, + }; + } + + // 2. Rehydrate VFS to the state just before this event + const vfs = await this.rehydrator.rehydrate(sessionId, event.vt_start - 1); + + // 3. Create deterministic providers (no global mutation!) + const providers = this.createDeterministicProviders(event.vt_start); + + // 4. Parse tool arguments + const args = JSON.parse(event.arguments || "{}"); + + // 5. Execute tool with rehydrated state and deterministic providers + const replayOutput = await this.executeTool(event.name, args, vfs, providers); + + // 6. Compare with original output + const originalOutput = event.result ? JSON.parse(event.result) : null; + const matches = this.compareOutputs(originalOutput, replayOutput); + + return { + success: true, + matches, + originalOutput, + replayOutput, + }; + } catch (error) { + return { + success: false, + matches: false, + originalOutput: null, + replayOutput: null, + error: error instanceof Error ? error.message : String(error), + }; + } + } + + /** + * Fetch a ToolCall event from the graph. + */ + private async fetchToolCallEvent( + sessionId: string, + eventId: string, + ): Promise { + const query = ` + MATCH (sess:Session {id: $sessionId})-[:TRIGGERS]->(t:Thought)-[:NEXT*0..]->(linked:Thought) + MATCH (linked)-[:YIELDS]->(tc:ToolCall {id: $eventId}) + RETURN tc.id as id, tc.name as name, tc.arguments as arguments, + tc.result as result, tc.vt_start as vt_start + `; + + const results = await this.falkor.query<{ + id: string; + name: string; + arguments: string; + result: string; + vt_start: number; + }>(query, { sessionId, eventId }); + + if (!results || results.length === 0) { + return null; + } + + const row = results[0]; + return { + id: row.id, + name: row.name, + arguments: row.arguments, + result: row.result, + vt_start: row.vt_start, + session_id: sessionId, + }; + } + + /** + * Create deterministic providers for replay. + * Uses dependency injection instead of global mutation to avoid + * cross-contamination with concurrent replays or other operations. + */ + private createDeterministicProviders(timestamp: number): DeterministicProviders { + return { + now: () => timestamp, + random: createSeededRandom(timestamp), + }; + } + + /** + * Execute a tool with the given arguments and VFS state. + * This is a simplified implementation - in production, would use MCP or tool registry. + * + * @param providers - Deterministic time/random providers for reproducibility + */ + private async executeTool( + toolName: string, + args: Record, + vfs: VirtualFileSystem, + _providers?: DeterministicProviders, // Reserved for tools that need time/random + ): Promise { + // Built-in tool implementations for replay + switch (toolName) { + case "read_file": { + const path = args.path as string; + return { content: vfs.readFile(path) }; + } + case "write_file": { + const path = args.path as string; + const content = args.content as string; + vfs.writeFile(path, content); + return { success: true }; + } + case "list_directory": { + const path = args.path as string; + return { entries: vfs.readDir(path) }; + } + default: + // For unknown tools, return a placeholder indicating replay not supported + return { + error: `Tool '${toolName}' replay not implemented`, + args, + }; + } + } + + /** + * Compare original and replay outputs for equality. + * Handles both primitive and object comparisons. + */ + private compareOutputs(original: unknown, replay: unknown): boolean { + if (original === null && replay === null) return true; + if (original === null || replay === null) return false; + + // Deep equality check via JSON serialization + try { + return JSON.stringify(original) === JSON.stringify(replay); + } catch { + return false; + } + } +} diff --git a/packages/temporal/src/time-travel.test.ts b/packages/temporal/src/time-travel.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb935fac223d67848f73fef0793c76d72eae36e2 --- /dev/null +++ b/packages/temporal/src/time-travel.test.ts @@ -0,0 +1,40 @@ +import { VirtualFileSystem } from "@engram/vfs"; +import { describe, expect, it, vi } from "vitest"; +import type { Rehydrator } from "./rehydrator"; +import { TimeTravelService } from "./time-travel"; + +// Mock VirtualFileSystem +const mockVFS = new VirtualFileSystem(); +mockVFS.root = { "test.txt": "content" }; // simplistic mock of root +mockVFS.readDir = vi.fn(() => ["test.txt"]); + +// Mock Rehydrator +const mockRehydrator = { + rehydrate: vi.fn(async (_sessionId: string, _targetTime: number) => { + return mockVFS; + }), +} as unknown as Rehydrator; + +describe("TimeTravelService", () => { + const service = new TimeTravelService(mockRehydrator); + + it("getFilesystemState should return rehydrated VFS", async () => { + const vfs = await service.getFilesystemState("session-1", 1000); + expect(mockRehydrator.rehydrate).toHaveBeenCalledWith("session-1", 1000); + expect(vfs).toBe(mockVFS); + }); + + it("getZippedState should return gzipped JSON of VFS root", async () => { + const buffer = await service.getZippedState("session-1", 1000); + expect(buffer).toBeDefined(); + expect(Buffer.isBuffer(buffer)).toBe(true); + // Decompressing to check content might be overkill but good for verification + // For now just check it's not empty + expect(buffer.length).toBeGreaterThan(0); + }); + + it("listFiles should return file list from VFS", async () => { + const files = await service.listFiles("session-1", 1000, "/"); + expect(files).toEqual(["test.txt"]); + }); +}); diff --git a/packages/temporal/src/time-travel.ts b/packages/temporal/src/time-travel.ts new file mode 100644 index 0000000000000000000000000000000000000000..b736d3fef20256e4713a71b745f695e3f1d2b934 --- /dev/null +++ b/packages/temporal/src/time-travel.ts @@ -0,0 +1,33 @@ +import { promisify } from "node:util"; +import * as zlib from "node:zlib"; +import type { VirtualFileSystem } from "@engram/vfs"; +import type { Rehydrator } from "./rehydrator"; + +const gzip = promisify(zlib.gzip); + +export class TimeTravelService { + constructor(private rehydrator: Rehydrator) {} + + async getFilesystemState(sessionId: string, targetTime: number): Promise { + return this.rehydrator.rehydrate(sessionId, targetTime); + } + + async getZippedState(sessionId: string, targetTime: number): Promise { + const vfs = await this.rehydrator.rehydrate(sessionId, targetTime); + // Create a simple JSON dump for now as "Zip" + // In a real implementation, we'd use a zip library like 'jszip' or 'archiver' + // to create a downloadable archive of the VFS content. + // For V1, returning the gzipped JSON state of the VFS root is sufficient for "State Reconstruction". + const state = JSON.stringify(vfs.root); + return gzip(state); + } + + async listFiles(sessionId: string, targetTime: number, path = "/"): Promise { + const vfs = await this.rehydrator.rehydrate(sessionId, targetTime); + try { + return vfs.readDir(path); + } catch (_e) { + return []; + } + } +} diff --git a/packages/temporal/tsconfig.json b/packages/temporal/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..641a81dc7930b9224a4c9e017be08450bf43e9f0 --- /dev/null +++ b/packages/temporal/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@engram/tsconfig/base.json", + "compilerOptions": { + "rootDir": ".", + "outDir": "dist", + "baseUrl": "." + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/run.sh b/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..34ce2319ab2d51e34d44c3655d515588f217a0fa --- /dev/null +++ b/run.sh @@ -0,0 +1,303 @@ +#!/bin/bash +# ============================================================================= +# Engram Benchmark Runner for HF Spaces +# ============================================================================= +# Starts FalkorDB, Qdrant and runs the benchmark, serving status on port 7860 +# Full Engram stack: FalkorDB (graph) + Qdrant (vectors) +# ============================================================================= + +set -euo pipefail + +echo "=== Engram Benchmark Runner ===" +echo "Starting at $(date)" + +# ----------------------------------------------------------------------------- +# Start FalkorDB (Redis + FalkorDB module) +# ----------------------------------------------------------------------------- +echo "Starting FalkorDB..." +mkdir -p /app/falkordb-data + +# FalkorDB module path +FALKORDB_MODULE="/opt/falkordb/falkordb.so" +if [ ! -f "$FALKORDB_MODULE" ]; then + echo "ERROR: FalkorDB module not found at $FALKORDB_MODULE" + exit 1 +fi + +# Start Redis with FalkorDB module +echo "Starting redis-server with FalkorDB module..." +redis-server --daemonize yes \ + --port 6379 \ + --bind 127.0.0.1 \ + --dir /app/falkordb-data \ + --loadmodule "$FALKORDB_MODULE" \ + --loglevel verbose \ + --logfile /app/redis.log \ + --save "" \ + --appendonly no + +# Check if redis started +sleep 2 +if [ -f /app/redis.log ]; then + echo "Redis log (first 20 lines):" + head -20 /app/redis.log +fi + +# Wait for FalkorDB to be ready +echo "Waiting for FalkorDB..." +FALKOR_READY=0 +for i in $(seq 1 30); do + if redis-cli -h 127.0.0.1 ping 2>/dev/null | grep -q PONG; then + echo "FalkorDB is ready!" + redis-cli -h 127.0.0.1 MODULE LIST + FALKOR_READY=1 + break + fi + echo " Attempt $i: waiting..." + sleep 1 +done + +if [ "$FALKOR_READY" -eq 0 ]; then + echo "ERROR: FalkorDB failed to start!" + echo "Redis log:" + cat /app/redis.log 2>/dev/null || echo "No log file" + echo "Checking redis process:" + ps aux | grep redis || echo "No redis process" + exit 1 +fi + +# ----------------------------------------------------------------------------- +# Start Qdrant +# ----------------------------------------------------------------------------- +echo "Starting Qdrant..." +mkdir -p /app/qdrant-storage +cat > /app/qdrant-config.yaml << 'EOF' +storage: + storage_path: /app/qdrant-storage +service: + http_port: 6333 + grpc_port: 6334 +telemetry_disabled: true +EOF + +/usr/local/bin/qdrant --config-path /app/qdrant-config.yaml & +QDRANT_PID=$! + +echo "Waiting for Qdrant..." +for i in {1..30}; do + if curl -s http://localhost:6333/readyz > /dev/null 2>&1; then + echo "Qdrant is ready!" + break + fi + sleep 2 +done + +# ----------------------------------------------------------------------------- +# Check/Download Dataset +# ----------------------------------------------------------------------------- +if [ ! -f /data/longmemeval_oracle.json ]; then + echo "Checking for benchmark dataset..." + if [ -f /app/packages/benchmark/data/longmemeval_oracle.json ]; then + cp /app/packages/benchmark/data/longmemeval_oracle.json /data/ + echo "Dataset copied from app bundle" + else + echo "WARNING: No dataset found at /data/longmemeval_oracle.json" + echo "Upload dataset or include in packages/benchmark/data/" + fi +fi + +# ----------------------------------------------------------------------------- +# Create Server with Ingest + Benchmark APIs +# ----------------------------------------------------------------------------- +cat > /app/server.js << 'SERVEREOF' +const http = require("http"); +const { spawn } = require("child_process"); +const fs = require("fs"); + +let status = "idle"; +let ingestStatus = "not_started"; +let output = []; +let currentProcess = null; + +const server = http.createServer((req, res) => { + res.setHeader("Content-Type", "application/json"); + res.setHeader("Access-Control-Allow-Origin", "*"); + + // Health check + if (req.url === "/health" || req.url === "/") { + res.end(JSON.stringify({ + status: "ok", + benchmark: status, + ingest: ingestStatus, + falkordb: "redis://localhost:6379", + qdrant: "http://localhost:6333" + })); + return; + } + + // Ingest data into FalkorDB + if (req.url === "/ingest" && req.method === "POST") { + if (ingestStatus === "running") { + res.statusCode = 400; + res.end(JSON.stringify({ error: "Ingest already running" })); + return; + } + + ingestStatus = "running"; + output = []; + + // Run ingest script + const args = [ + "tsx", "packages/benchmark/src/cli/index.ts", + "ingest", + "--dataset", "/data/longmemeval_oracle.json", + "--falkor-url", "redis://localhost:6379", + "--qdrant-url", "http://localhost:6333", + "--verbose" + ]; + + currentProcess = spawn("npx", args, { cwd: "/app" }); + + currentProcess.stdout.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.log("[ingest]", line); + }); + + currentProcess.stderr.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.error("[ingest]", line); + }); + + currentProcess.on("close", (code) => { + ingestStatus = code === 0 ? "completed" : "failed"; + console.log(`Ingest finished with code ${code}`); + currentProcess = null; + }); + + res.end(JSON.stringify({ status: "ingest_started" })); + return; + } + + // Start benchmark + if (req.url === "/start" && req.method === "POST") { + if (status === "running") { + res.statusCode = 400; + res.end(JSON.stringify({ error: "Benchmark already running" })); + return; + } + + if (ingestStatus !== "completed") { + res.statusCode = 400; + res.end(JSON.stringify({ + error: "Data not ingested. POST /ingest first.", + ingestStatus + })); + return; + } + + status = "running"; + output = []; + + const args = [ + "tsx", "packages/benchmark/src/cli/index.ts", + "run", "longmemeval", + "--dataset", "/data/longmemeval_oracle.json", + "--variant", "oracle", + "--embeddings", "engram", + "--llm", "gemini", + "--gemini-model", "gemini-2.5-flash-preview-05-20", + "--falkor-url", "redis://127.0.0.1:6379", + "--qdrant-url", "http://localhost:6333", + "--top-k", "10", + "--hybrid-search", + "--rerank", + "--rerank-tier", "accurate", + "--rerank-depth", "50", + "--multi-query", + "--session-aware", + "--temporal-aware", + "--abstention", + "--abstention-hedging", + "--abstention-nli", + "--key-expansion", + "--temporal-analysis", + "--chain-of-note", + "--time-aware", + "--embedding-model", "e5-large", + "--verbose", + "--output", "/results/benchmark-results.jsonl" + ]; + + currentProcess = spawn("npx", args, { cwd: "/app" }); + + currentProcess.stdout.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.log("[benchmark]", line); + }); + + currentProcess.stderr.on("data", (data) => { + const line = data.toString(); + output.push(line); + console.error("[benchmark]", line); + }); + + currentProcess.on("close", (code) => { + status = code === 0 ? "completed" : "failed"; + console.log(`Benchmark finished with code ${code}`); + currentProcess = null; + }); + + res.end(JSON.stringify({ status: "started" })); + return; + } + + // Get status + if (req.url === "/status") { + res.end(JSON.stringify({ + benchmark: status, + ingest: ingestStatus, + output: output.slice(-100).join(""), + resultsExist: fs.existsSync("/results/benchmark-results.jsonl") + })); + return; + } + + // Download results + if (req.url === "/results" && status === "completed") { + if (fs.existsSync("/results/benchmark-results.jsonl")) { + res.setHeader("Content-Type", "application/jsonl"); + fs.createReadStream("/results/benchmark-results.jsonl").pipe(res); + return; + } + res.statusCode = 404; + res.end(JSON.stringify({ error: "Results not found" })); + return; + } + + // 404 + res.statusCode = 404; + res.end(JSON.stringify({ error: "Not found" })); +}); + +server.listen(7860, "0.0.0.0", () => { + console.log("Engram Benchmark Server running on http://0.0.0.0:7860"); + console.log(""); + console.log("API Endpoints:"); + console.log(" GET / - Health check"); + console.log(" POST /ingest - Ingest dataset into FalkorDB + Qdrant"); + console.log(" POST /start - Start benchmark (requires ingest first)"); + console.log(" GET /status - Get current status"); + console.log(" GET /results - Download results (when complete)"); + console.log(""); + console.log("Workflow:"); + console.log(" 1. POST /ingest - Load data into graph + vectors"); + console.log(" 2. POST /start - Run benchmark with full Engram pipeline"); + console.log(" 3. GET /results - Download results"); +}); +SERVEREOF + +echo "Starting benchmark server..." +node /app/server.js