Spaces:
Configuration error
Configuration error
Initial Git Push
Browse filesCI CD Tests Included
Files changed (48)
- .github/dependabot.yml+6-84
- .github/workflows/automation.ymlAdded+128
- .github/workflows/ci.ymlDeleted-59
- .github/workflows/publish.ymlDeleted-124
- INSTALL_FOR_AGENTS.md-18
- automation.tmlAdded+39
- hooks/powershell-hook.ps1Deleted-77
- src/app.py+46-15
- src/cache/__init__.py+35-12
- src/cache/observe.py+1-5
- src/cache/timeline.py+3-1
- src/cli.py+70-13
- src/connect.py+333-80
- src/db.py+12-13
- src/functions.py
- src/import_data.py+24-20
- src/mcp_stdio.py+47-16
- src/replay_import.py+202-119
- src/routes/graph.py+7-2
- src/routes/health.py+25-13
- src/routes/mcp.py+196-62
- src/routes/memories.py+6
- src/routes/migration.py+3
- src/routes/observations.py+49-45
- src/routes/search.py+10-2
- src/search.py+174-80
- src/storage/__init__.py+8-2
- src/storage/images.py+6-2
- src/storage/paths.py+2-6
- src/viewer_helpers.py+22-19
- src/workers.py+3-1
- tests/test_api.py+76-37
- tests/test_auth.py+3
- tests/test_context.py+75-38
- tests/test_debounce.py+19-18
- tests/test_folder_graph_build.py+38-24
- tests/test_folder_observe.py+44-43
- tests/test_forget.py+54-44
- tests/test_graph.py+45-42
- tests/test_migration.py+69-47
- tests/test_normalize.py+25-21
- tests/test_obs_lookup.py+32-23
- tests/test_observe_core.py+7-1
- tests/test_properties.py+64-23
- tests/test_remember.py+76-21
- tests/test_route_regressions.py+169-79
- tests/test_search.py+53-14
- tests/test_timeline.py+30-25
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647482 unmodified lines515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495966 unmodified lines103104105106107108109110version: 2updates:- package-ecosystem: npmdirectory: /schedule:interval: weeklyday: mondaytime: "06:00"timezone: Etc/UTCopen-pull-requests-limit: 10labels:- dependencies- npmcommit-message:prefix: depsinclude: scopegroups:minor-and-patch:update-types:- minor- patch- package-ecosystem: npmdirectory: /websiteschedule:interval: weeklyday: mondaytime: "06:00"timezone: Etc/UTCopen-pull-requests-limit: 10labels:- dependencies- npm- websitecommit-message:prefix: deps(website)include: scopegroups:minor-and-patch:update-types:- minor- patch- package-ecosystem: npmdirectory: /integrations/openclawschedule:interval: weeklyday: monday2 unmodified linesopen-pull-requests-limit: 5labels:- dependencies- npm- integrationscommit-message:prefix: deps(openclaw)include: scope- package-ecosystem: npmdirectory: /integrations/pischedule:interval: weeklyday: mondaytime: "06:00"timezone: Etc/UTCopen-pull-requests-limit: 5labels:- dependencies- npm- integrationscommit-message:prefix: deps(pi)include: scope- package-ecosystem: npmdirectory: /integrations/filesystem-watcherschedule:interval: weeklyday: mondaytime: "06:00"timezone: Etc/UTCopen-pull-requests-limit: 5labels:- dependencies- npm- integrationscommit-message:prefix: deps(fs-watcher)include: scope- package-ecosystem: github-actionsdirectory: /schedule:interval: weeklyday: monday6 unmodified linescommit-message:prefix: ci(deps)include: scopegroups:minor-and-patch:update-types:- minor- patch12345672 unmodified lines101112131415161718192021226 unmodified lines29303132version: 2updates:- package-ecosystem: pipdirectory: "/"schedule:interval: weeklyday: monday2 unmodified linesopen-pull-requests-limit: 5labels:- dependencies- pythoncommit-message:prefix: depsinclude: scope- package-ecosystem: github-actionsdirectory: "/"schedule:interval: weeklyday: monday6 unmodified linescommit-message:prefix: ci(deps)include: scope
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128name: Test Automation Pipeline
on: push: branches: [main] paths-ignore: - "README.md" - "CHANGELOG.md" - "AGENTS.md" - "ROADMAP.md" - "**/*.md" pull_request: branches: [main] paths-ignore: - "README.md" - "CHANGELOG.md" - "AGENTS.md" - "ROADMAP.md" - "**/*.md" workflow_dispatch: schedule: # Run every Sunday at midnight to check for dependency updates and slow/regression bugs - cron: '0 0 * * 0'
concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs: lint-and-format: name: Lint & Style Checks runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install Ruff run: pip install ruff
- name: Run Ruff Linter run: ruff check src/ tests/
- name: Check Code Formatting run: ruff format --check src/ tests/
automated-testing: name: Run Tests (${{ matrix.os }} - Py ${{ matrix.python-version }}) needs: lint-and-format runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest] python-version: ["3.10", "3.11", "3.12"] steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: 'pip'
- name: Install Dependencies run: | python -m pip install --upgrade pip pip install -e ".[dev]"
- name: Run Standard Unit & Integration Tests run: pytest tests/ --ignore=tests/test_properties.py -v --tb=short
- name: Run Hypothesis Property-Based Tests run: pytest tests/test_properties.py -v --tb=short
build-verification: name: Build & Package Verification needs: automated-testing runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11"
- name: Install Build Tool run: pip install build
- name: Build Package (wheel & sdist) run: python -m build
- name: Upload Build Artifacts uses: actions/upload-artifact@v4 with: name: agentcache-dist path: dist/ retention-days: 5
deploy-to-huggingface: name: Deploy to Hugging Face Spaces needs: [lint-and-format, automated-testing, build-verification] if: (github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v4 with: fetch-depth: 0 lfs: true
- name: Push to Hugging Face Space env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | git config --global user.email "bot@github.com" git config --global user.name "GitHub Action Bot" git remote add hf https://Yash030:$HF_TOKEN@huggingface.co/spaces/Yash030/agentmemory-python git push --force hf main:main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859name: CI
# `paths-ignore` keeps doc-only / website / README / CHANGELOG churn from# burning runner minutes. Source / config / workflow changes always run.# `workflow_dispatch` gives a manual re-run button for flake debugging.on: push: branches: [main] paths-ignore: - "README.md" - "CHANGELOG.md" - "AGENTS.md" - "ROADMAP.md" - "website/**" - "docs/**" - "assets/**" - "deploy/**/README.md" - "**/*.md" - "**/*.mdx" pull_request: branches: [main] paths-ignore: - "README.md" - "CHANGELOG.md" - "AGENTS.md" - "ROADMAP.md" - "website/**" - "docs/**" - "assets/**" - "deploy/**/README.md" - "**/*.md" - "**/*.mdx" workflow_dispatch:
# Cancel in-flight PR runs when a force-push lands. Keep push runs to# protect against partial state on main.concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: pip install -e ".[dev]" - name: Run tests run: pytest tests/ -v --tb=short - name: Build package run: | pip install build python -m build123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124name: Publish to npm
on: release: types: [published] workflow_dispatch: inputs: packages: description: "Packages to publish (comma-separated: agentmemory,mcp,fs-watcher)" required: false default: "agentmemory,mcp,fs-watcher"
# Workflow-level permissions stay minimal — only `contents: read`# is required to check out the repo. `id-token: write` is granted on# the publish job for npm's --provenance Sigstore OIDC mint.permissions: contents: read
jobs: publish: runs-on: ubuntu-latest permissions: contents: read id-token: write steps: - uses: actions/checkout@v6 with: # Don't persist the GITHUB_TOKEN to .git/config — the # publish steps don't push back to the repo, so the token # only needs to live in memory for this checkout. persist-credentials: false
- uses: actions/setup-node@v6 with: node-version: 22 registry-url: https://registry.npmjs.org
# Two-step install: generate a lockfile in-runner with # --package-lock-only, then install from it with `npm ci`. Gives a # single deterministic dep graph across build / test / publish # within one job — important because publish uses `--provenance`. # Lockfiles are gitignored at the repo level. - run: npm install --package-lock-only --legacy-peer-deps --no-audit --no-fund - run: npm ci --legacy-peer-deps --no-audit --no-fund - run: npm run build - run: npm test
- name: Publish @agentmemory/agentmemory run: | if npm view "@agentmemory/agentmemory@$(node -p "require('./package.json').version")" version >/dev/null 2>&1; then echo "Version already published, skipping" else npm publish --provenance --access public fi env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Wait for npm registry propagation run: | VERSION=$(node -p "require('./package.json').version") for i in $(seq 1 24); do if npm view "@agentmemory/agentmemory@$VERSION" version >/dev/null 2>&1; then echo "Registry propagated after ${i} attempt(s)" exit 0 fi echo "Attempt $i: not yet available, sleeping 5s..." sleep 5 done echo "ERROR: registry never propagated after 2 minutes" >&2 exit 1
- name: Publish @agentmemory/mcp shim working-directory: packages/mcp run: | SHIM_VERSION=$(node -p "require('./package.json').version") if npm view "@agentmemory/mcp@$SHIM_VERSION" version >/dev/null 2>&1; then echo "Shim version already published, skipping" else npm publish --provenance --access public fi env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Wait for @agentmemory/mcp registry propagation working-directory: packages/mcp run: | SHIM_VERSION=$(node -p "require('./package.json').version") for i in $(seq 1 24); do if npm view "@agentmemory/mcp@$SHIM_VERSION" version >/dev/null 2>&1; then echo "Shim propagated after ${i} attempt(s)" exit 0 fi echo "Attempt $i: not yet available, sleeping 5s..." sleep 5 done echo "ERROR: shim never propagated after 2 minutes" >&2 exit 1
- name: Publish @agentmemory/fs-watcher connector working-directory: integrations/filesystem-watcher run: | FSW_VERSION=$(node -p "require('./package.json').version") if npm view "@agentmemory/fs-watcher@$FSW_VERSION" version >/dev/null 2>&1; then echo "fs-watcher version already published, skipping" else npm publish --provenance --access public fi env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Wait for @agentmemory/fs-watcher registry propagation working-directory: integrations/filesystem-watcher run: | FSW_VERSION=$(node -p "require('./package.json').version") for i in $(seq 1 24); do if npm view "@agentmemory/fs-watcher@$FSW_VERSION" version >/dev/null 2>&1; then echo "fs-watcher propagated after ${i} attempt(s)" exit 0 fi echo "Attempt $i: not yet available, sleeping 5s..." sleep 5 done echo "ERROR: fs-watcher never propagated after 2 minutes" >&2 exit 1152 unmodified lines153154155156157158159160161162163164165166167168169170171172173174175176152 unmodified linesThe module reads `AGENTCACHE_URL`, `AGENTCACHE_SECRET`, and `AGENTCACHE_AGENT_ID` from `process.env`. Set them in your shell profile or in Cursor's environment settings.### PowerShell terminal (`hooks/powershell-hook.ps1`)Add a single dot-source line to your PowerShell `$PROFILE` to activate automatic command logging:```powershell. C:\path\to\hooks\powershell-hook.ps1```Set the required variables in `$PROFILE` before the dot-source line:```powershell$env:AGENTCACHE_URL = "http://127.0.0.1:3111"$env:AGENTCACHE_SECRET = "your-secret-here" # omit if no auth set$env:AGENTCACHE_AGENT_ID = "powershell"```The hook installs a PSReadLine `CommandValidationHandler` that fires a background job on every command you run. If PSReadLine is not available, call `Send-AgentCacheObservation -Text "..."` manually.### `.env` file formatAll hooks and the server itself read credentials from `~/.agentcache/.env`. Create this file if it doesn't exist:152 unmodified lines153154155156157158152 unmodified linesThe module reads `AGENTCACHE_URL`, `AGENTCACHE_SECRET`, and `AGENTCACHE_AGENT_ID` from `process.env`. Set them in your shell profile or in Cursor's environment settings.### `.env` file formatAll hooks and the server itself read credentials from `~/.agentcache/.env`. Create this file if it doesn't exist:
123456789101112131415161718192021222324252627282930313233343536373839# agentcache Test Automation Configuration File (.tml)
[project]name = "agentcache"description = "A Python REST + WebSocket + MCP cache server for AI agents, backed by SQLite"version = "0.9.8"
[ci_cd]platform = "GitHub Actions"workflow_path = ".github/workflows/automation.yml"trigger_on = ["push", "pull_request", "workflow_dispatch", "schedule"]huggingface_deploy = truehuggingface_space = "Yash030/agentmemory-python"huggingface_username = "Yash030"
[environments]python_versions = ["3.10", "3.11", "3.12"]primary_os = "ubuntu-latest"alternative_os = "windows-latest" # Recommended for testing Windows file locks/paths
[test_matrix]enable_linting = trueenable_unit_tests = trueenable_property_tests = trueenable_build_verification = true
[commands]install_deps = "pip install -e \".[dev]\""lint = "python -m pip install ruff && ruff check src/ tests/"format = "ruff format --check src/ tests/"pytest_unit = "pytest tests/ --ignore=tests/test_properties.py -v --tb=short"pytest_properties = "pytest tests/test_properties.py -v --tb=short"build_package = "pip install build && python -m build"
[embedding_providers_mocked]# During automated test execution, embedding APIs are mocked to avoid cost/network issues.openai = "MOCKED"gemini = "MOCKED"sentence_transformers = "MOCKED"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# agentmemory PowerShell terminal hook# Source this file from your $PROFILE to automatically log terminal commands.## Usage:# . C:\path\to\powershell-hook.ps1## Configuration (set as environment variables or override at top of profile):# $env:AGENTMEMORY_URL = "http://127.0.0.1:3111" (default)# $env:AGENTMEMORY_SECRET = "" (optional)# $env:AGENTMEMORY_AGENT_ID = "powershell" (default)
param( [string]$ServerUrl = $env:AGENTMEMORY_URL ?? "http://127.0.0.1:3111", [string]$AgentId = $env:AGENTMEMORY_AGENT_ID ?? "powershell", [string]$Secret = $env:AGENTMEMORY_SECRET ?? "")
function Send-AgentMemoryObservation { param( [string]$Text, [string]$FolderPath = (Get-Location).Path )
$payload = @{ folderPath = $FolderPath agentId = $AgentId text = $Text.Substring(0, [Math]::Min($Text.Length, 4000)) timestamp = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") } | ConvertTo-Json -Compress
$headers = @{ "Content-Type" = "application/json" } if ($Secret) { $headers["Authorization"] = "Bearer $Secret" }
try { Invoke-RestMethod ` -Uri "$ServerUrl/agentmemory/agent/observe" ` -Method Post ` -Headers $headers ` -Body $payload ` -TimeoutSec 5 ` -ErrorAction SilentlyContinue | Out-Null } catch { # Non-fatal — agentmemory is a best-effort sidecar }}
# Hook into PSReadLine's CommandValidationHandler to log every commandif (Get-Module -Name PSReadLine -ErrorAction SilentlyContinue) { $existingHandler = (Get-PSReadLineOption).CommandValidationHandler
Set-PSReadLineOption -CommandValidationHandler { param([System.Management.Automation.Language.CommandAst]$CommandAst)
# Forward to existing handler if any if ($existingHandler) { & $existingHandler $CommandAst }
# Log the command to agentmemory (best-effort, non-blocking) $cmd = $CommandAst.ToString() if ($cmd -and $cmd.Trim()) { $job = Start-Job -ScriptBlock { param($u, $a, $s, $t, $f) $payload = "{`"folderPath`":`"$f`",`"agentId`":`"$a`",`"text`":`"$t`",`"timestamp`":`"$(Get-Date -Format 'yyyy-MM-ddTHH:mm:ssZ')`"}" $h = @{"Content-Type"="application/json"} if ($s) { $h["Authorization"] = "Bearer $s" } try { Invoke-RestMethod -Uri "$u/agentmemory/agent/observe" -Method Post -Headers $h -Body $payload -TimeoutSec 5 -EA SilentlyContinue | Out-Null } catch {} } -ArgumentList $ServerUrl, $AgentId, $Secret, $cmd, (Get-Location).Path $null = $job # fire-and-forget }
return $true } Write-Host "[agentmemory] PowerShell hook active (agent: $AgentId, server: $ServerUrl)"} else { Write-Warning "[agentmemory] PSReadLine not available — hook not installed. Call Send-AgentMemoryObservation manually."}8 unmodified lines910111213141534 unmodified lines505152535455567 unmodified lines6465666768697071727374757677787980818283848586878889904 unmodified lines95969798991001011021031041054 unmodified lines11011111211311411511611754 unmodified lines1721731741751761771784 unmodified lines18318418518618718818921 unmodified lines2112122132142152162172187 unmodified lines2262272282292302312322332342352362372388 unmodified linesimport sysimport jsonimport hmacfrom flask import Flask, request, make_response, send_from_directoryfrom flask_sock import Sock# Prevent double-import of app when run directly as __main__34 unmodified lines# Check security credentialsif not os.getenv("AGENTCACHE_SECRET") and not os.getenv("AGENTMEMORY_SECRET"):print("[security] WARNING: AGENTCACHE_SECRET/AGENTMEMORY_SECRET is not set! All API endpoints are publicly accessible without authentication.")import search as search_modimport functions7 unmodified lines# GEMINI_API_KEY → OPENAI_API_KEY → AGENTCACHE_LOCAL_EMBEDDING_MODEL → BM25-onlyapi_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")openai_key = os.getenv("OPENAI_API_KEY")local_model = os.getenv("AGENTCACHE_LOCAL_EMBEDDING_MODEL") or os.getenv("AGENTMEMORY_LOCAL_EMBEDDING_MODEL")if api_key:try:embedding_provider = search_mod.GeminiEmbeddingProvider(api_key)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: gemini ({embedding_provider.dimensions} dims)")except Exception as e:print(f"[search] Error initialising Gemini embedding provider: {e}")elif openai_key:try:embedding_provider = search_mod.OpenAIEmbeddingProvider(openai_key)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: openai ({embedding_provider.dimensions} dims)")except Exception as e:print(f"[search] Error initialising OpenAI embedding provider: {e}")elif local_model:try:embedding_provider = search_mod.SentenceTransformerProvider(local_model)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: sentence-transformers/{local_model} ({embedding_provider.dimensions} dims)")except ImportError as e:print(f"[search] sentence-transformers not installed: {e}")except Exception as e:4 unmodified lines# 3. Index persistence — use embedding_provider variable set abovehas_vector = embedding_provider is not Nonepersistence = functions.IndexPersistence(kv, functions._bm25_index, functions._vector_index if has_vector else None,)functions.set_index_persistence(persistence)loaded = persistence.load()print(f"[persistence] Load results: BM25={loaded['bm25']}, Vector={loaded['vector']}")# Backfill coordinate lookup index if missing/incompletetry:4 unmodified lines# 4. Flask app + blueprintsflask_app = Flask(__name__)from werkzeug.middleware.proxy_fix import ProxyFixflask_app.wsgi_app = ProxyFix(flask_app.wsgi_app, x_proto=1, x_host=1, x_port=1, x_prefix=1)from routes import register_blueprintsregister_blueprints(flask_app)# 5. WebSocket broadcaster54 unmodified lines"https://huggingface.co,https://*.hf.space,""vscode-webview://*,chrome-extension://*")_cors_origins_raw = os.getenv("AGENTCACHE_CORS_ORIGINS") or os.getenv("AGENTMEMORY_CORS_ORIGINS") or _default_corsdef _parse_cors_origins(raw: str):"""Return (exact_set, suffix_list) for efficient origin matching."""4 unmodified linescontinueif entry.startswith("*."):# *.hf.space → match anything ending with .hf.spacesuffixes.append(entry[1:].lower()) # keep the leading dot: ".hf.space"elif "*" in entry:# generic prefix wildcard: strip trailing * and treat as prefixsuffixes.append(("prefix:", entry.rstrip("*").lower()))21 unmodified linesif origin and _origin_allowed(origin):response.headers["Access-Control-Allow-Origin"] = originresponse.headers["Access-Control-Allow-Credentials"] = "true"response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")response.headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")return response# Handle CORS preflight OPTIONS requests globally7 unmodified linesresp = _FlaskResponse("", status=204)resp.headers["Access-Control-Allow-Origin"] = originresp.headers["Access-Control-Allow-Credentials"] = "true"resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"resp.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"resp.headers["Access-Control-Max-Age"] = "86400"return resp# 8. Background workersfrom workers import start_background_workersstart_background_workers(kv)return flask_app8 unmodified lines910111213141534 unmodified lines5051525354555657587 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991004 unmodified lines1051061071081091101111121131141151161171181194 unmodified lines12412512612712812913013113213313413554 unmodified lines1901911921931941951961971981992004 unmodified lines20520620720820921021121 unmodified lines2332342352362372382392402412422432447 unmodified lines2522532542552562572582592602612622632642652662672682698 unmodified linesimport sysimport jsonimport hmacfrom flask import Flask, request, send_from_directoryfrom flask_sock import Sock# Prevent double-import of app when run directly as __main__34 unmodified lines# Check security credentialsif not os.getenv("AGENTCACHE_SECRET") and not os.getenv("AGENTMEMORY_SECRET"):print("[security] WARNING: AGENTCACHE_SECRET/AGENTMEMORY_SECRET is not set! All API endpoints are publicly accessible without authentication.")import search as search_modimport functions7 unmodified lines# GEMINI_API_KEY → OPENAI_API_KEY → AGENTCACHE_LOCAL_EMBEDDING_MODEL → BM25-onlyapi_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")openai_key = os.getenv("OPENAI_API_KEY")local_model = os.getenv("AGENTCACHE_LOCAL_EMBEDDING_MODEL") or os.getenv("AGENTMEMORY_LOCAL_EMBEDDING_MODEL")if api_key:try:embedding_provider = search_mod.GeminiEmbeddingProvider(api_key)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: gemini ({embedding_provider.dimensions} dims)")except Exception as e:print(f"[search] Error initialising Gemini embedding provider: {e}")elif openai_key:try:embedding_provider = search_mod.OpenAIEmbeddingProvider(openai_key)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: openai ({embedding_provider.dimensions} dims)")except Exception as e:print(f"[search] Error initialising OpenAI embedding provider: {e}")elif local_model:try:embedding_provider = search_mod.SentenceTransformerProvider(local_model)functions.set_embedding_provider(embedding_provider)print(f"[search] Embedding provider active: sentence-transformers/{local_model} ({embedding_provider.dimensions} dims)")except ImportError as e:print(f"[search] sentence-transformers not installed: {e}")except Exception as e:4 unmodified lines# 3. Index persistence — use embedding_provider variable set abovehas_vector = embedding_provider is not Nonepersistence = functions.IndexPersistence(kv,functions._bm25_index,functions._vector_index if has_vector else None,)functions.set_index_persistence(persistence)loaded = persistence.load()print(f"[persistence] Load results: BM25={loaded['bm25']}, Vector={loaded['vector']}")# Backfill coordinate lookup index if missing/incompletetry:4 unmodified lines# 4. Flask app + blueprintsflask_app = Flask(__name__)from werkzeug.middleware.proxy_fix import ProxyFixflask_app.wsgi_app = ProxyFix(flask_app.wsgi_app, x_proto=1, x_host=1, x_port=1, x_prefix=1)from routes import register_blueprintsregister_blueprints(flask_app)# 5. WebSocket broadcaster54 unmodified lines"https://huggingface.co,https://*.hf.space,""vscode-webview://*,chrome-extension://*")_cors_origins_raw = (os.getenv("AGENTCACHE_CORS_ORIGINS")or os.getenv("AGENTMEMORY_CORS_ORIGINS")or _default_cors)def _parse_cors_origins(raw: str):"""Return (exact_set, suffix_list) for efficient origin matching."""4 unmodified linescontinueif entry.startswith("*."):# *.hf.space → match anything ending with .hf.spacesuffixes.append(entry[1:].lower()) # keep the leading dot: ".hf.space"elif "*" in entry:# generic prefix wildcard: strip trailing * and treat as prefixsuffixes.append(("prefix:", entry.rstrip("*").lower()))21 unmodified linesif origin and _origin_allowed(origin):response.headers["Access-Control-Allow-Origin"] = originresponse.headers["Access-Control-Allow-Credentials"] = "true"response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")response.headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")return response# Handle CORS preflight OPTIONS requests globally7 unmodified linesresp = _FlaskResponse("", status=204)resp.headers["Access-Control-Allow-Origin"] = originresp.headers["Access-Control-Allow-Credentials"] = "true"resp.headers["Access-Control-Allow-Headers"] = ("Content-Type, Authorization")resp.headers["Access-Control-Allow-Methods"] = ("GET, POST, PUT, DELETE, OPTIONS")resp.headers["Access-Control-Max-Age"] = "86400"return resp# 8. Background workersfrom workers import start_background_workersstart_background_workers(kv)return flask_app
12 unmodified lines1314151617181928 unmodified lines4849505152535455565758596061626364656667686970717212 unmodified linescallers may import from this package (A2.2)."""from .observe import folder_observe, observe, build_synthetic_compression, strip_private_datafrom .remember import remember, forget, jaccard_similarityfrom .context import context, export_data, rebuild_indexfrom .graph import folder_graph_build28 unmodified lines__all__ = [# observe.py"folder_observe", "observe", "build_synthetic_compression", "strip_private_data",# remember.py"remember", "forget", "jaccard_similarity",# context.py"context", "export_data", "rebuild_index",# graph.py"folder_graph_build",# timeline.py"folder_timeline", "folder_search",# health.py"health_check", "auto_forget",# functions.py shims (A2.2)"KV","generate_id", "fingerprint_id","normalize_folder_path", "validate_agent_id","IndexPersistence","set_embedding_provider", "set_index_persistence", "set_stream_broadcaster","get_agent_id","record_audit", "query_audit", "safe_audit","lesson_save", "lesson_list", "lesson_recall","migrate_sessions_to_folders", "list_sessions",]12 unmodified lines13141516171819202122232428 unmodified lines5354555657585960616263646566676869707172737475767778798081828384858687888990919293949512 unmodified linescallers may import from this package (A2.2)."""from .observe import (folder_observe,observe,build_synthetic_compression,strip_private_data,)from .remember import remember, forget, jaccard_similarityfrom .context import context, export_data, rebuild_indexfrom .graph import folder_graph_build28 unmodified lines__all__ = [# observe.py"folder_observe","observe","build_synthetic_compression","strip_private_data",# remember.py"remember","forget","jaccard_similarity",# context.py"context","export_data","rebuild_index",# graph.py"folder_graph_build",# timeline.py"folder_timeline","folder_search",# health.py"health_check","auto_forget",# functions.py shims (A2.2)"KV","generate_id","fingerprint_id","normalize_folder_path","validate_agent_id","IndexPersistence","set_embedding_provider","set_index_persistence","set_stream_broadcaster","get_agent_id","record_audit","query_audit","safe_audit","lesson_save","lesson_list","lesson_recall","migrate_sessions_to_folders","list_sessions",]
9 unmodified lines10111213141516171819209 unmodified linesfrom __future__ import annotationsimport osimport reimport jsonimport datetimefrom typing import Any, Dict, List, Optional, Tuplefrom db import StateKVimport functions as _fn # access module-level globals (_bm25_index, etc.)9 unmodified lines101112131415169 unmodified linesfrom __future__ import annotationsfrom typing import Any, Dictfrom db import StateKVimport functions as _fn # access module-level globals (_bm25_index, etc.)
33 unmodified lines3435363733 unmodified linesagent_id: Optional[str] = None,) -> List[Dict[str, Any]]:"""BM25 + vector hybrid search across folder observations and global memories."""return _fn.folder_search(kv, query, limit, folder_path=folder_path, agent_id=agent_id)33 unmodified lines34353637383933 unmodified linesagent_id: Optional[str] = None,) -> List[Dict[str, Any]]:"""BM25 + vector hybrid search across folder observations and global memories."""return _fn.folder_search(kv, query, limit, folder_path=folder_path, agent_id=agent_id)
18 unmodified lines1920212223244 unmodified lines29303132333435363738394041424344455 unmodified lines5152535455561 unmodified line585960616263646566676869703 unmodified lines747576777879808182838485868788893 unmodified lines93949596979818 unmodified linesos.environ.setdefault("III_REST_PORT", str(args.port))sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from app import create_appflask_app = create_app()print(f"[cli] Starting agentcache on {args.host}:{args.port}")flask_app.run(host=args.host, port=args.port, debug=False)4 unmodified linessys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from db import StateKVfrom functions import migrate_sessions_to_folderskv = StateKV()result = migrate_sessions_to_folders(kv, dry_run=args.dry_run)print(json.dumps(result, indent=2))if args.dry_run:print(f"\n[cli] Dry run — no changes made. "f"{result['migrated_sessions']} sessions, "f"{result['migrated_observations']} observations would be migrated.")else:print(f"\n[cli] Migration complete: "f"{result['migrated_sessions']} sessions, "f"{result['migrated_observations']} observations migrated.")if result.get("errors"):print(f"[cli] {len(result['errors'])} errors:")for e in result["errors"]:5 unmodified linessys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from db import StateKVfrom functions import export_datakv = StateKV()data = export_data(kv, {})output = json.dumps(data, indent=2, ensure_ascii=False)1 unmodified linewith open(args.output, "w", encoding="utf-8") as f:f.write(output)print(f"[cli] Exported to {args.output}")total_obs = sum(len(folder.get("observations", [])) for folder in data.get("folders", []))print(f"[cli] {len(data.get('folders', []))} folders, {total_obs} observations, "f"{len(data.get('memories', []))} memories")else:print(output)def main() -> None:parser = argparse.ArgumentParser(prog="agentcache",3 unmodified lines# serveserve_parser = subparsers.add_parser("serve", help="Start the cache server")serve_parser.add_argument("--port", type=int, default=int(os.getenv("III_REST_PORT", "3111")))serve_parser.add_argument("--host", default="0.0.0.0")# migratemigrate_parser = subparsers.add_parser("migrate", help="Migrate legacy session data to folder-based storage")migrate_parser.add_argument("--dry-run", action="store_true", help="Preview without writing")# exportexport_parser = subparsers.add_parser("export", help="Export all data as JSON")export_parser.add_argument("--output", "-o", help="Output file path (default: stdout)")args = parser.parse_args()3 unmodified linescmd_migrate(args)elif args.command == "export":cmd_export(args)if __name__ == "__main__":18 unmodified lines192021222324254 unmodified lines303132333435363738394041424344454647484950515 unmodified lines575859606162631 unmodified line656667686970717273747576777879808182838485868788893 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431443 unmodified lines14814915015115215315415518 unmodified linesos.environ.setdefault("III_REST_PORT", str(args.port))sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from app import create_appflask_app = create_app()print(f"[cli] Starting agentcache on {args.host}:{args.port}")flask_app.run(host=args.host, port=args.port, debug=False)4 unmodified linessys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from db import StateKVfrom functions import migrate_sessions_to_folderskv = StateKV()result = migrate_sessions_to_folders(kv, dry_run=args.dry_run)print(json.dumps(result, indent=2))if args.dry_run:print(f"\n[cli] Dry run — no changes made. "f"{result['migrated_sessions']} sessions, "f"{result['migrated_observations']} observations would be migrated.")else:print(f"\n[cli] Migration complete: "f"{result['migrated_sessions']} sessions, "f"{result['migrated_observations']} observations migrated.")if result.get("errors"):print(f"[cli] {len(result['errors'])} errors:")for e in result["errors"]:5 unmodified linessys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from db import StateKVfrom functions import export_datakv = StateKV()data = export_data(kv, {})output = json.dumps(data, indent=2, ensure_ascii=False)1 unmodified linewith open(args.output, "w", encoding="utf-8") as f:f.write(output)print(f"[cli] Exported to {args.output}")total_obs = sum(len(folder.get("observations", [])) for folder in data.get("folders", []))print(f"[cli] {len(data.get('folders', []))} folders, {total_obs} observations, "f"{len(data.get('memories', []))} memories")else:print(output)def cmd_connect(args) -> None:"""Connect/wire MCP and hooks to client agents."""sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from connect import run_connectrun_connect(args)def main() -> None:parser = argparse.ArgumentParser(prog="agentcache",3 unmodified lines# serveserve_parser = subparsers.add_parser("serve", help="Start the cache server")serve_parser.add_argument("--port", type=int, default=int(os.getenv("III_REST_PORT", "3111")))serve_parser.add_argument("--host", default="0.0.0.0")# migratemigrate_parser = subparsers.add_parser("migrate", help="Migrate legacy session data to folder-based storage")migrate_parser.add_argument("--dry-run", action="store_true", help="Preview without writing")# exportexport_parser = subparsers.add_parser("export", help="Export all data as JSON")export_parser.add_argument("--output", "-o", help="Output file path (default: stdout)")# connectconnect_parser = subparsers.add_parser("connect", help="Connect/wire MCP and hooks to client agents")connect_parser.add_argument("agent",nargs="?",help="Specify target agent (antigravity, claude-code, kiro, etc.)",)connect_parser.add_argument("--with-hooks",action="store_true",help="Install global workspace hook execution blocks (Claude/Codex).",)connect_parser.add_argument("--dry-run",action="store_true",help="Log proposed configuration modifications without writing.",)connect_parser.add_argument("--force",action="store_true",help="Overwrite existing configuration settings.",)connect_parser.add_argument("--all", action="store_true", help="Attempt connection to all detected agents.")args = parser.parse_args()3 unmodified linescmd_migrate(args)elif args.command == "export":cmd_export(args)elif args.command == "connect":cmd_connect(args)if __name__ == "__main__":
3 unmodified lines456789101112131415161718193 unmodified lines2324252627283 unmodified lines3233343536371 unmodified line3940414243443 unmodified lines4849505152531 unmodified line55565758596026 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211320 unmodified lines1341351361371381391401411421431441451461471484 unmodified lines1531541551561571581591606 unmodified lines1671681691701711726 unmodified lines17918018118218318418518618718818919011 unmodified lines2022032042052062072082092102112122132 unmodified lines2162172182192202212222232242252262272282292302314 unmodified lines2362372382392402412422435 unmodified lines2492502512522532549 unmodified lines2642652662672682692701 unmodified line2722732742752762772782792802814 unmodified lines2862872882892902912922932942952962972982993003013023033043053063073083092 unmodified lines31231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737826 unmodified lines4054064074084094104118 unmodified lines4204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604612 unmodified lines4644654664674684694704714724734744754764774783 unmodified linesimport jsonimport shutilimport argparsefrom pathlib import Path# Helper functions for connect moduledef get_home_dir():return os.path.expanduser("~")def get_appdata_dir():return os.environ.get("APPDATA") or os.environ.get("LOCALAPPDATA") or get_home_dir()def read_json_safe(path):if not os.path.exists(path):return {}3 unmodified linesexcept Exception:return {}def write_json_atomic(path, data):os.makedirs(os.path.dirname(path), exist_ok=True)temp_path = f"{path}.tmp"3 unmodified lines# Atomic renameshutil.move(temp_path, path)def backup_file(path, prefix, ext="json"):if not os.path.exists(path):return None1 unmodified lineshutil.copy2(path, backup_path)return backup_pathdef get_plugin_root():# connect.py resides in src/, plugin/ is in the parent directorysrc_dir = os.path.dirname(os.path.abspath(__file__))3 unmodified linesreturn plugin_pathraise RuntimeError("Could not find plugin root directory.")def get_mcp_stdio_path():src_dir = os.path.dirname(os.path.abspath(__file__))mcp_path = os.path.join(src_dir, "mcp_stdio.py")1 unmodified linereturn mcp_pathraise RuntimeError("Could not find mcp_stdio.py.")def build_merged_hooks(existing_hooks, plugin_root, manifest_filename="hooks.json"):manifest_path = os.path.join(plugin_root, "hooks", manifest_filename)with open(manifest_path, "r", encoding="utf-8") as f:26 unmodified linesnext_entry = {}if "matcher" in entry:next_entry["matcher"] = entry["matcher"]resolved_handlers = []for handler in entry.get("hooks", []):cmd = handler.get("command", "")resolved_cmd = cmd.replace("${CLAUDE_PLUGIN_ROOT}", plugin_root.replace("\\", "/"))# Also replace python with sys.executable to use the correct Python instanceif resolved_cmd.startswith("python "):resolved_cmd = f'"{sys.executable.replace("\\", "/")}" ' + resolved_cmd[7:]resolved_handlers.append({"type": handler.get("type"),"command": resolved_cmd})next_entry["hooks"] = resolved_handlersresolved_entries.append(next_entry)cleaned_hooks[event] = cleaned_hooks.get(event, []) + resolved_entriesreturn {"hooks": cleaned_hooks}# ----------------- Adapters -----------------class ClaudeCodeAdapter:name = "claude-code"display_name = "Claude Code"20 unmodified linesbackup = backup_file(claude_json, "claude-code")if backup:print(f"Backed up configuration to {backup}")env = {"AGENTCACHE_URL": os.environ.get("AGENTCACHE_URL") or os.environ.get("AGENTMEMORY_URL") or "http://localhost:3111"}secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")if secret:env["AGENTCACHE_SECRET"] = secretservers["agentcache"] = {"command": sys.executable,"args": [mcp_stdio_path],"env": env}next_cfg["mcpServers"] = serverswrite_json_atomic(claude_json, next_cfg)4 unmodified linestry:plugin_root = get_plugin_root()existing_settings = read_json_safe(claude_settings)merged = build_merged_hooks(existing_settings, plugin_root, "hooks.json")if args.dry_run:print(f"[dry-run] Would merge hooks into {claude_settings}")else:6 unmodified linesexcept Exception as e:print(f"[FAIL] Failed to configure Claude Code hooks: {e}")class CodexAdapter:name = "codex"display_name = "Codex CLI"6 unmodified linescodex_toml = os.path.join(get_home_dir(), ".codex", "config.toml")mcp_stdio_path = get_mcp_stdio_path()url = os.environ.get("AGENTCACHE_URL") or os.environ.get("AGENTMEMORY_URL") or "http://localhost:3111"secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")toml_block = f"""[mcp_servers.agentcache]command = "{sys.executable.replace('\\', '/')}"args = ["{mcp_stdio_path.replace('\\', '/')}"][mcp_servers.agentcache.env]AGENTCACHE_URL = "{url}""""11 unmodified linesprint(f"[OK] Codex CLI already wired in {codex_toml}")else:if args.dry_run:print(f"[dry-run] Would write [mcp_servers.agentcache] block to {codex_toml}")else:backup = backup_file(codex_toml, "codex", "toml")if backup:print(f"Backed up config to {backup}")# Strip existing block if forcingcleaned = currentif wired:2 unmodified linesskipping = Falsefor line in lines:trimmed = line.strip()if trimmed == "[mcp_servers.agentcache]" or trimmed == "[mcp_servers.agentcache.env]":skipping = Truecontinueif skipping and trimmed.startswith("[") and trimmed != "[mcp_servers.agentcache.env]":skipping = Falseif not skipping:out.append(line)cleaned = "\n".join(out).strip()next_toml = cleaned + ("\n\n" if cleaned else "") + toml_block.strip() + "\n"os.makedirs(os.path.dirname(codex_toml), exist_ok=True)with open(codex_toml, "w", encoding="utf-8") as f:f.write(next_toml)4 unmodified linestry:plugin_root = get_plugin_root()existing_hooks = read_json_safe(codex_hooks)merged = build_merged_hooks(existing_hooks, plugin_root, "hooks.codex.json")if args.dry_run:print(f"[dry-run] Would merge hooks into {codex_hooks}")else:5 unmodified linesexcept Exception as e:print(f"[FAIL] Failed to configure Codex hooks: {e}")class HermesAdapter:name = "hermes"display_name = "Hermes Agent"9 unmodified lineshermes_src = os.path.join(project_root, "integrations", "hermes")if not os.path.exists(hermes_src):print(f"[FAIL] Failed: Source integrations/hermes not found at {hermes_src}")returnif args.dry_run:1 unmodified lineelse:if os.path.exists(dest_dir):if not args.force:print(f"[OK] Hermes plugin directory already exists at {dest_dir}. Use --force to overwrite.")returnshutil.rmtree(dest_dir)shutil.copytree(hermes_src, dest_dir)print(f"[OK] Copied Hermes cache provider plugin to {dest_dir}")print("To finish configuration, add to ~/.hermes/config.yaml:")4 unmodified linesprint(" cache:")print(" provider: agentcache")class AntigravityAdapter:name = "antigravity"display_name = "Antigravity"def get_user_dir(self):if sys.platform == "darwin":return os.path.join(get_home_dir(), "Library", "Application Support", "Antigravity", "User")elif sys.platform == "win32":appdata = get_appdata_dir()return os.path.join(appdata, "Antigravity", "User")else:return os.path.join(get_home_dir(), ".config", "Antigravity", "User")def detect(self):return os.path.exists(self.get_user_dir())def install(self, args):mcp_config_path = os.path.join(self.get_user_dir(), "mcp_config.json")mcp_stdio_path = get_mcp_stdio_path()existing = read_json_safe(mcp_config_path)2 unmodified linesalready_has = "agentcache" in serversif already_has and not args.force:print(f"[OK] Antigravity already wired in {mcp_config_path}")else:if args.dry_run:print(f"[dry-run] Would write mcpServers.agentcache in {mcp_config_path}")else:backup = backup_file(mcp_config_path, "antigravity")if backup:print(f"Backed up config to {backup}")env = {"AGENTCACHE_URL": os.environ.get("AGENTCACHE_URL") or os.environ.get("AGENTMEMORY_URL") or "http://localhost:3111"}secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")if secret:env["AGENTCACHE_SECRET"] = secretservers["agentcache"] = {"command": sys.executable,"args": [mcp_stdio_path],"env": env}next_cfg["mcpServers"] = serverswrite_json_atomic(mcp_config_path, next_cfg)print(f"[OK] Wired Antigravity MCP config in {mcp_config_path}")class KiroAdapter:name = "kiro"display_name = "Kiro"def detect(self):kiro_dir = os.path.join(get_home_dir(), ".kiro")return os.path.exists(kiro_dir)def install(self, args):mcp_config_path = os.path.join(get_home_dir(), ".kiro", "settings", "mcp.json")mcp_stdio_path = get_mcp_stdio_path()existing = read_json_safe(mcp_config_path)next_cfg = existing.copy()servers = next_cfg.get("mcpServers", {})already_has = "agentcache" in serversif already_has and not args.force:print(f"[OK] Kiro already wired in {mcp_config_path}")else:if args.dry_run:print(f"[dry-run] Would write mcpServers.agentcache in {mcp_config_path}")else:backup = backup_file(mcp_config_path, "kiro")if backup:print(f"Backed up config to {backup}")env = {"AGENTCACHE_URL": os.environ.get("AGENTCACHE_URL") or os.environ.get("AGENTMEMORY_URL") or "http://localhost:3111"}secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")if secret:env["AGENTCACHE_SECRET"] = secretservers["agentcache"] = {"command": sys.executable,"args": [mcp_stdio_path],"env": env}next_cfg["mcpServers"] = serverswrite_json_atomic(mcp_config_path, next_cfg)print(f"[OK] Wired Kiro MCP config in {mcp_config_path}")class RulesGeneratorAdapter:name = "cursor"26 unmodified lines- Call `cache_reflect` to automatically distribute observations into slots if needed."""cwd = os.getcwd()# Write to .cursorrulescursorrules = os.path.join(cwd, ".cursorrules")clineskills = os.path.join(cwd, ".clineskills")8 unmodified linesf.write(rule_content)with open(windsurfrules, "w", encoding="utf-8") as f:f.write(rule_content)print(f"[OK] Generated rule templates in current workspace:")print(f" - {cursorrules}")print(f" - {clineskills}")print(f" - {windsurfrules}")ADAPTERS = [ClaudeCodeAdapter(),CodexAdapter(),HermesAdapter(),AntigravityAdapter(),KiroAdapter(),RulesGeneratorAdapter()]def main():parser = argparse.ArgumentParser(description="Wired agentcache MCP and Hooks into client agents.")parser.add_argument("agent", nargs="?", choices=[a.name for a in ADAPTERS], help="Specify target agent.")parser.add_argument("--with-hooks", action="store_true", help="Install global workspace hook execution blocks (Claude/Codex).")parser.add_argument("--dry-run", action="store_true", help="Log proposed configuration modifications without writing.")parser.add_argument("--force", action="store_true", help="Overwrite existing configuration settings.")parser.add_argument("--all", action="store_true", help="Attempt connection to all detected agents.")args = parser.parse_args()if not args.agent and not args.all:parser.print_help()print("\nAvailable agents:")for a in ADAPTERS:print(f" - {a.name:15} ({a.display_name})")sys.exit(0)targets = []if args.all:targets = [a for a in ADAPTERS if a.detect() and a.name != "cursor"]else:matched = [a for a in ADAPTERS if a.name == args.agent]if matched:targets = matched2 unmodified linessys.exit(1)for target in targets:if not target.detect() and not args.force:print(f"[FAIL] {target.display_name} not detected on this system. (Use --force to install anyway)")continueprint(f"Wiring {target.display_name}...")try:target.install(args)except Exception as e:print(f"[FAIL] Failed to install {target.display_name}: {e}")if __name__ == "__main__":main()3 unmodified lines4567891011121314151617181920213 unmodified lines252627282930313 unmodified lines353637383940411 unmodified line434445464748493 unmodified lines535455565758591 unmodified line6162636465666726 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312420 unmodified lines1451461471481491501511521531541551561571581591601611621631641654 unmodified lines1701711721731741751761771781796 unmodified lines1861871881891901911926 unmodified lines19920020120220320420520620720820921021121221321421521621721811 unmodified lines2302312322332342352362372382392402412422432 unmodified lines2462472482492502512522532542552562572582592602612622632642652662672682692704 unmodified lines2752762772782792802812822832845 unmodified lines2902912922932942952969 unmodified lines3063073083093103113123133141 unmodified line3163173183193203213223233243253263274 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664672 unmodified lines47047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656726 unmodified lines5945955965975985996008 unmodified lines6096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706712 unmodified lines6746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307313 unmodified linesimport jsonimport shutilimport argparse# Helper functions for connect moduledef get_home_dir():return os.path.expanduser("~")def get_appdata_dir():return os.environ.get("APPDATA") or os.environ.get("LOCALAPPDATA") or get_home_dir()def read_json_safe(path):if not os.path.exists(path):return {}3 unmodified linesexcept Exception:return {}def write_json_atomic(path, data):os.makedirs(os.path.dirname(path), exist_ok=True)temp_path = f"{path}.tmp"3 unmodified lines# Atomic renameshutil.move(temp_path, path)def backup_file(path, prefix, ext="json"):if not os.path.exists(path):return None1 unmodified lineshutil.copy2(path, backup_path)return backup_pathdef get_plugin_root():# connect.py resides in src/, plugin/ is in the parent directorysrc_dir = os.path.dirname(os.path.abspath(__file__))3 unmodified linesreturn plugin_pathraise RuntimeError("Could not find plugin root directory.")def get_mcp_stdio_path():src_dir = os.path.dirname(os.path.abspath(__file__))mcp_path = os.path.join(src_dir, "mcp_stdio.py")1 unmodified linereturn mcp_pathraise RuntimeError("Could not find mcp_stdio.py.")def build_merged_hooks(existing_hooks, plugin_root, manifest_filename="hooks.json"):manifest_path = os.path.join(plugin_root, "hooks", manifest_filename)with open(manifest_path, "r", encoding="utf-8") as f:26 unmodified linesnext_entry = {}if "matcher" in entry:next_entry["matcher"] = entry["matcher"]resolved_handlers = []for handler in entry.get("hooks", []):cmd = handler.get("command", "")resolved_cmd = cmd.replace("${CLAUDE_PLUGIN_ROOT}", plugin_root.replace("\\", "/"))# Also replace python with sys.executable to use the correct Python instanceif resolved_cmd.startswith("python "):python_exe_posix = sys.executable.replace("\\", "/")resolved_cmd = f'"{python_exe_posix}" ' + resolved_cmd[7:]resolved_handlers.append({"type": handler.get("type"), "command": resolved_cmd})next_entry["hooks"] = resolved_handlersresolved_entries.append(next_entry)cleaned_hooks[event] = cleaned_hooks.get(event, []) + resolved_entriesreturn {"hooks": cleaned_hooks}# ----------------- Adapters -----------------class ClaudeCodeAdapter:name = "claude-code"display_name = "Claude Code"20 unmodified linesbackup = backup_file(claude_json, "claude-code")if backup:print(f"Backed up configuration to {backup}")env = {"AGENTCACHE_URL": os.environ.get("AGENTCACHE_URL")or os.environ.get("AGENTMEMORY_URL")or "http://localhost:3111"}secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")if secret:env["AGENTCACHE_SECRET"] = secretservers["agentcache"] = {"command": sys.executable,"args": [mcp_stdio_path],"env": env,}next_cfg["mcpServers"] = serverswrite_json_atomic(claude_json, next_cfg)4 unmodified linestry:plugin_root = get_plugin_root()existing_settings = read_json_safe(claude_settings)merged = build_merged_hooks(existing_settings, plugin_root, "hooks.json")if args.dry_run:print(f"[dry-run] Would merge hooks into {claude_settings}")else:6 unmodified linesexcept Exception as e:print(f"[FAIL] Failed to configure Claude Code hooks: {e}")class CodexAdapter:name = "codex"display_name = "Codex CLI"6 unmodified linescodex_toml = os.path.join(get_home_dir(), ".codex", "config.toml")mcp_stdio_path = get_mcp_stdio_path()url = (os.environ.get("AGENTCACHE_URL")or os.environ.get("AGENTMEMORY_URL")or "http://localhost:3111")secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")python_exe_posix = sys.executable.replace("\\", "/")mcp_stdio_posix = mcp_stdio_path.replace("\\", "/")toml_block = f"""[mcp_servers.agentcache]command = "{python_exe_posix}"args = ["{mcp_stdio_posix}"][mcp_servers.agentcache.env]AGENTCACHE_URL = "{url}""""11 unmodified linesprint(f"[OK] Codex CLI already wired in {codex_toml}")else:if args.dry_run:print(f"[dry-run] Would write [mcp_servers.agentcache] block to {codex_toml}")else:backup = backup_file(codex_toml, "codex", "toml")if backup:print(f"Backed up config to {backup}")# Strip existing block if forcingcleaned = currentif wired:2 unmodified linesskipping = Falsefor line in lines:trimmed = line.strip()if (trimmed == "[mcp_servers.agentcache]"or trimmed == "[mcp_servers.agentcache.env]"):skipping = Truecontinueif (skippingand trimmed.startswith("[")and trimmed != "[mcp_servers.agentcache.env]"):skipping = Falseif not skipping:out.append(line)cleaned = "\n".join(out).strip()next_toml = (cleaned + ("\n\n" if cleaned else "") + toml_block.strip() + "\n")os.makedirs(os.path.dirname(codex_toml), exist_ok=True)with open(codex_toml, "w", encoding="utf-8") as f:f.write(next_toml)4 unmodified linestry:plugin_root = get_plugin_root()existing_hooks = read_json_safe(codex_hooks)merged = build_merged_hooks(existing_hooks, plugin_root, "hooks.codex.json")if args.dry_run:print(f"[dry-run] Would merge hooks into {codex_hooks}")else:5 unmodified linesexcept Exception as e:print(f"[FAIL] Failed to configure Codex hooks: {e}")class HermesAdapter:name = "hermes"display_name = "Hermes Agent"9 unmodified lineshermes_src = os.path.join(project_root, "integrations", "hermes")if not os.path.exists(hermes_src):print(f"[FAIL] Failed: Source integrations/hermes not found at {hermes_src}")returnif args.dry_run:1 unmodified lineelse:if os.path.exists(dest_dir):if not args.force:print(f"[OK] Hermes plugin directory already exists at {dest_dir}. Use --force to overwrite.")returnshutil.rmtree(dest_dir)shutil.copytree(hermes_src, dest_dir)print(f"[OK] Copied Hermes cache provider plugin to {dest_dir}")print("To finish configuration, add to ~/.hermes/config.yaml:")4 unmodified linesprint(" cache:")print(" provider: agentcache")class AntigravityAdapter:name = "antigravity"display_name = "Antigravity"def get_user_dir(self):if sys.platform == "darwin":return os.path.join(get_home_dir(), "Library", "Application Support", "Antigravity", "User")elif sys.platform == "win32":appdata = get_appdata_dir()return os.path.join(appdata, "Antigravity", "User")else:return os.path.join(get_home_dir(), ".config", "Antigravity", "User")def get_gemini_mcp_dir(self):return os.path.join(get_home_dir(), ".gemini", "antigravity", "mcp", "agentcache")def detect(self):gemini_parent = os.path.dirname(os.path.dirname(self.get_gemini_mcp_dir()))return os.path.exists(gemini_parent) or os.path.exists(self.get_user_dir())def install_gemini_schemas(self, args):gemini_mcp_dir = self.get_gemini_mcp_dir()if args.dry_run:print(f"[dry-run] Would create directory {gemini_mcp_dir} and write tool schema JSON files.")returnos.makedirs(gemini_mcp_dir, exist_ok=True)try:# Dynamic import to avoid circular dependencytry:from routes.mcp import get_mcp_tools_schemasexcept ImportError:try:from src.routes.mcp import get_mcp_tools_schemasexcept ImportError:sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from routes.mcp import get_mcp_tools_schemastools = get_mcp_tools_schemas()except Exception as e:print(f"[FAIL] Could not load tool schemas: {e}")returnfor tool in tools:tool_name = tool["name"]schema = {"name": tool_name,"description": tool.get("description", ""),"parameters": tool.get("inputSchema", {}),}tool_file_path = os.path.join(gemini_mcp_dir, f"{tool_name}.json")if os.path.exists(tool_file_path) and not args.force:continuewith open(tool_file_path, "w", encoding="utf-8") as f:json.dump(schema, f, indent=2)f.write("\n")print(f"[OK] Installed {len(tools)} tool schemas to {gemini_mcp_dir}")def install(self, args):# 1. Install tool schemas under ~/.gemini/antigravity/mcp/agentcachegemini_parent = os.path.dirname(os.path.dirname(self.get_gemini_mcp_dir()))if os.path.exists(gemini_parent) or args.force:self.install_gemini_schemas(args)# 2. Wire the VS Code/User AppData client config if presentuser_dir = self.get_user_dir()if os.path.exists(user_dir) or args.force:mcp_config_path = os.path.join(user_dir, "mcp_config.json")mcp_stdio_path = get_mcp_stdio_path()existing = read_json_safe(mcp_config_path)next_cfg = existing.copy()servers = next_cfg.get("mcpServers", {})already_has = "agentcache" in serversif already_has and not args.force:print(f"[OK] Antigravity VS Code client already wired in {mcp_config_path}")else:if args.dry_run:print(f"[dry-run] Would write mcpServers.agentcache in {mcp_config_path}")else:backup = backup_file(mcp_config_path, "antigravity")if backup:print(f"Backed up config to {backup}")env = {"AGENTCACHE_URL": os.environ.get("AGENTCACHE_URL")or os.environ.get("AGENTMEMORY_URL")or "http://localhost:3111"}secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")if secret:env["AGENTCACHE_SECRET"] = secretservers["agentcache"] = {"command": sys.executable,"args": [mcp_stdio_path],"env": env,}next_cfg["mcpServers"] = serverswrite_json_atomic(mcp_config_path, next_cfg)print(f"[OK] Wired Antigravity VS Code client MCP config in {mcp_config_path}")class KiroAdapter:name = "kiro"display_name = "Kiro"def detect(self):kiro_dir = os.path.join(get_home_dir(), ".kiro")return os.path.exists(kiro_dir)def install(self, args):mcp_config_path = os.path.join(get_home_dir(), ".kiro", "settings", "mcp.json")mcp_stdio_path = get_mcp_stdio_path()existing = read_json_safe(mcp_config_path)2 unmodified linesalready_has = "agentcache" in serversif already_has and not args.force:print(f"[OK] Kiro already wired in {mcp_config_path}")else:if args.dry_run:print(f"[dry-run] Would write mcpServers.agentcache in {mcp_config_path}")else:backup = backup_file(mcp_config_path, "kiro")if backup:print(f"Backed up config to {backup}")env = {"AGENTCACHE_URL": os.environ.get("AGENTCACHE_URL")or os.environ.get("AGENTMEMORY_URL")or "http://localhost:3111"}secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")if secret:env["AGENTCACHE_SECRET"] = secretservers["agentcache"] = {"command": sys.executable,"args": [mcp_stdio_path],"env": env,}next_cfg["mcpServers"] = serverswrite_json_atomic(mcp_config_path, next_cfg)print(f"[OK] Wired Kiro MCP config in {mcp_config_path}")class VSCodeAdapter:name = "vscode"display_name = "VS Code"def get_user_config_path(self):if sys.platform == "darwin":return os.path.join(get_home_dir(),"Library","Application Support","Code","User","mcp.json",)elif sys.platform == "win32":appdata = get_appdata_dir()return os.path.join(appdata, "Code", "User", "mcp.json")else:return os.path.join(get_home_dir(), ".config", "Code", "User", "mcp.json")def detect(self):return os.path.exists(os.path.dirname(self.get_user_config_path()))def install(self, args):mcp_config_path = self.get_user_config_path()mcp_stdio_path = get_mcp_stdio_path()existing = read_json_safe(mcp_config_path)next_cfg = existing.copy()servers = next_cfg.get("servers", {})already_has = "agentcache" in serversif already_has and not args.force:print(f"[OK] VS Code already wired in {mcp_config_path}")else:if args.dry_run:print(f"[dry-run] Would write servers.agentcache in {mcp_config_path}")else:backup = backup_file(mcp_config_path, "vscode")if backup:print(f"Backed up config to {backup}")env = {"AGENTCACHE_URL": os.environ.get("AGENTCACHE_URL")or os.environ.get("AGENTMEMORY_URL")or "http://localhost:3111"}secret = os.environ.get("AGENTCACHE_SECRET") or os.environ.get("AGENTMEMORY_SECRET")if secret:env["AGENTCACHE_SECRET"] = secretservers["agentcache"] = {"command": sys.executable,"args": [mcp_stdio_path],"env": env,}next_cfg["servers"] = serverswrite_json_atomic(mcp_config_path, next_cfg)print(f"[OK] Wired VS Code MCP config in {mcp_config_path}")class RulesGeneratorAdapter:name = "cursor"26 unmodified lines- Call `cache_reflect` to automatically distribute observations into slots if needed."""cwd = os.getcwd()# Write to .cursorrulescursorrules = os.path.join(cwd, ".cursorrules")clineskills = os.path.join(cwd, ".clineskills")8 unmodified linesf.write(rule_content)with open(windsurfrules, "w", encoding="utf-8") as f:f.write(rule_content)print("[OK] Generated rule templates in current workspace:")print(f" - {cursorrules}")print(f" - {clineskills}")print(f" - {windsurfrules}")ADAPTERS = [ClaudeCodeAdapter(),CodexAdapter(),HermesAdapter(),AntigravityAdapter(),KiroAdapter(),VSCodeAdapter(),RulesGeneratorAdapter(),]def map_agent_alias(name: str) -> str:if not name:return namename = name.lower().strip()if name in ("antigravity","/anti-gravity","anti-gravity","/antigravity","antigravity",):return "antigravity"if name in ("claude", "claude-code", "claudecode", "claude code"):return "claude-code"if name in ("kiro", "keyro"):return "kiro"if name in ("vscode", "vs-code", "visual-studio-code", "vs code"):return "vscode"return namedef run_connect(args):# Normalize/Map target agent alias if providedagent_name = getattr(args, "agent", None)if agent_name:agent_name = map_agent_alias(agent_name)setattr(args, "agent", agent_name)valid_names = [a.name for a in ADAPTERS]if agent_name and agent_name not in valid_names:print(f"[FAIL] Unknown agent: {agent_name}. Supported agents: {', '.join(valid_names)}")sys.exit(1)targets = []if getattr(args, "all", False):targets = [a for a in ADAPTERS if a.detect() and a.name != "cursor"]else:matched = [a for a in ADAPTERS if a.name == agent_name]if matched:targets = matched2 unmodified linessys.exit(1)for target in targets:if not target.detect() and not getattr(args, "force", False):print(f"[FAIL] {target.display_name} not detected on this system. (Use --force to install anyway)")continueprint(f"Wiring {target.display_name}...")try:target.install(args)except Exception as e:print(f"[FAIL] Failed to install {target.display_name}: {e}")def main():parser = argparse.ArgumentParser(description="Wired agentcache MCP and Hooks into client agents.")parser.add_argument("agent",nargs="?",help="Specify target agent (antigravity, claude-code, kiro, etc.).",)parser.add_argument("--with-hooks",action="store_true",help="Install global workspace hook execution blocks (Claude/Codex).",)parser.add_argument("--dry-run",action="store_true",help="Log proposed configuration modifications without writing.",)parser.add_argument("--force",action="store_true",help="Overwrite existing configuration settings.",)parser.add_argument("--all", action="store_true", help="Attempt connection to all detected agents.")args = parser.parse_args()if not args.agent and not args.all:parser.print_help()print("\nAvailable agents:")for a in ADAPTERS:print(f" - {a.name:15} ({a.display_name})")sys.exit(0)run_connect(args)if __name__ == "__main__":main()
3 unmodified lines45678910107 unmodified lines11811912012112212312419 unmodified lines14414514614714814915015111 unmodified lines1631641651661671681696 unmodified lines1761771781791801811821835 unmodified lines18919019119219319419519612 unmodified lines20921021121221321421533 unmodified lines2492502512522532542559 unmodified lines2652662672682692702718 unmodified lines2802812822832842852863 unmodified linesimport threadingimport timeimport atexitfrom typing import Dict, Any, List, Optional, TypeVar, UnionT = TypeVar("T")107 unmodified linesPRIMARY KEY (scope, key))""")conn.execute("CREATE INDEX IF NOT EXISTS idx_kv_scope ON kv_store(scope)")conn.execute("""CREATE TABLE IF NOT EXISTS audit_log (id INTEGER PRIMARY KEY AUTOINCREMENT,19 unmodified linestry:conn = self._get_conn()row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()if row:val = json.loads(row["value"])11 unmodified linesconn = self._get_conn()conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(value)))conn.commit()return value6 unmodified linestry:conn = self._get_conn()cur = conn.execute("DELETE FROM kv_store WHERE scope = ? AND key = ?",(scope, key))conn.commit()return cur.rowcount > 05 unmodified linestry:conn = self._get_conn()rows = conn.execute("SELECT key, value FROM kv_store WHERE scope = ?",(scope,)).fetchall()results = []for r in rows:12 unmodified linesconn = self._get_conn()row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key)).fetchone()obj = json.loads(row["value"]) if row else {}if not isinstance(obj, dict):33 unmodified linesconn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(obj)))conn.commit()return obj9 unmodified linesconn = self._get_conn()cur = conn.execute("INSERT INTO audit_log (ts, agent_id, message) VALUES (?, ?, ?)",(int(time.time() * 1000), author, message))conn.commit()row_id = str(cur.lastrowid)8 unmodified linesconn = self._get_conn()rows = conn.execute("SELECT id, ts, agent_id, message FROM audit_log ORDER BY ts DESC LIMIT ?",(limit,)).fetchall()return [dict(r) for r in rows]except Exception as e:3 unmodified lines45678910107 unmodified lines11811912012112212312412512619 unmodified lines14614714814915015115211 unmodified lines1641651661671681691706 unmodified lines1771781791801811821835 unmodified lines18919019119219319419512 unmodified lines20820921021121221321433 unmodified lines2482492502512522532549 unmodified lines2642652662672682692708 unmodified lines2792802812822832842853 unmodified linesimport threadingimport timeimport atexitfrom typing import Dict, Any, List, Optional, TypeVarT = TypeVar("T")107 unmodified linesPRIMARY KEY (scope, key))""")conn.execute("CREATE INDEX IF NOT EXISTS idx_kv_scope ON kv_store(scope)")conn.execute("""CREATE TABLE IF NOT EXISTS audit_log (id INTEGER PRIMARY KEY AUTOINCREMENT,19 unmodified linestry:conn = self._get_conn()row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?", (scope, key)).fetchone()if row:val = json.loads(row["value"])11 unmodified linesconn = self._get_conn()conn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(value)),)conn.commit()return value6 unmodified linestry:conn = self._get_conn()cur = conn.execute("DELETE FROM kv_store WHERE scope = ? AND key = ?", (scope, key))conn.commit()return cur.rowcount > 05 unmodified linestry:conn = self._get_conn()rows = conn.execute("SELECT key, value FROM kv_store WHERE scope = ?", (scope,)).fetchall()results = []for r in rows:12 unmodified linesconn = self._get_conn()row = conn.execute("SELECT value FROM kv_store WHERE scope = ? AND key = ?",(scope, key),).fetchone()obj = json.loads(row["value"]) if row else {}if not isinstance(obj, dict):33 unmodified linesconn.execute("INSERT OR REPLACE INTO kv_store (scope, key, value) VALUES (?, ?, ?)",(scope, key, json.dumps(obj)),)conn.commit()return obj9 unmodified linesconn = self._get_conn()cur = conn.execute("INSERT INTO audit_log (ts, agent_id, message) VALUES (?, ?, ?)",(int(time.time() * 1000), author, message),)conn.commit()row_id = str(cur.lastrowid)8 unmodified linesconn = self._get_conn()rows = conn.execute("SELECT id, ts, agent_id, message FROM audit_log ORDER BY ts DESC LIMIT ?",(limit,),).fetchall()return [dict(r) for r in rows]except Exception as e:
6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758593 unmodified lines636465666768697071727374757677787980818283846 unmodified linessys.path.append(os.path.dirname(os.path.abspath(__file__)))from db import StateKVdef import_old_data(old_db_path: str, kv: StateKV) -> bool:if not os.path.exists(old_db_path):print(f"[import] Error: Path {old_db_path} does not exist.")return Falseprint(f"[import] Starting migration from: {old_db_path}")count = 0for filename in os.listdir(old_db_path):if not filename.endswith(".bin"):continueif not filename.startswith("mem%3A"):continue# URL decode the scope name (e.g. mem%3Asessions.bin -> mem:sessions)decoded_name = urllib.parse.unquote(filename)scope = decoded_name[:-4] if decoded_name.endswith(".bin") else decoded_namefilepath = os.path.join(old_db_path, filename)try:with open(filepath, "rb") as f:data = f.read()if not data:continue# Find the last matching JSON curly brace to strip binary padding/footerstry:last_brace = data.rindex(b'}')json_str = data[:last_brace+1].decode("utf-8")records = json.loads(json_str)except Exception as e:print(f"[import] Skipping {filename}: could not parse JSON ({e})")continueprint(f"[import] Scope '{scope}': found {len(records)} items. Migrating...")for key, val in records.items():kv.set(scope, key, val)count += 1except Exception as e:print(f"[import] Failed to process {filename}: {e}")if count > 0:print("[import] Creating Dolt version commit...")kv.commit_version("Import legacy AgentCache database from Hugging Face", "system")print(f"[import] Finished! Migrated {count} total records into Dolt SQL.")return True3 unmodified lines# Prioritize the restored HF data in the user's home folder, falling back to local workspace datahome_path = os.path.expanduser(os.path.join("~", ".agentcache", "state_store.db"))workspace_path = r"d:\Downloads\Projects\Other Projects\agentcache\agentcache\data\state_store.db"if os.path.exists(home_path):default_path = home_pathprint(f"[import] Found restored HF data at: {default_path}")else:default_path = workspace_pathprint(f"[import] HF data not found at home path, falling back to workspace: {default_path}")# Allow custom path via command line argumentif len(sys.argv) > 1:default_path = sys.argv[1]print(f"[import] Overriding path with CLI argument: {default_path}")# Initialize connectionprint(f"[import] Initializing Dolt StateKV...")kv = StateKV()import_old_data(default_path, kv)6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061623 unmodified lines66676869707172737475767778798081828384858687886 unmodified linessys.path.append(os.path.dirname(os.path.abspath(__file__)))from db import StateKVdef import_old_data(old_db_path: str, kv: StateKV) -> bool:if not os.path.exists(old_db_path):print(f"[import] Error: Path {old_db_path} does not exist.")return Falseprint(f"[import] Starting migration from: {old_db_path}")count = 0for filename in os.listdir(old_db_path):if not filename.endswith(".bin"):continueif not filename.startswith("mem%3A"):continue# URL decode the scope name (e.g. mem%3Asessions.bin -> mem:sessions)decoded_name = urllib.parse.unquote(filename)scope = decoded_name[:-4] if decoded_name.endswith(".bin") else decoded_namefilepath = os.path.join(old_db_path, filename)try:with open(filepath, "rb") as f:data = f.read()if not data:continue# Find the last matching JSON curly brace to strip binary padding/footerstry:last_brace = data.rindex(b"}")json_str = data[: last_brace + 1].decode("utf-8")records = json.loads(json_str)except Exception as e:print(f"[import] Skipping {filename}: could not parse JSON ({e})")continueprint(f"[import] Scope '{scope}': found {len(records)} items. Migrating...")for key, val in records.items():kv.set(scope, key, val)count += 1except Exception as e:print(f"[import] Failed to process {filename}: {e}")if count > 0:print("[import] Creating Dolt version commit...")kv.commit_version("Import legacy AgentCache database from Hugging Face", "system")print(f"[import] Finished! Migrated {count} total records into Dolt SQL.")return True3 unmodified lines# Prioritize the restored HF data in the user's home folder, falling back to local workspace datahome_path = os.path.expanduser(os.path.join("~", ".agentcache", "state_store.db"))workspace_path = r"d:\Downloads\Projects\Other Projects\agentcache\agentcache\data\state_store.db"if os.path.exists(home_path):default_path = home_pathprint(f"[import] Found restored HF data at: {default_path}")else:default_path = workspace_pathprint(f"[import] HF data not found at home path, falling back to workspace: {default_path}")# Allow custom path via command line argumentif len(sys.argv) > 1:default_path = sys.argv[1]print(f"[import] Overriding path with CLI argument: {default_path}")# Initialize connectionprint("[import] Initializing Dolt StateKV...")kv = StateKV()import_old_data(default_path, kv)
7 unmodified lines891011121314151617181919 unmodified lines39404142434445464748495051527 unmodified lines606162636465666711 unmodified lines79808182838485868788899010 unmodified lines1011021031041051061071087 unmodified linesAntigravity sync functions have been moved to examples/antigravity_sync.py (D1.3).All tool calls are proxied to the HTTP API."""import sysimport jsonimport osimport requestsBASE = (os.getenv("AGENTCACHE_URL") or os.getenv("AGENTMEMORY_URL") or "http://127.0.0.1:3111").rstrip("/")if not BASE.endswith("/agentcache") and not BASE.endswith("/agentmemory"):BASE = f"{BASE}/agentcache"19 unmodified linesparams = req.get("params") or {}if method == "initialize":send({"jsonrpc": "2.0", "id": req_id,"result": {"protocolVersion": "2024-11-05","capabilities": {"tools": {}},"serverInfo": {"name": "agentcache-local", "version": "0.9.8"}}})elif method == "initialized":pass # notification — no response7 unmodified linestools = r.json().get("tools", [])send({"jsonrpc": "2.0", "id": req_id, "result": {"tools": tools}})except Exception as e:send({"jsonrpc": "2.0", "id": req_id,"error": {"code": -32000, "message": f"agentmemory unreachable: {e}"}})elif method == "tools/call":name = params.get("name")11 unmodified linesresult = {"content": [{"type": "text", "text": json.dumps(result)}]}send({"jsonrpc": "2.0", "id": req_id, "result": result})except Exception as e:send({"jsonrpc": "2.0", "id": req_id,"error": {"code": -32000, "message": str(e)}})elif req_id is not None:send({"jsonrpc": "2.0", "id": req_id,"error": {"code": -32601, "message": "Method not found"}})def main():10 unmodified linesexcept Exception as e:req_id = req.get("id") if isinstance(req, dict) else Noneif req_id is not None:send({"jsonrpc": "2.0", "id": req_id,"error": {"code": -32603, "message": f"Internal error: {e}"}})if __name__ == "__main__":7 unmodified lines8910111213141516171819202122232419 unmodified lines44454647484950515253545556575859607 unmodified lines6869707172737475767778798081828311 unmodified lines959697989910010110210310410510610710810911011111211311411511610 unmodified lines1271281291301311321331341351361371381397 unmodified linesAntigravity sync functions have been moved to examples/antigravity_sync.py (D1.3).All tool calls are proxied to the HTTP API."""import sysimport jsonimport osimport requestsBASE = (os.getenv("AGENTCACHE_URL")or os.getenv("AGENTMEMORY_URL")or "http://127.0.0.1:3111").rstrip("/")if not BASE.endswith("/agentcache") and not BASE.endswith("/agentmemory"):BASE = f"{BASE}/agentcache"19 unmodified linesparams = req.get("params") or {}if method == "initialize":send({"jsonrpc": "2.0","id": req_id,"result": {"protocolVersion": "2024-11-05","capabilities": {"tools": {}},"serverInfo": {"name": "agentcache-local", "version": "0.9.8"},},})elif method == "initialized":pass # notification — no response7 unmodified linestools = r.json().get("tools", [])send({"jsonrpc": "2.0", "id": req_id, "result": {"tools": tools}})except Exception as e:send({"jsonrpc": "2.0","id": req_id,"error": {"code": -32000,"message": f"agentmemory unreachable: {e}",},})elif method == "tools/call":name = params.get("name")11 unmodified linesresult = {"content": [{"type": "text", "text": json.dumps(result)}]}send({"jsonrpc": "2.0", "id": req_id, "result": result})except Exception as e:send({"jsonrpc": "2.0","id": req_id,"error": {"code": -32000, "message": str(e)},})elif req_id is not None:send({"jsonrpc": "2.0","id": req_id,"error": {"code": -32601, "message": "Method not found"},})def main():10 unmodified linesexcept Exception as e:req_id = req.get("id") if isinstance(req, dict) else Noneif req_id is not None:send({"jsonrpc": "2.0","id": req_id,"error": {"code": -32603, "message": f"Internal error: {e}"},})if __name__ == "__main__":
21 unmodified lines222324252627282930313233343536373839404142434445464748491 unmodified line515253545556575859606162636465666768697071727374757677787980818283848586878814 unmodified lines1031041051061071081097 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641657 unmodified lines1731741751761771781791801811821831841851861871881891901919 unmodified lines20120220320420520620718 unmodified lines22622722822923023123223323423513 unmodified lines24925025125225325425515 unmodified lines2712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013024 unmodified lines3073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483494 unmodified lines3543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994001 unmodified line4024034044054064074085 unmodified lines4144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674683 unmodified lines47247347447547647747847948013 unmodified lines49449549649749849914 unmodified lines5145155165175185195205215225235245255265275285295305315325335345355365375385395403 unmodified lines5445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785 unmodified lines58458558658758858959059159259359459559659759859960060160260360460560660721 unmodified lines]LESSON_PATTERNS = [re.compile(r"\b(always|never|don'?t|do not|make sure|remember to|note:|caveat:|warning:)\b[^.\n]{10,200}[.!\n]", re.IGNORECASE),re.compile(r"\b(prefer|avoid)\s[^.\n]{10,200}[.!\n]", re.IGNORECASE),]def generate_id(prefix: str) -> str:import uuidreturn f"{prefix}_{uuid.uuid4().hex}"def fingerprint_id(prefix: str, content: str) -> str:# Hash content for stable ID (similar to TS fingerprintId)h = hashlib.sha256(content.strip().encode("utf-8")).hexdigest()return f"{prefix}_{h[:32]}"def is_sensitive(path: str) -> bool:return any(pattern.search(path) for pattern in SENSITIVE_PATH_PATTERNS)def derive_project(cwd: str) -> str:if not cwd:return "unknown"parts = [p for p in re.split(r'[\\/]', cwd) if p]return parts[-1] if parts else "unknown"def to_text(content: Any) -> str:if isinstance(content, str):return content1 unmodified linereturn ""parts = []for item in content:if isinstance(item, dict) and item.get("type") == "text" and isinstance(item.get("text"), str):parts.append(item["text"])return "\n".join(parts)def extract_tool_uses(content: Any) -> List[Dict[str, Any]]:if not isinstance(content, list):return []out = []for item in content:if isinstance(item, dict) and item.get("type") == "tool_use":out.append({"id": item.get("id", ""),"name": item.get("name", "unknown"),"input": item.get("input")})return outdef extract_tool_results(content: Any) -> List[Dict[str, Any]]:if not isinstance(content, list):return []out = []for item in content:if isinstance(item, dict) and item.get("type") == "tool_result":out.append({"toolUseId": item.get("tool_use_id", ""),"output": item.get("content"),"isError": item.get("is_error") is True})return outdef parse_jsonl_text(text: str, fallback_session_id: str = None) -> Dict[str, Any]:lines = [l for l in text.split("\n") if l.strip()]entries = []for line in lines:try:14 unmodified linessession_id = entry["sessionId"]if entry.get("cwd") and not cwd:cwd = entry["cwd"]ts = entry.get("timestamp") or datetime.datetime.utcnow().isoformat() + "Z"if not first_ts:first_ts = ts7 unmodified linestool_results = extract_tool_results(content)if tool_results:for result in tool_results:observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "post_tool_failure" if result["isError"] else "post_tool_use","toolName": None,"toolInput": {"toolUseId": result["toolUseId"]},"toolOutput": result["output"],"raw": entry})else:txt = to_text(content)if txt.strip():observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "prompt_submit","userPrompt": txt,"raw": entry})elif entry.get("type") == "assistant" and role == "assistant":txt = to_text(content)tools = extract_tool_uses(content)if txt.strip():observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "stop","assistantResponse": txt,"raw": entry})for tool in tools:observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "pre_tool_use","toolName": tool["name"],"toolInput": tool["input"],"raw": {"toolUseId": tool["id"], "entry": entry}})effective_session_id = session_id or fallback_session_id or generate_id("sess")for obs in observations:7 unmodified lines"cwd": cwd or os.getcwd(),"startedAt": first_ts or now_iso,"endedAt": last_ts or now_iso,"observations": observations}def derive_crystal_and_lessons(kv,session_id: str,project: str,raw_obs: List[Dict[str, Any]],compressed: List[Dict[str, Any]],first_prompt: str = None) -> None:from functions import KVif not raw_obs:returncreated_at = datetime.datetime.utcnow().isoformat() + "Z"9 unmodified linesassistant_texts = []user_prompts = []for r in raw_obs:if isinstance(r.get("assistantResponse"), str) and r["assistantResponse"].strip():assistant_texts.append(r["assistantResponse"])if isinstance(r.get("userPrompt"), str) and r["userPrompt"].strip():user_prompts.append(r["userPrompt"])18 unmodified linesexisting = kv.get(KV.lessons, lesson_id)if existing:existing_sources = existing.get("sourceIds", [])merged_sources = existing_sources if session_id in existing_sources else (existing_sources + [session_id])existing_tags = existing.get("tags", [])merged_tags = existing_tags if "auto-import" in existing_tags else (existing_tags + ["auto-import"])existing["sourceIds"] = merged_sourcesexisting["tags"] = merged_tagsexisting["reinforcements"] = existing.get("reinforcements", 0) + 113 unmodified lines"tags": ["auto-import"],"createdAt": created_at,"updatedAt": created_at,"decayRate": 0.05}kv.set(KV.lessons, lesson_id, lesson)lesson_ids.append(lesson_id)15 unmodified linesexisting_crystal = kv.get(KV.crystals, crystal_id) or {}crystal = {"id": crystal_id,"narrative": narrative_preview or f"Session {session_id[:12]} ({len(raw_obs)} observations)","keyOutcomes": list(tools)[:8],"filesAffected": list(files)[:20],"lessons": lesson_ids,"sourceActionIds": existing_crystal.get("sourceActionIds", []),"sessionId": session_id,"project": project,"createdAt": existing_crystal.get("createdAt", created_at)}kv.set(KV.crystals, crystal_id, crystal)except Exception:passdef find_jsonl_files(root: str, limit=200) -> Tuple[List[str], bool, int, bool]:out = []discovered = 0walked = 0traversal_cap = max(limit * 50, 50000)for dirpath, dirnames, filenames in os.walk(root):if walked >= traversal_cap:break# skip symlinks or hidden directoriesdirnames[:] = [d for d in dirnames if not d.startswith('.') and not os.path.islink(os.path.join(dirpath, d))]for name in filenames:walked += 1if walked >= traversal_cap:4 unmodified linesdiscovered += 1if len(out) < limit:out.append(full)traversal_capped = walked >= traversal_captruncated = discovered > len(out) or traversal_cappedreturn out, truncated, discovered, traversal_cappeddef import_jsonl_data(kv, path: str = None, max_files: int = None) -> Dict[str, Any]:from functions import KV, build_synthetic_compression, IndexPersistence, _bm25_index, _vector_indexdefault_root = os.path.expanduser(os.path.join("~", ".claude", "projects"))raw_path = path or default_rootexpanded = os.path.expanduser(raw_path)abs_path = os.path.abspath(expanded)if is_sensitive(abs_path):return {"success": False, "error": "refusing to process sensitive-looking path"}if os.path.islink(abs_path):return {"success": False, "error": "symlinks are not supported"}if not os.path.exists(abs_path):return {"success": False, "error": "path not found"}limit = max_files if isinstance(max_files, int) and max_files > 0 else MAX_FILES_DEFAULTlimit = min(limit, MAX_FILES_UPPER_BOUND)files = []truncated = Falsediscovered = 0traversal_capped = Falseif os.path.isdir(abs_path):files, truncated, discovered, traversal_capped = find_jsonl_files(abs_path, limit)elif os.path.isfile(abs_path) and abs_path.endswith(".jsonl"):files = [abs_path]discovered = 1else:return {"success": False, "error": "path must be a .jsonl file or directory"}if not files:return {"success": True,4 unmodified lines"truncated": truncated,"traversalCapped": traversal_capped,"maxFiles": limit,"maxFilesUpperBound": MAX_FILES_UPPER_BOUND}session_ids = []observation_count = 0for file in files:if is_sensitive(file):continueif os.path.islink(file):continuetry:with open(file, "r", encoding="utf-8", errors="ignore") as f:text = f.read()except Exception as e:print(f"[import-jsonl] Failed to read {file}: {e}")continueparsed = parse_jsonl_text(text, generate_id("sess"))if not parsed["observations"]:continuefirst_prompt_obs = Nonefor o in parsed["observations"]:if isinstance(o.get("userPrompt"), str) and o["userPrompt"].strip():first_prompt_obs = obreakfirst_prompt = Noneif first_prompt_obs:first_prompt = re.sub(r"\s+", " ", first_prompt_obs["userPrompt"]).strip()[:200]existing = kv.get(KV.sessions, parsed["sessionId"])if existing:existing["observationCount"] = existing.get("observationCount", 0) + len(parsed["observations"])if parsed["endedAt"] > existing.get("endedAt", ""):existing["endedAt"] = parsed["endedAt"]if existing.get("status") == "active":existing["status"] = "completed"existing_tags = existing.get("tags", [])if "jsonl-import" not in existing_tags:existing["tags"] = existing_tags + ["jsonl-import"]1 unmodified lineexisting["firstPrompt"] = first_promptif not existing.get("id"):existing["id"] = parsed["sessionId"]kv.set(KV.sessions, parsed["sessionId"], existing)else:session = {5 unmodified lines"status": "completed","observationCount": len(parsed["observations"]),"tags": ["jsonl-import"],"firstPrompt": first_prompt}kv.set(KV.sessions, session["id"], session)from functions import _bm25_index, vector_index_add_guardedcompressed = []for obs in parsed["observations"]:synthetic = build_synthetic_compression(obs)compressed.append(synthetic)kv.set(KV.observations(parsed["sessionId"]), obs["id"], synthetic)# Index_bm25_index.add(synthetic)comb_text = synthetic["title"] + " " + (synthetic.get("narrative") or "")vector_index_add_guarded(synthetic["id"], synthetic["sessionId"], comb_text, {"kind": "synthetic", "logId": synthetic["id"]})observation_count += len(parsed["observations"])session_ids.append(parsed["sessionId"])derive_crystal_and_lessons(kv,parsed["sessionId"],parsed["project"],parsed["observations"],compressed,first_prompt)# Save the updated persistence stateimport functionsif functions._index_persistence:try:functions._index_persistence.save()except Exception as e:print(f"[import-jsonl] Warning saving index persistence: {e}")# Audit trailtry:from functions import log_auditlog_audit(kv, "import", "mem::replay::import-jsonl", f"Imported {len(session_ids)} sessions: {','.join(session_ids[:3])}...")except Exception:pass# Dolt commit if enabledtry:kv.commit_version(f"Import {len(session_ids)} Claude Code sessions from JSONL", "system")except Exception:passreturn {"success": True,"imported": len(files),3 unmodified lines"truncated": truncated,"traversalCapped": traversal_capped,"maxFiles": limit,"maxFilesUpperBound": MAX_FILES_UPPER_BOUND}def kind_from_hook(obs: Dict[str, Any]) -> str:ht = obs.get("hookType")if ht == "session_start":13 unmodified lineselse:return "hook"def label_for(obs: Dict[str, Any], kind: str) -> str:if kind == "prompt":val = obs.get("userPrompt") or "User prompt"14 unmodified lineselse:return obs.get("hookType") or ""def estimate_duration_ms(event: Dict[str, Any]) -> int:body = event.get("body") or ""tool_input = event.get("toolInput") or ""tool_output = event.get("toolOutput") or ""chars = len(body)if isinstance(tool_input, str):chars += len(tool_input)elif tool_input is not None:chars += len(json.dumps(tool_input))if isinstance(tool_output, str):chars += len(tool_output)elif tool_output is not None:chars += len(json.dumps(tool_output))if chars == 0:return 300ms = round((chars / 40) * 1000)return max(300, min(20000, ms))def project_timeline(observations: List[Dict[str, Any]]) -> Dict[str, Any]:if not observations:now = datetime.datetime.utcnow().isoformat() + "Z"3 unmodified lines"endedAt": now,"totalDurationMs": 0,"eventCount": 0,"events": []}sorted_obs = sorted(observations, key=lambda o: o.get("timestamp", ""))started_at = sorted_obs[0].get("timestamp", "")try:import dateutil.parserstart_dt = dateutil.parser.isoparse(started_at)start_ms = start_dt.timestamp() * 1000except Exception:start_ms = 0events = []synthetic_offset = 0all_same_ts = all(o.get("timestamp") == started_at for o in sorted_obs)for obs in sorted_obs:kind = kind_from_hook(obs)body = obs.get("userPrompt") if kind == "prompt" else (obs.get("assistantResponse") if kind == "response" else None)try:import dateutil.parserobs_dt = dateutil.parser.isoparse(obs.get("timestamp", ""))obs_ms = obs_dt.timestamp() * 1000offset_ms = int(max(0, obs_ms - start_ms)) if not all_same_ts else synthetic_offsetexcept Exception:offset_ms = synthetic_offsetevent = {"id": obs.get("id"),"sessionId": obs.get("sessionId"),5 unmodified lines"body": body,"toolName": obs.get("toolName"),"toolInput": obs.get("toolInput"),"toolOutput": obs.get("toolOutput")}event["durationMs"] = estimate_duration_ms(event)events.append(event)synthetic_offset += event["durationMs"]if not events:total_duration_ms = 0else:last = events[-1]total_duration_ms = last["offsetMs"] + last["durationMs"]return {"sessionId": sorted_obs[0].get("sessionId"),"startedAt": started_at,"endedAt": sorted_obs[-1].get("timestamp"),"totalDurationMs": total_duration_ms,"eventCount": len(events),"events": events}21 unmodified lines222324252627282930313233343536373839404142434445464748495051525354555657581 unmodified line6061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710814 unmodified lines1231241251261271281297 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941957 unmodified lines2032042052062072082092102112122132142152162172182192202212229 unmodified lines23223323423523623723823924024118 unmodified lines26026126226326426526626726826927027127227327427527627713 unmodified lines29129229329429529629715 unmodified lines3133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493504 unmodified lines3553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024 unmodified lines4074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564571 unmodified line4594604614624634644655 unmodified lines4714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395403 unmodified lines54454554654754854955055155255313 unmodified lines56756856957057157257314 unmodified lines5885895905915925935945955965975985996006016026036046056066076086096106116126136146156163 unmodified lines6206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616625 unmodified lines66866967067167267367467567667767867968068168268368468568668768868969021 unmodified lines]LESSON_PATTERNS = [re.compile(r"\b(always|never|don'?t|do not|make sure|remember to|note:|caveat:|warning:)\b[^.\n]{10,200}[.!\n]",re.IGNORECASE,),re.compile(r"\b(prefer|avoid)\s[^.\n]{10,200}[.!\n]", re.IGNORECASE),]def generate_id(prefix: str) -> str:import uuidreturn f"{prefix}_{uuid.uuid4().hex}"def fingerprint_id(prefix: str, content: str) -> str:# Hash content for stable ID (similar to TS fingerprintId)h = hashlib.sha256(content.strip().encode("utf-8")).hexdigest()return f"{prefix}_{h[:32]}"def is_sensitive(path: str) -> bool:return any(pattern.search(path) for pattern in SENSITIVE_PATH_PATTERNS)def derive_project(cwd: str) -> str:if not cwd:return "unknown"parts = [p for p in re.split(r"[\\/]", cwd) if p]return parts[-1] if parts else "unknown"def to_text(content: Any) -> str:if isinstance(content, str):return content1 unmodified linereturn ""parts = []for item in content:if (isinstance(item, dict)and item.get("type") == "text"and isinstance(item.get("text"), str)):parts.append(item["text"])return "\n".join(parts)def extract_tool_uses(content: Any) -> List[Dict[str, Any]]:if not isinstance(content, list):return []out = []for item in content:if isinstance(item, dict) and item.get("type") == "tool_use":out.append({"id": item.get("id", ""),"name": item.get("name", "unknown"),"input": item.get("input"),})return outdef extract_tool_results(content: Any) -> List[Dict[str, Any]]:if not isinstance(content, list):return []out = []for item in content:if isinstance(item, dict) and item.get("type") == "tool_result":out.append({"toolUseId": item.get("tool_use_id", ""),"output": item.get("content"),"isError": item.get("is_error") is True,})return outdef parse_jsonl_text(text: str, fallback_session_id: str = None) -> Dict[str, Any]:lines = [line_str for line_str in text.split("\n") if line_str.strip()]entries = []for line in lines:try:14 unmodified linessession_id = entry["sessionId"]if entry.get("cwd") and not cwd:cwd = entry["cwd"]ts = entry.get("timestamp") or datetime.datetime.utcnow().isoformat() + "Z"if not first_ts:first_ts = ts7 unmodified linestool_results = extract_tool_results(content)if tool_results:for result in tool_results:observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "post_tool_failure"if result["isError"]else "post_tool_use","toolName": None,"toolInput": {"toolUseId": result["toolUseId"]},"toolOutput": result["output"],"raw": entry,})else:txt = to_text(content)if txt.strip():observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "prompt_submit","userPrompt": txt,"raw": entry,})elif entry.get("type") == "assistant" and role == "assistant":txt = to_text(content)tools = extract_tool_uses(content)if txt.strip():observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "stop","assistantResponse": txt,"raw": entry,})for tool in tools:observations.append({"id": generate_id("obs"),"sessionId": session_id or "imported","timestamp": ts,"hookType": "pre_tool_use","toolName": tool["name"],"toolInput": tool["input"],"raw": {"toolUseId": tool["id"], "entry": entry},})effective_session_id = session_id or fallback_session_id or generate_id("sess")for obs in observations:7 unmodified lines"cwd": cwd or os.getcwd(),"startedAt": first_ts or now_iso,"endedAt": last_ts or now_iso,"observations": observations,}def derive_crystal_and_lessons(kv,session_id: str,project: str,raw_obs: List[Dict[str, Any]],compressed: List[Dict[str, Any]],first_prompt: str = None,) -> None:from functions import KVif not raw_obs:returncreated_at = datetime.datetime.utcnow().isoformat() + "Z"9 unmodified linesassistant_texts = []user_prompts = []for r in raw_obs:if (isinstance(r.get("assistantResponse"), str)and r["assistantResponse"].strip()):assistant_texts.append(r["assistantResponse"])if isinstance(r.get("userPrompt"), str) and r["userPrompt"].strip():user_prompts.append(r["userPrompt"])18 unmodified linesexisting = kv.get(KV.lessons, lesson_id)if existing:existing_sources = existing.get("sourceIds", [])merged_sources = (existing_sourcesif session_id in existing_sourceselse (existing_sources + [session_id]))existing_tags = existing.get("tags", [])merged_tags = (existing_tagsif "auto-import" in existing_tagselse (existing_tags + ["auto-import"]))existing["sourceIds"] = merged_sourcesexisting["tags"] = merged_tagsexisting["reinforcements"] = existing.get("reinforcements", 0) + 113 unmodified lines"tags": ["auto-import"],"createdAt": created_at,"updatedAt": created_at,"decayRate": 0.05,}kv.set(KV.lessons, lesson_id, lesson)lesson_ids.append(lesson_id)15 unmodified linesexisting_crystal = kv.get(KV.crystals, crystal_id) or {}crystal = {"id": crystal_id,"narrative": narrative_previewor f"Session {session_id[:12]} ({len(raw_obs)} observations)","keyOutcomes": list(tools)[:8],"filesAffected": list(files)[:20],"lessons": lesson_ids,"sourceActionIds": existing_crystal.get("sourceActionIds", []),"sessionId": session_id,"project": project,"createdAt": existing_crystal.get("createdAt", created_at),}kv.set(KV.crystals, crystal_id, crystal)except Exception:passdef find_jsonl_files(root: str, limit=200) -> Tuple[List[str], bool, int, bool]:out = []discovered = 0walked = 0traversal_cap = max(limit * 50, 50000)for dirpath, dirnames, filenames in os.walk(root):if walked >= traversal_cap:break# skip symlinks or hidden directoriesdirnames[:] = [dfor d in dirnamesif not d.startswith(".") and not os.path.islink(os.path.join(dirpath, d))]for name in filenames:walked += 1if walked >= traversal_cap:4 unmodified linesdiscovered += 1if len(out) < limit:out.append(full)traversal_capped = walked >= traversal_captruncated = discovered > len(out) or traversal_cappedreturn out, truncated, discovered, traversal_cappeddef import_jsonl_data(kv, path: str = None, max_files: int = None) -> Dict[str, Any]:from functions import KV, build_synthetic_compression, _bm25_indexdefault_root = os.path.expanduser(os.path.join("~", ".claude", "projects"))raw_path = path or default_rootexpanded = os.path.expanduser(raw_path)abs_path = os.path.abspath(expanded)if is_sensitive(abs_path):return {"success": False, "error": "refusing to process sensitive-looking path"}if os.path.islink(abs_path):return {"success": False, "error": "symlinks are not supported"}if not os.path.exists(abs_path):return {"success": False, "error": "path not found"}limit = (max_files if isinstance(max_files, int) and max_files > 0 else MAX_FILES_DEFAULT)limit = min(limit, MAX_FILES_UPPER_BOUND)files = []truncated = Falsediscovered = 0traversal_capped = Falseif os.path.isdir(abs_path):files, truncated, discovered, traversal_capped = find_jsonl_files(abs_path, limit)elif os.path.isfile(abs_path) and abs_path.endswith(".jsonl"):files = [abs_path]discovered = 1else:return {"success": False, "error": "path must be a .jsonl file or directory"}if not files:return {"success": True,4 unmodified lines"truncated": truncated,"traversalCapped": traversal_capped,"maxFiles": limit,"maxFilesUpperBound": MAX_FILES_UPPER_BOUND,}session_ids = []observation_count = 0for file in files:if is_sensitive(file):continueif os.path.islink(file):continuetry:with open(file, "r", encoding="utf-8", errors="ignore") as f:text = f.read()except Exception as e:print(f"[import-jsonl] Failed to read {file}: {e}")continueparsed = parse_jsonl_text(text, generate_id("sess"))if not parsed["observations"]:continuefirst_prompt_obs = Nonefor o in parsed["observations"]:if isinstance(o.get("userPrompt"), str) and o["userPrompt"].strip():first_prompt_obs = obreakfirst_prompt = Noneif first_prompt_obs:first_prompt = re.sub(r"\s+", " ", first_prompt_obs["userPrompt"]).strip()[:200]existing = kv.get(KV.sessions, parsed["sessionId"])if existing:existing["observationCount"] = existing.get("observationCount", 0) + len(parsed["observations"])if parsed["endedAt"] > existing.get("endedAt", ""):existing["endedAt"] = parsed["endedAt"]if existing.get("status") == "active":existing["status"] = "completed"existing_tags = existing.get("tags", [])if "jsonl-import" not in existing_tags:existing["tags"] = existing_tags + ["jsonl-import"]1 unmodified lineexisting["firstPrompt"] = first_promptif not existing.get("id"):existing["id"] = parsed["sessionId"]kv.set(KV.sessions, parsed["sessionId"], existing)else:session = {5 unmodified lines"status": "completed","observationCount": len(parsed["observations"]),"tags": ["jsonl-import"],"firstPrompt": first_prompt,}kv.set(KV.sessions, session["id"], session)from functions import vector_index_add_guardedcompressed = []for obs in parsed["observations"]:synthetic = build_synthetic_compression(obs)compressed.append(synthetic)kv.set(KV.observations(parsed["sessionId"]), obs["id"], synthetic)# Index_bm25_index.add(synthetic)comb_text = synthetic["title"] + " " + (synthetic.get("narrative") or "")vector_index_add_guarded(synthetic["id"],synthetic["sessionId"],comb_text,{"kind": "synthetic", "logId": synthetic["id"]},)observation_count += len(parsed["observations"])session_ids.append(parsed["sessionId"])derive_crystal_and_lessons(kv,parsed["sessionId"],parsed["project"],parsed["observations"],compressed,first_prompt,)# Save the updated persistence stateimport functionsif functions._index_persistence:try:functions._index_persistence.save()except Exception as e:print(f"[import-jsonl] Warning saving index persistence: {e}")# Audit trailtry:from functions import log_auditlog_audit(kv,"import","mem::replay::import-jsonl",f"Imported {len(session_ids)} sessions: {','.join(session_ids[:3])}...",)except Exception:pass# Dolt commit if enabledtry:kv.commit_version(f"Import {len(session_ids)} Claude Code sessions from JSONL", "system")except Exception:passreturn {"success": True,"imported": len(files),3 unmodified lines"truncated": truncated,"traversalCapped": traversal_capped,"maxFiles": limit,"maxFilesUpperBound": MAX_FILES_UPPER_BOUND,}def kind_from_hook(obs: Dict[str, Any]) -> str:ht = obs.get("hookType")if ht == "session_start":13 unmodified lineselse:return "hook"def label_for(obs: Dict[str, Any], kind: str) -> str:if kind == "prompt":val = obs.get("userPrompt") or "User prompt"14 unmodified lineselse:return obs.get("hookType") or ""def estimate_duration_ms(event: Dict[str, Any]) -> int:body = event.get("body") or ""tool_input = event.get("toolInput") or ""tool_output = event.get("toolOutput") or ""chars = len(body)if isinstance(tool_input, str):chars += len(tool_input)elif tool_input is not None:chars += len(json.dumps(tool_input))if isinstance(tool_output, str):chars += len(tool_output)elif tool_output is not None:chars += len(json.dumps(tool_output))if chars == 0:return 300ms = round((chars / 40) * 1000)return max(300, min(20000, ms))def project_timeline(observations: List[Dict[str, Any]]) -> Dict[str, Any]:if not observations:now = datetime.datetime.utcnow().isoformat() + "Z"3 unmodified lines"endedAt": now,"totalDurationMs": 0,"eventCount": 0,"events": [],}sorted_obs = sorted(observations, key=lambda o: o.get("timestamp", ""))started_at = sorted_obs[0].get("timestamp", "")try:import dateutil.parserstart_dt = dateutil.parser.isoparse(started_at)start_ms = start_dt.timestamp() * 1000except Exception:start_ms = 0events = []synthetic_offset = 0all_same_ts = all(o.get("timestamp") == started_at for o in sorted_obs)for obs in sorted_obs:kind = kind_from_hook(obs)body = (obs.get("userPrompt")if kind == "prompt"else (obs.get("assistantResponse") if kind == "response" else None))try:import dateutil.parserobs_dt = dateutil.parser.isoparse(obs.get("timestamp", ""))obs_ms = obs_dt.timestamp() * 1000offset_ms = (int(max(0, obs_ms - start_ms)) if not all_same_ts else synthetic_offset)except Exception:offset_ms = synthetic_offsetevent = {"id": obs.get("id"),"sessionId": obs.get("sessionId"),5 unmodified lines"body": body,"toolName": obs.get("toolName"),"toolInput": obs.get("toolInput"),"toolOutput": obs.get("toolOutput"),}event["durationMs"] = estimate_duration_ms(event)events.append(event)synthetic_offset += event["durationMs"]if not events:total_duration_ms = 0else:last = events[-1]total_duration_ms = last["offsetMs"] + last["durationMs"]return {"sessionId": sorted_obs[0].get("sessionId"),"startedAt": started_at,"endedAt": sorted_obs[-1].get("timestamp"),"totalDurationMs": total_duration_ms,"eventCount": len(events),"events": events,}
10 unmodified lines111213141516171819202122238 unmodified lines3233343536371 unmodified line3940414243448 unmodified lines53545556575813 unmodified lines7273747576771 unmodified line798081828384854 unmodified lines90919293949510 unmodified linesimport osfrom flask import Blueprint, request, jsonifyimport functionsfrom functions import KVgraph_bp = Blueprint("graph", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# GET /agentcache/graph# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph", methods=["GET"])@graph_bp.route("/agentmemory/graph", methods=["GET"])def api_graph():8 unmodified lines# GET /agentcache/graph/stats# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/stats", methods=["GET"])@graph_bp.route("/agentmemory/graph/stats", methods=["GET"])def api_graph_stats():13 unmodified lines# POST /agentcache/graph/query# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/query", methods=["POST"])@graph_bp.route("/agentmemory/graph/query", methods=["POST"])def api_graph_query():1 unmodified lineif auth_err:return auth_errtry:body = request.get_json(force=True) or {}# start_node_id = body.get("startNodeId") # reserved for future usereturn jsonify({"nodes": [], "edges": [], "success": True}), 200except Exception as e:4 unmodified lines# POST /agentcache/graph/build# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/build", methods=["POST"])@graph_bp.route("/agentmemory/graph/build", methods=["POST"])def api_graph_build():10 unmodified lines111213141516171819202122238 unmodified lines323334353637381 unmodified line404142434445468 unmodified lines5556575859606113 unmodified lines757677787980811 unmodified line838485868788894 unmodified lines94959697989910010 unmodified linesimport osfrom flask import Blueprint, request, jsonifyimport functionsgraph_bp = Blueprint("graph", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# GET /agentcache/graph# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph", methods=["GET"])@graph_bp.route("/agentmemory/graph", methods=["GET"])def api_graph():8 unmodified lines# GET /agentcache/graph/stats# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/stats", methods=["GET"])@graph_bp.route("/agentmemory/graph/stats", methods=["GET"])def api_graph_stats():13 unmodified lines# POST /agentcache/graph/query# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/query", methods=["POST"])@graph_bp.route("/agentmemory/graph/query", methods=["POST"])def api_graph_query():1 unmodified lineif auth_err:return auth_errtry:request.get_json(force=True) or {}# start_node_id = body.get("startNodeId") # reserved for future usereturn jsonify({"nodes": [], "edges": [], "success": True}), 200except Exception as e:4 unmodified lines# POST /agentcache/graph/build# ---------------------------------------------------------------------------@graph_bp.route("/agentcache/graph/build", methods=["POST"])@graph_bp.route("/agentmemory/graph/build", methods=["POST"])def api_graph_build():
17 unmodified lines1819202122238 unmodified lines32333435363738394041421 unmodified line4445464748497 unmodified lines575859606162635 unmodified lines697071727374757677787980818283848586878889904 unmodified lines959697989910011 unmodified lines11211311411511611740 unmodified lines15815916016116216316416516617 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kvdef _get_embedding_provider():import app as app_modulereturn app_module.embedding_provider1 unmodified line# GET /auth.md (no auth required)# ---------------------------------------------------------------------------@health_bp.route("/auth.md", methods=["GET"])def auth_docs():"""Serve the agent onboarding documentation in Markdown format."""7 unmodified linesreturn Response(content,mimetype="text/markdown",headers={"Content-Type": "text/markdown; charset=utf-8"})except Exception as e:return jsonify({"error": f"failed to read auth.md: {e}"}), 5005 unmodified lines# GET /agentcache/livez (no auth required)# ---------------------------------------------------------------------------@health_bp.route("/agentcache/livez", methods=["GET"])@health_bp.route("/agentmemory/livez", methods=["GET"])def livez():port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))return jsonify({"status": "ok","service": "agentcache","viewerPort": port,"viewerSkipped": False,})# ---------------------------------------------------------------------------# GET /agentcache/health# ---------------------------------------------------------------------------@health_bp.route("/agentcache/health", methods=["GET"])@health_bp.route("/agentmemory/health", methods=["GET"])def health():4 unmodified lines# GET /agentcache/audit# ---------------------------------------------------------------------------@health_bp.route("/agentcache/audit", methods=["GET"])@health_bp.route("/agentmemory/audit", methods=["GET"])def api_audit():11 unmodified lines# GET /agentcache/config/flags# ---------------------------------------------------------------------------@health_bp.route("/agentcache/config/flags", methods=["GET"])@health_bp.route("/agentmemory/config/flags", methods=["GET"])def config_flags():40 unmodified lines"docsHref": "https://github.com/rohitg00/agentmemory/issues/138",},]return jsonify({"version": "0.9.8","provider": provider_kind,"embeddingProvider": embedding_prov,"flags": flags,})17 unmodified lines181920212223248 unmodified lines333435363738394041424344451 unmodified line474849505152537 unmodified lines616263646566675 unmodified lines73747576777879808182838485868788899091929394959697984 unmodified lines10310410510610710810911 unmodified lines12112212312412512612740 unmodified lines16816917017117217317417517617717817 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kvdef _get_embedding_provider():import app as app_modulereturn app_module.embedding_provider1 unmodified line# GET /auth.md (no auth required)# ---------------------------------------------------------------------------@health_bp.route("/auth.md", methods=["GET"])def auth_docs():"""Serve the agent onboarding documentation in Markdown format."""7 unmodified linesreturn Response(content,mimetype="text/markdown",headers={"Content-Type": "text/markdown; charset=utf-8"},)except Exception as e:return jsonify({"error": f"failed to read auth.md: {e}"}), 5005 unmodified lines# GET /agentcache/livez (no auth required)# ---------------------------------------------------------------------------@health_bp.route("/agentcache/livez", methods=["GET"])@health_bp.route("/agentmemory/livez", methods=["GET"])def livez():port = int(os.getenv("III_REST_PORT", os.getenv("PORT", "3111")))return jsonify({"status": "ok","service": "agentcache","viewerPort": port,"viewerSkipped": False,})# ---------------------------------------------------------------------------# GET /agentcache/health# ---------------------------------------------------------------------------@health_bp.route("/agentcache/health", methods=["GET"])@health_bp.route("/agentmemory/health", methods=["GET"])def health():4 unmodified lines# GET /agentcache/audit# ---------------------------------------------------------------------------@health_bp.route("/agentcache/audit", methods=["GET"])@health_bp.route("/agentmemory/audit", methods=["GET"])def api_audit():11 unmodified lines# GET /agentcache/config/flags# ---------------------------------------------------------------------------@health_bp.route("/agentcache/config/flags", methods=["GET"])@health_bp.route("/agentmemory/config/flags", methods=["GET"])def config_flags():40 unmodified lines"docsHref": "https://github.com/rohitg00/agentmemory/issues/138",},]return jsonify({"version": "0.9.8","provider": provider_kind,"embeddingProvider": embedding_prov,"flags": flags,})
17 unmodified lines1819202122238 unmodified lines32333435363714 unmodified lines52535455565758596061626364651 unmodified line6768697071727374755 unmodified lines8182838485868788894 unmodified lines9495969798991001011021031041051061071081091101111121131149 unmodified lines12412512612712812913013113213313413511 unmodified lines1471481491501511521531541551561571581591601611624 unmodified lines16716816917017117217317417517617717817918018118218318418524 unmodified lines2102112122132142152162172182192203 unmodified lines2242252262272282292302312322332342351 unmodified line23723823924024124221 unmodified lines2642652662672682692702712721 unmodified line2742752762772782792802812822832842852865 unmodified lines2922932942952962972982993002 unmodified lines30330430530630730830931031131231331428 unmodified lines34334434534634734834926 unmodified lines37637737837938038138229 unmodified lines4124134144154164174187 unmodified lines42642742842943043143217 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv14 unmodified lines# GET /agentcache/mcp/tools# ---------------------------------------------------------------------------@mcp_bp.route("/agentcache/mcp/tools", methods=["GET"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["GET"])def mcp_tools_list():auth_err = _check_auth()if auth_err:return auth_errtools = [{"name": "cache_recall","description": "Search past folder observations and global memories. Use when you need to recall what happened in a folder.",1 unmodified line"type": "object","properties": {"query": {"type": "string", "description": "Search query keywords"},"limit": {"type": "number", "description": "Max results to return (default 10)"},"folderPath": {"type": "string", "description": "Filter to a specific folder path (optional)"},"agentId": {"type": "string", "description": "Filter to a specific agent ID (optional)"},},"required": ["query"],},5 unmodified lines"type": "object","properties": {"query": {"type": "string", "description": "Search query"},"limit": {"type": "number", "description": "Max results (default 10)"},"folderPath": {"type": "string", "description": "Filter to a specific folder path (optional)"},"agentId": {"type": "string", "description": "Filter to a specific agent ID (optional)"},},"required": ["query"],},4 unmodified lines"inputSchema": {"type": "object","properties": {"content": {"type": "string", "description": "The insight or decision to remember"},"type": {"type": "string", "description": "Memory type: pattern, preference, architecture, bug, workflow, or fact"},"concepts": {"oneOf": [{"type": "string", "description": "Comma-separated key concepts"},{"type": "array", "items": {"type": "string"}, "description": "List of key concepts"},]},"files": {"oneOf": [{"type": "string", "description": "Comma-separated relevant file paths"},{"type": "array", "items": {"type": "string"}, "description": "List of relevant file paths"},]},"project": {"type": "string", "description": "Canonical project identifier"},},"required": ["content"],},9 unmodified lines"inputSchema": {"type": "object","properties": {"memoryId": {"type": "string", "description": "Memory ID to delete"},"folderPath": {"type": "string", "description": "Folder path to delete observations from"},"agentId": {"type": "string", "description": "Agent ID to delete observations for"},"observationIds": {"oneOf": [{"type": "string", "description": "Comma-separated observation IDs to delete"},{"type": "array", "items": {"type": "string"}},]},11 unmodified lines"inputSchema": {"type": "object","properties": {"folderPath": {"type": "string", "description": "Absolute path of the working directory"},"agentId": {"type": "string", "description": "Identity of the agent (e.g. 'kiro', 'claude')"},"text": {"type": "string", "description": "Observation content"},"timestamp": {"type": "string", "description": "ISO 8601 UTC timestamp (defaults to now)"},"type": {"type": "string", "description": "Observation type"},"title": {"type": "string", "description": "Short title"},"concepts": {"type": "array", "items": {"type": "string"}},"files": {"type": "array", "items": {"type": "string"}},"importance": {"type": "integer", "description": "1-10"},"sessionId": {"type": "string", "description": "Deprecated — ignored"},},"required": ["folderPath", "agentId", "text"],},4 unmodified lines"inputSchema": {"type": "object","properties": {"agentId": {"type": "string", "description": "ID/Name of the agent (optional)"},"content": {"type": "string", "description": "The memory content/insight"},"project": {"type": "string", "description": "Canonical project path/identifier"},"type": {"type": "string", "description": "Memory type: fact, preference, bug, workflow, architecture"},"concepts": {"oneOf": [{"type": "string", "description": "Comma-separated key concepts"},{"type": "array", "items": {"type": "string"}},]},"files": {"oneOf": [{"type": "string", "description": "Comma-separated relevant file paths"},{"type": "array", "items": {"type": "string"}},]},24 unmodified lines"inputSchema": {"type": "object","properties": {"folderPath": {"type": "string", "description": "Filter by folder path (optional)"},"agentId": {"type": "string", "description": "Filter by agent ID (optional)"},"limit": {"type": "integer", "description": "Max results (default 100)"},"before": {"type": "string", "description": "ISO timestamp upper bound (optional)"},"after": {"type": "string", "description": "ISO timestamp lower bound (optional)"},},},},3 unmodified lines"inputSchema": {"type": "object","properties": {"folderPath": {"type": "string", "description": "Folder path to deduplicate (optional — omit for all pairs)"},"agentId": {"type": "string", "description": "Agent ID to deduplicate (optional — omit for all pairs)"},},},},]return jsonify({"tools": tools}), 2001 unmodified line# POST /agentcache/mcp/tools# ---------------------------------------------------------------------------@mcp_bp.route("/agentcache/mcp/tools", methods=["POST"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["POST"])def mcp_tools_call():21 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidres = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name in ("cache_save", "memory_save"):1 unmodified lineconcepts = _parse_mcp_list_arg(args.get("concepts"))files = _parse_mcp_list_arg(args.get("files"))project = args.get("project")res = functions.remember(kv, {"content": content,"type": args.get("type") or "fact","concepts": concepts,"files": files,"project": project,})text_out = json.dumps(res)elif name in ("cache_smart_search", "memory_smart_search"):5 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidres = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name in ("cache_diagnose", "memory_diagnose"):2 unmodified lineselif name in ("cache_forget", "memory_forget"):obs_ids = _parse_mcp_list_arg(args.get("observationIds"))res = functions.forget(kv, {"memoryId": args.get("memoryId"),"folderPath": args.get("folderPath"),"agentId": args.get("agentId"),"observationIds": obs_ids,})text_out = json.dumps(res, indent=2)elif name in ("cache_export", "memory_export"):28 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidif not text:26 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidif not content:29 unmodified linesif functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid and aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403obs = sorted(kv.list(KV.folder_obs(fp, aid)),key=lambda x: x.get("timestamp", ""),7 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidres = functions.folder_timeline(kv,17 unmodified lines181920212223248 unmodified lines3334353637383914 unmodified lines5455565758596061621 unmodified line6465666768697071727374757677787980815 unmodified lines878889909192939495969798991001011021031044 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511529 unmodified lines16216316416516616716816917017117217317417517617717817918018118218318418511 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232244 unmodified lines22923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426524 unmodified lines2902912922932942952962972982993003013023033043053063073083093103113123133143153 unmodified lines3193203213223233243253263273283293303313323333343353363373383393403413423433443453461 unmodified line34834935035135235335421 unmodified lines3763773783793803813823833843853863873881 unmodified line3903913923933943953963973983994004014024034044055 unmodified lines4114124134144154164174184194204214224232 unmodified lines42642742842943043143243343443543643743843944028 unmodified lines46947047147247347447547647726 unmodified lines50450550650750850951051151229 unmodified lines5425435445455465475485495507 unmodified lines55855956056156256356456556617 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv14 unmodified lines# GET /agentcache/mcp/tools# ---------------------------------------------------------------------------def get_mcp_tools_schemas():return [{"name": "cache_recall","description": "Search past folder observations and global memories. Use when you need to recall what happened in a folder.",1 unmodified line"type": "object","properties": {"query": {"type": "string", "description": "Search query keywords"},"limit": {"type": "number","description": "Max results to return (default 10)",},"folderPath": {"type": "string","description": "Filter to a specific folder path (optional)",},"agentId": {"type": "string","description": "Filter to a specific agent ID (optional)",},},"required": ["query"],},5 unmodified lines"type": "object","properties": {"query": {"type": "string", "description": "Search query"},"limit": {"type": "number","description": "Max results (default 10)",},"folderPath": {"type": "string","description": "Filter to a specific folder path (optional)",},"agentId": {"type": "string","description": "Filter to a specific agent ID (optional)",},},"required": ["query"],},4 unmodified lines"inputSchema": {"type": "object","properties": {"content": {"type": "string","description": "The insight or decision to remember",},"type": {"type": "string","description": "Memory type: pattern, preference, architecture, bug, workflow, or fact",},"concepts": {"oneOf": [{"type": "string","description": "Comma-separated key concepts",},{"type": "array","items": {"type": "string"},"description": "List of key concepts",},]},"files": {"oneOf": [{"type": "string","description": "Comma-separated relevant file paths",},{"type": "array","items": {"type": "string"},"description": "List of relevant file paths",},]},"project": {"type": "string","description": "Canonical project identifier",},},"required": ["content"],},9 unmodified lines"inputSchema": {"type": "object","properties": {"memoryId": {"type": "string","description": "Memory ID to delete",},"folderPath": {"type": "string","description": "Folder path to delete observations from",},"agentId": {"type": "string","description": "Agent ID to delete observations for",},"observationIds": {"oneOf": [{"type": "string","description": "Comma-separated observation IDs to delete",},{"type": "array", "items": {"type": "string"}},]},11 unmodified lines"inputSchema": {"type": "object","properties": {"folderPath": {"type": "string","description": "Absolute path of the working directory",},"agentId": {"type": "string","description": "Identity of the agent (e.g. 'kiro', 'claude')",},"text": {"type": "string", "description": "Observation content"},"timestamp": {"type": "string","description": "ISO 8601 UTC timestamp (defaults to now)",},"type": {"type": "string", "description": "Observation type"},"title": {"type": "string", "description": "Short title"},"concepts": {"type": "array", "items": {"type": "string"}},"files": {"type": "array", "items": {"type": "string"}},"importance": {"type": "integer", "description": "1-10"},"sessionId": {"type": "string","description": "Deprecated — ignored",},},"required": ["folderPath", "agentId", "text"],},4 unmodified lines"inputSchema": {"type": "object","properties": {"agentId": {"type": "string","description": "ID/Name of the agent (optional)",},"content": {"type": "string","description": "The memory content/insight",},"project": {"type": "string","description": "Canonical project path/identifier",},"type": {"type": "string","description": "Memory type: fact, preference, bug, workflow, architecture",},"concepts": {"oneOf": [{"type": "string","description": "Comma-separated key concepts",},{"type": "array", "items": {"type": "string"}},]},"files": {"oneOf": [{"type": "string","description": "Comma-separated relevant file paths",},{"type": "array", "items": {"type": "string"}},]},24 unmodified lines"inputSchema": {"type": "object","properties": {"folderPath": {"type": "string","description": "Filter by folder path (optional)",},"agentId": {"type": "string","description": "Filter by agent ID (optional)",},"limit": {"type": "integer","description": "Max results (default 100)",},"before": {"type": "string","description": "ISO timestamp upper bound (optional)",},"after": {"type": "string","description": "ISO timestamp lower bound (optional)",},},},},3 unmodified lines"inputSchema": {"type": "object","properties": {"folderPath": {"type": "string","description": "Folder path to deduplicate (optional — omit for all pairs)",},"agentId": {"type": "string","description": "Agent ID to deduplicate (optional — omit for all pairs)",},},},},]@mcp_bp.route("/agentcache/mcp/tools", methods=["GET"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["GET"])def mcp_tools_list():auth_err = _check_auth()if auth_err:return auth_errtools = get_mcp_tools_schemas()return jsonify({"tools": tools}), 2001 unmodified line# POST /agentcache/mcp/tools# ---------------------------------------------------------------------------@mcp_bp.route("/agentcache/mcp/tools", methods=["POST"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["POST"])def mcp_tools_call():21 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidres = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name in ("cache_save", "memory_save"):1 unmodified lineconcepts = _parse_mcp_list_arg(args.get("concepts"))files = _parse_mcp_list_arg(args.get("files"))project = args.get("project")res = functions.remember(kv,{"content": content,"type": args.get("type") or "fact","concepts": concepts,"files": files,"project": project,},)text_out = json.dumps(res)elif name in ("cache_smart_search", "memory_smart_search"):5 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidres = functions.folder_search(kv, q, limit, folder_path=folder_path, agent_id=agent_id)text_out = json.dumps(res, indent=2)elif name in ("cache_diagnose", "memory_diagnose"):2 unmodified lineselif name in ("cache_forget", "memory_forget"):obs_ids = _parse_mcp_list_arg(args.get("observationIds"))res = functions.forget(kv,{"memoryId": args.get("memoryId"),"folderPath": args.get("folderPath"),"agentId": args.get("agentId"),"observationIds": obs_ids,},)text_out = json.dumps(res, indent=2)elif name in ("cache_export", "memory_export"):28 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidif not text:26 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if agent_id and agent_id != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidif not content:29 unmodified linesif functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid and aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403obs = sorted(kv.list(KV.folder_obs(fp, aid)),key=lambda x: x.get("timestamp", ""),7 unmodified linescurrent_aid = functions.get_agent_id()if current_aid:if request_aid and request_aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidres = functions.folder_timeline(kv,
17 unmodified lines1819202122238 unmodified lines3233343536371 unmodified line39404142434413 unmodified lines58596061626339 unmodified lines10310410510610710814 unmodified lines12312412512612712817 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# POST /agentmemory/remember# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/remember", methods=["POST"])@memories_bp.route("/agentmemory/remember", methods=["POST"])def api_remember():13 unmodified lines# POST /agentmemory/agent/remember# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/agent/remember", methods=["POST"])@memories_bp.route("/agentmemory/agent/remember", methods=["POST"])def api_agent_remember():39 unmodified lines# GET /agentmemory/memories# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/memories", methods=["GET"])@memories_bp.route("/agentmemory/memories", methods=["GET"])def api_memories_list():14 unmodified lines# POST /agentmemory/forget# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/forget", methods=["POST"])@memories_bp.route("/agentmemory/forget", methods=["POST"])def api_forget():17 unmodified lines181920212223248 unmodified lines333435363738391 unmodified line4142434445464713 unmodified lines6162636465666739 unmodified lines10710810911011111211314 unmodified lines12812913013113213313417 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# POST /agentmemory/remember# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/remember", methods=["POST"])@memories_bp.route("/agentmemory/remember", methods=["POST"])def api_remember():13 unmodified lines# POST /agentmemory/agent/remember# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/agent/remember", methods=["POST"])@memories_bp.route("/agentmemory/agent/remember", methods=["POST"])def api_agent_remember():39 unmodified lines# GET /agentmemory/memories# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/memories", methods=["GET"])@memories_bp.route("/agentmemory/memories", methods=["GET"])def api_memories_list():14 unmodified lines# POST /agentmemory/forget# ---------------------------------------------------------------------------@memories_bp.route("/agentcache/forget", methods=["POST"])@memories_bp.route("/agentmemory/forget", methods=["POST"])def api_forget():
13 unmodified lines1415161718198 unmodified lines2829303132331 unmodified line35363738394013 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# POST /agentcache/migrate# ---------------------------------------------------------------------------@migration_bp.route("/agentcache/migrate", methods=["POST"])@migration_bp.route("/agentmemory/migrate", methods=["POST"])def api_migrate():13 unmodified lines141516171819208 unmodified lines293031323334351 unmodified line3738394041424313 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# POST /agentcache/migrate# ---------------------------------------------------------------------------@migration_bp.route("/agentcache/migrate", methods=["POST"])@migration_bp.route("/agentmemory/migrate", methods=["POST"])def api_migrate():
23 unmodified lines2425262728299 unmodified lines3940414243441 unmodified line4647484950514 unmodified lines565758596061626364656667686970717273747576777879808182838485868788899091929394959610 unmodified lines10710810911011111211311411511611711811912012129 unmodified lines1511521531541551561571581591601612 unmodified lines16416516616716816916 unmodified lines1861871881891901917 unmodified lines1992002012022032042052062072082092102112122132142152162175 unmodified lines22322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325423 unmodified lines27827928028128228316 unmodified lines30030130230323 unmodified linesdef _check_auth():"""Replicate the check_auth() pattern from app.py."""import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None9 unmodified linesdef _get_kv():"""Retrieve the shared kv instance from the app module."""import app as app_modulereturn app_module.kv1 unmodified line# POST /agentmemory/observe (legacy raw hook endpoint + auto-compat shim)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/observe", methods=["POST"])@observations_bp.route("/agentmemory/observe", methods=["POST"])def api_observe():4 unmodified linesbody = {}try:body = request.get_json(force=True) or {}# Compat shim: accept both folder-based and legacy session-based payloads.# Old clients send sessionId/project/cwd + data{tool_input/output}# New clients send folderPath/agentId/textfolder_path = (body.get("folderPath")or body.get("cwd")or body.get("project")or os.getenv("AGENTCACHE_CWD")or os.getenv("AGENTMEMORY_CWD")or "/unknown")agent_id = (body.get("agentId")or body.get("sessionId")or functions.get_agent_id()or os.getenv("AGENT_ID")or "agent")# Build text from whichever field the client usedtext = body.get("text") or body.get("content") or ""if not text:# Legacy clients put content in a nested 'data' dictdata = body.get("data")if isinstance(data, dict):parts = [str(v) for k, v in data.items()if v and k in ("tool_input", "tool_output", "prompt","response", "tool_name", "content")]text = " | ".join(parts) if parts else str(data)elif isinstance(data, str):text = dataif not text:# Last resort: use hookType as a minimal marker so we don't 400text = body.get("hookType") or "observation"payload = {"folderPath": folder_path,10 unmodified linesreturn jsonify(res), 201except Exception as e:import tracebacktb = traceback.format_exc()print(f"[observe] 400 — keys={list(body.keys())} {type(e).__name__}: {e}\n{tb}")return jsonify({"error": str(e), "detail": type(e).__name__, "keys": list(body.keys()), "tb": tb}), 400# ---------------------------------------------------------------------------# POST /agentmemory/agent/observe# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/agent/observe", methods=["POST"])@observations_bp.route("/agentmemory/agent/observe", methods=["POST"])def api_agent_observe():29 unmodified linesreturn jsonify(res), 201except ValueError as e:import tracebackprint(f"[agent_observe] 400 ValueError — body keys: {list(body.keys())} — {e}")return jsonify({"error": str(e)}), 400except Exception as e:import tracebackprint(f"[agent_observe] 400 error — body keys: {list(body.keys())} — {type(e).__name__}: {e}")print(traceback.format_exc())return jsonify({"error": str(e), "detail": type(e).__name__}), 4002 unmodified lines# GET /agentmemory/folders# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/folders", methods=["GET"])@observations_bp.route("/agentmemory/folders", methods=["GET"])def api_folders():16 unmodified lines# GET /agentmemory/folder/observations# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/folder/observations", methods=["GET"])@observations_bp.route("/agentmemory/folder/observations", methods=["GET"])def api_folder_observations():7 unmodified linesif functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid and aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated to another agent"}), 403observations = sorted(_get_kv().list(KV.folder_obs(fp, aid)),key=lambda x: x.get("timestamp", ""),reverse=True,)return jsonify({"observations": observations, "folderPath": fp, "agentId": aid}), 200# ---------------------------------------------------------------------------# POST /agentmemory/session/start (legacy compat shim → 200 no-op)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/session/start", methods=["POST"])@observations_bp.route("/agentmemory/session/start", methods=["POST"])def api_session_start():5 unmodified linesreturn auth_errimport uuidbody = request.get_json(force=True) or {}session_id = body.get("sessionId") or f"compat_{uuid.uuid4().hex[:16]}"return jsonify({"sessionId": session_id,"status": "active","message": "Session model migrated to folder-based. Use /agentmemory/agent/observe.",}), 200# ---------------------------------------------------------------------------# POST /agentmemory/session/end (legacy compat shim → 200 no-op)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/session/end", methods=["POST"])@observations_bp.route("/agentmemory/session/end", methods=["POST"])def api_session_end():auth_err = _check_auth()if auth_err:return auth_errreturn jsonify({"success": True, "message": "Session model is now folder-based."}), 200# ---------------------------------------------------------------------------# GET /agentmemory/observations (legacy compat shim)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/folder/dedup", methods=["POST"])@observations_bp.route("/agentmemory/folder/dedup", methods=["POST"])def api_folder_dedup():23 unmodified lines# GET /agentmemory/observations (legacy compat shim)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/observations", methods=["GET"])@observations_bp.route("/agentmemory/observations", methods=["GET"])def api_observations_legacy():16 unmodified lines)return jsonify({"observations": obs, "sessionId": session_id}), 200except Exception as e:return jsonify({"observations": [], "sessionId": session_id, "error": str(e)}), 20023 unmodified lines242526272829309 unmodified lines404142434445461 unmodified line484950515253544 unmodified lines59606162636465666768697010 unmodified lines8182838485868788899091929394959697989910010110210310429 unmodified lines1341351361371381391401411421431441451461471482 unmodified lines15115215315415515615716 unmodified lines1741751761771781791807 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102115 unmodified lines21721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425523 unmodified lines27928028128228328428516 unmodified lines30230330430530630723 unmodified linesdef _check_auth():"""Replicate the check_auth() pattern from app.py."""import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None9 unmodified linesdef _get_kv():"""Retrieve the shared kv instance from the app module."""import app as app_modulereturn app_module.kv1 unmodified line# POST /agentmemory/observe (legacy raw hook endpoint + auto-compat shim)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/observe", methods=["POST"])@observations_bp.route("/agentmemory/observe", methods=["POST"])def api_observe():4 unmodified linesbody = {}try:body = request.get_json(force=True) or {}folder_path = body.get("folderPath")agent_id = body.get("agentId")text = body.get("text") or body.get("content") or ""if not folder_path or not agent_id or not text:return jsonify({"error": "folderPath, agentId, and text are required"}), 400payload = {"folderPath": folder_path,10 unmodified linesreturn jsonify(res), 201except Exception as e:import tracebacktb = traceback.format_exc()print(f"[observe] 400 — keys={list(body.keys())} {type(e).__name__}: {e}\n{tb}")return jsonify({"error": str(e),"detail": type(e).__name__,"keys": list(body.keys()),"tb": tb,}), 400# ---------------------------------------------------------------------------# POST /agentmemory/agent/observe# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/agent/observe", methods=["POST"])@observations_bp.route("/agentmemory/agent/observe", methods=["POST"])def api_agent_observe():29 unmodified linesreturn jsonify(res), 201except ValueError as e:import tracebackprint(f"[agent_observe] 400 ValueError — body keys: {list(body.keys())} — {e}")return jsonify({"error": str(e)}), 400except Exception as e:import tracebackprint(f"[agent_observe] 400 error — body keys: {list(body.keys())} — {type(e).__name__}: {e}")print(traceback.format_exc())return jsonify({"error": str(e), "detail": type(e).__name__}), 4002 unmodified lines# GET /agentmemory/folders# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/folders", methods=["GET"])@observations_bp.route("/agentmemory/folders", methods=["GET"])def api_folders():16 unmodified lines# GET /agentmemory/folder/observations# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/folder/observations", methods=["GET"])@observations_bp.route("/agentmemory/folder/observations", methods=["GET"])def api_folder_observations():7 unmodified linesif functions.is_agent_scope_isolated():current_aid = functions.get_agent_id()if current_aid and aid != current_aid:return jsonify({"error": "Unauthorized: Agent scope is isolated to another agent"}), 403observations = sorted(_get_kv().list(KV.folder_obs(fp, aid)),key=lambda x: x.get("timestamp", ""),reverse=True,)return jsonify({"observations": observations, "folderPath": fp, "agentId": aid}), 200# ---------------------------------------------------------------------------# POST /agentmemory/session/start (legacy compat shim → 200 no-op)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/session/start", methods=["POST"])@observations_bp.route("/agentmemory/session/start", methods=["POST"])def api_session_start():5 unmodified linesreturn auth_errimport uuidbody = request.get_json(force=True) or {}session_id = body.get("sessionId") or f"compat_{uuid.uuid4().hex[:16]}"return jsonify({"sessionId": session_id,"status": "active","message": "Session model migrated to folder-based. Use /agentmemory/agent/observe.",}), 200# ---------------------------------------------------------------------------# POST /agentmemory/session/end (legacy compat shim → 200 no-op)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/session/end", methods=["POST"])@observations_bp.route("/agentmemory/session/end", methods=["POST"])def api_session_end():auth_err = _check_auth()if auth_err:return auth_errreturn jsonify({"success": True, "message": "Session model is now folder-based."}), 200# ---------------------------------------------------------------------------# GET /agentmemory/observations (legacy compat shim)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/folder/dedup", methods=["POST"])@observations_bp.route("/agentmemory/folder/dedup", methods=["POST"])def api_folder_dedup():23 unmodified lines# GET /agentmemory/observations (legacy compat shim)# ---------------------------------------------------------------------------@observations_bp.route("/agentcache/observations", methods=["GET"])@observations_bp.route("/agentmemory/observations", methods=["GET"])def api_observations_legacy():16 unmodified lines)return jsonify({"observations": obs, "sessionId": session_id}), 200except Exception as e:return jsonify({"observations": [], "sessionId": session_id, "error": str(e)}), 200
14 unmodified lines1516171819208 unmodified lines2930313233341 unmodified line36373839404110 unmodified lines525354555657583 unmodified lines6263646566678 unmodified lines7677787980818214 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# POST /agentcache/search# ---------------------------------------------------------------------------@search_bp.route("/agentcache/search", methods=["POST"])@search_bp.route("/agentmemory/search", methods=["POST"])def api_search():10 unmodified linesfolder_path = body.get("folderPath")agent_id = body.get("agentId")res = functions.folder_search(_get_kv(), query, limit, folder_path=folder_path, agent_id=agent_id)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 4003 unmodified lines# POST /agentcache/timeline# ---------------------------------------------------------------------------@search_bp.route("/agentcache/timeline", methods=["POST"])@search_bp.route("/agentmemory/timeline", methods=["POST"])def api_timeline():8 unmodified lineslimit = body.get("limit") or 100before = body.get("before")after = body.get("after")result = functions.folder_timeline(_get_kv(), limit, folder_path, agent_id, before, after)return jsonify({"observations": result}), 200except Exception as e:return jsonify({"error": str(e)}), 40014 unmodified lines151617181920218 unmodified lines303132333435361 unmodified line3839404142434410 unmodified lines5556575859606162633 unmodified lines676869707172738 unmodified lines82838485868788899014 unmodified linesdef _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return None8 unmodified linesdef _get_kv():import app as app_modulereturn app_module.kv1 unmodified line# POST /agentcache/search# ---------------------------------------------------------------------------@search_bp.route("/agentcache/search", methods=["POST"])@search_bp.route("/agentmemory/search", methods=["POST"])def api_search():10 unmodified linesfolder_path = body.get("folderPath")agent_id = body.get("agentId")res = functions.folder_search(_get_kv(), query, limit, folder_path=folder_path, agent_id=agent_id)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 4003 unmodified lines# POST /agentcache/timeline# ---------------------------------------------------------------------------@search_bp.route("/agentcache/timeline", methods=["POST"])@search_bp.route("/agentmemory/timeline", methods=["POST"])def api_timeline():8 unmodified lineslimit = body.get("limit") or 100before = body.get("before")after = body.get("after")result = functions.folder_timeline(_get_kv(), limit, folder_path, agent_id, before, after)return jsonify({"observations": result}), 200except Exception as e:return jsonify({"error": str(e)}), 400
11 unmodified lines121314151617181920212223242526272829303132337 unmodified lines41424344454647484950515253545536 unmodified lines929394959697981 unmodified line10010110210310410510610710810911011111211311411511611711811912 unmodified lines13213313413513613753 unmodified lines1911921931941951961971981992002012022032042052062072082092102112121 unmodified line21421521621721821922022122222322422522622734 unmodified lines26226326426526626726826927027110 unmodified lines28228328428528628728868 unmodified lines3573583593603613623636 unmodified lines3703713723733743753769 unmodified lines38638738838939039139239339439539639739839940040140240340440540640740840941013 unmodified lines4244254264274284294306 unmodified lines43743843944044144244316 unmodified lines46046146246346446546622 unmodified lines4894904914924934944954964974984995005015025035045055065077 unmodified lines51551651751851952012 unmodified lines5335345355365375385395405415425435441 unmodified line5465475485495505515529 unmodified lines56256356456556656756856957057157257357413 unmodified lines5885895905915925935945955965975985996006016029 unmodified lines6126136146156166176186196206214 unmodified lines6266276286296306316326336346356366376386396406416426436446456466476486496506516523 unmodified lines6566576586596606616626636646653 unmodified lines66967067167267367467513 unmodified lines68969069169269369469526 unmodified lines7227237247257267277287297307311 unmodified line7337347357367377387397407417427437447457467477487493 unmodified lines75375475575675775831 unmodified lines79079179279379479579612 unmodified lines8098108118128138148 unmodified lines8238248258268278288298308314 unmodified lines83683783883984011 unmodified lines# =====================================================================step2map = {"ational": "ate", "tional": "tion", "enci": "ence", "anci": "ance","izer": "ize", "iser": "ise", "abli": "able", "alli": "al","entli": "ent", "eli": "e", "ousli": "ous", "ization": "ize","isation": "ise", "ation": "ate", "ator": "ate", "alism": "al","iveness": "ive", "fulness": "ful", "ousness": "ous", "aliti": "al","iviti": "ive", "biliti": "ble",}step3map = {"icate": "ic", "ative": "", "alize": "al", "alise": "al","iciti": "ic", "ical": "ic", "ful": "", "ness": "",}def _has_vowel(s: str) -> bool:return any(c in "aeiou" for c in s)def _measure(s: str) -> int:# Reduce non-vowels (excluding y) to C, vowels (+y) to Vreduced = ""7 unmodified lines# count "VC" patternsreturn len(re.findall(r"VC", reduced))def _ends_double_consonant(s: str) -> bool:return len(s) >= 2 and s[-1] == s[-2] and s[-1] not in "aeiou"def _ends_cvc(s: str) -> bool:if len(s) < 3:return Falsec1, v, c2 = s[-3], s[-2], s[-1]return c1 not in "aeiou" and v in "aeiou" and c2 not in "aeiouwxy"def stem(word: str) -> str:if len(word) <= 2:return word36 unmodified lines# Step 2for suffix, replacement in step2map.items():if w.endswith(suffix):base = w[:-len(suffix)]if _measure(base) > 0:w = base + replacementbreak1 unmodified line# Step 3for suffix, replacement in step3map.items():if w.endswith(suffix):base = w[:-len(suffix)]if _measure(base) > 0:w = base + replacementbreak# Step 4suffixes_step4 = ("al", "ance", "ence", "er", "ic", "able", "ible", "ant", "ement","ment", "ent", "tion", "sion", "ou", "ism", "ate", "iti", "ous","ive", "ize", "ise")if w.endswith(suffixes_step4):# find matching suffix lengthmatch = re.search(r"(ement|ment|tion|sion|ance|ence|able|ible|ism|ate|iti|ous|ive|ize|ise|ant|ent|al|er|ic|ou)$", w)if match:suffix_len = len(match.group(1))base = w[:-suffix_len]12 unmodified linesreturn w# =====================================================================# Synonym Map (Ported from synonyms.ts)# =====================================================================53 unmodified linesif other != s:synonymMap[s].add(other)def get_synonyms(stemmed_term: str) -> List[str]:return list(synonymMap.get(stemmed_term, []))# =====================================================================# CJK Segmenter (Ported from cjk-segmenter.ts)# =====================================================================CJK_RE = re.compile(r'[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\uac00-\ud7a3]')CJK_RUN_RE = re.compile(r'[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\uac00-\ud7a3]+')HANGUL_RE = re.compile(r'[\uac00-\ud7a3]')KANA_RE = re.compile(r'[\u3040-\u309f\u30a0-\u30ff]')HANGUL_BLOCK_RE = re.compile(r'[가-]+')jieba_loaded = Falsejieba_instance = Nonedef get_jieba():global jieba_loaded, jieba_instanceif jieba_loaded:1 unmodified linejieba_loaded = Truetry:import jiebajieba_instance = jiebaexcept ImportError:print("[search] Install jieba to improve Chinese word segmentation (pip install jieba)")return jieba_instancedef has_cjk(text: str) -> bool:return bool(CJK_RE.search(text))def segment_cjk(text: str) -> List[str]:if not has_cjk(text):return [text]34 unmodified linesreturn out# =====================================================================# SearchIndex (BM25 - Ported from search-index.ts)# =====================================================================class SearchIndex:def __init__(self):self.entries: Dict[str, Dict[str, Any]] = {}10 unmodified linesobs_id = obs.get("id")if not obs_id:returnterms = self.extract_terms(obs)term_freq: Dict[str, int] = {}term_count = 068 unmodified linesfor q_item in query_terms:term = q_item["term"]weight = q_item["weight"]matching_docs = self.inverted_index.get(term)if matching_docs:df = len(matching_docs)6 unmodified linesdoc_len = entry["termCount"]numerator = tf * (self.k1 + 1)denominator = tf + self.k1 * (1 - self.b + self.b * (doc_len / avg_doc_len))bm25_score = idf * (numerator / denominator) * weightscores[obs_id] = scores.get(obs_id, 0.0) + bm25_score9 unmodified linesobs_ids = self.inverted_index.get(index_term, set())prefix_df = len(obs_ids)prefix_idf = math.log((N - prefix_df + 0.5) / (prefix_df + 0.5) + 1) * 0.5for obs_id in obs_ids:entry = self.entries[obs_id]doc_terms = self.doc_term_counts.get(obs_id, {})tf = doc_terms.get(index_term, 0)doc_len = entry["termCount"]numerator = tf * (self.k1 + 1)denominator = tf + self.k1 * (1 - self.b + self.b * (doc_len / avg_doc_len))scores[obs_id] = scores.get(obs_id, 0.0) + prefix_idf * (numerator / denominator) * weightresults = []for obs_id, score in scores.items():entry = self.entries[obs_id]results.append({"obsId": obs_id,"sessionId": entry["sessionId"],"score": score})results.sort(key=lambda x: x["score"], reverse=True)return results[:limit]13 unmodified linesself.clear()if not data:returnfor k, v in data.get("entries", []):self.entries[k] = vfor term, ids in data.get("inverted", []):6 unmodified linesdef serialize_data(self) -> Dict[str, Any]:entries = list(self.entries.items())inverted = [(term, list(ids)) for term, ids in self.inverted_index.items()]doc_terms = [(id_, list(counts.items())) for id_, counts in self.doc_term_counts.items()]return {"v": 2,"entries": entries,16 unmodified linesdef tokenize(self, text: str) -> List[str]:# Strip special characters except valid separatorscleaned = re.sub(r'[^\w\s/.\\-_]', ' ', text)out = []for raw in cleaned.split():if len(raw) < 2:22 unmodified lineshi = midreturn lo# =====================================================================# VectorIndex (Cosine Similarity - Ported from vector-index.ts)# =====================================================================def float32_to_base64(floats: List[float]) -> str:arr = array.array('f', floats)return base64.b64encode(arr.tobytes()).decode('utf-8')def base64_to_float32(b64: str) -> List[float]:arr = array.array('f')arr.frombytes(base64.b64decode(b64))return list(arr)def cosine_similarity(a: List[float], b: List[float]) -> float:if len(a) != len(b) or len(a) == 0:return 0.07 unmodified linesdenom = math.sqrt(norm_a) * math.sqrt(norm_b)return dot / denom if denom != 0.0 else 0.0class VectorIndex:def __init__(self):self.vectors: Dict[str, Dict[str, Any]] = {}12 unmodified linesresults = []for obs_id, entry in self.vectors.items():score = cosine_similarity(query, entry["embedding"])results.append({"obsId": obs_id,"sessionId": entry["sessionId"],"score": score})results.sort(key=lambda x: x["score"], reverse=True)return results[:limit]1 unmodified linedef size(self) -> int:return len(self.vectors)def validate_dimensions(self, expected: int) -> Tuple[List[Dict[str, Any]], Set[int]]:mismatches = []seen_dimensions = set()for obs_id, entry in self.vectors.items():9 unmodified linesdef serialize_data(self) -> List[Any]:data = []for obs_id, entry in self.vectors.items():data.append([obs_id,{"embedding": float32_to_base64(entry["embedding"]),"sessionId": entry["sessionId"]}])return datadef restore_from_data(self, data: List[Any]) -> None:13 unmodified linescontinueself.vectors[obs_id] = {"embedding": base64_to_float32(emb_b64),"sessionId": sess_id}except Exception:continue# =====================================================================# Gemini Embedding Client (Urllib POST completion)# =====================================================================class GeminiEmbeddingProvider:def __init__(self, api_key: str):self.name = "gemini"9 unmodified linesdef embed_batch(self, texts: List[str]) -> List[List[float]]:results: List[List[float]] = []batch_limit = 100for i in range(0, len(texts), batch_limit):chunk = texts[i:i + batch_limit]payload = {"requests": [{4 unmodified linesfor t in chunk]}req_data = json.dumps(payload).encode("utf-8")url = f"{self.api_url}?key={self.api_key}"req = urllib.request.Request(url,data=req_data,headers={"Content-Type": "application/json"},method="POST")try:with urllib.request.urlopen(req, timeout=30.0) as response:resp_data = json.loads(response.read().decode("utf-8"))for emb in resp_data.get("embeddings", []):values = emb.get("values", [])results.append(self._l2_normalize(values))except Exception as e:raise RuntimeError(f"Gemini embedding batch call failed: {e}")return resultsdef _l2_normalize(self, vec: List[float]) -> List[float]:3 unmodified linesreturn vecreturn [x / norm for x in vec]# =====================================================================# HybridSearch (Triple Stream - Ported from hybrid-search.ts)# =====================================================================class HybridSearch:def __init__(self,3 unmodified lineskv: Any,bm25_weight: float = 0.4,vector_weight: float = 0.6,graph_weight: float = 0.3):self.bm25 = bm25self.vector = vector13 unmodified linesquery_embedding = self.embedding_provider.embed(query)vector_results = self.vector.search(query_embedding, limit * 2)except Exception:pass # Fallback to BM25# Build scores mappingscores: Dict[str, Dict[str, Any]] = {}26 unmodified lines}has_vector = len(vector_results) > 0effective_bm25_w = self.bm25_weighteffective_vector_w = self.vector_weight if has_vector else 0.0total_w = effective_bm25_w + effective_vector_wif total_w > 0:effective_bm25_w /= total_w1 unmodified linecombined = []for obs_id, s in scores.items():combined.append({"obsId": obs_id,"sessionId": s["sessionId"],"bm25Score": s["bm25Score"],"vectorScore": s["vectorScore"],"graphScore": s["graphScore"],"combinedScore": (effective_bm25_w * (1.0 / (RRF_K + s["bm25Rank"])) +effective_vector_w * (1.0 / (RRF_K + s["vectorRank"])))})combined.sort(key=lambda x: x["combinedScore"], reverse=True)return combined[:limit]3 unmodified lines# OpenAI Embedding Client (D5.1)# =====================================================================class OpenAIEmbeddingProvider:"""OpenAI text-embedding-3-small provider (1536 dims).31 unmodified lineswith urllib.request.urlopen(req, timeout=30.0) as response:resp_data = json.loads(response.read().decode("utf-8"))# Sort by index to preserve orderembeddings_sorted = sorted(resp_data.get("data", []), key=lambda e: e["index"])for emb in embeddings_sorted:results.append(self._l2_normalize(emb["embedding"]))except Exception as e:12 unmodified lines# SentenceTransformer Local Provider (D5.2)# =====================================================================class SentenceTransformerProvider:"""Local sentence-transformers provider (optional install).8 unmodified linesself.name = "sentence-transformers"try:from sentence_transformers import SentenceTransformer # type: ignoreself._model = SentenceTransformer(model_name)self.dimensions = self._model.get_sentence_embedding_dimension()print(f"[search] SentenceTransformerProvider loaded: {model_name} ({self.dimensions} dims)")except ImportError:raise ImportError("sentence-transformers is not installed. "4 unmodified linesreturn self.embed_batch([text])[0]def embed_batch(self, texts: List[str]) -> List[List[float]]:embeddings = self._model.encode(texts, show_progress_bar=False, normalize_embeddings=True)return [emb.tolist() for emb in embeddings]11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556577 unmodified lines65666768697071727374757677787980818236 unmodified lines1191201211221231241251 unmodified line12712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616712 unmodified lines18018118218318418518653 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672681 unmodified line27027127227327427527627727827928028128228328428528628728834 unmodified lines32332432532632732832933033133233333410 unmodified lines34534634734834935035168 unmodified lines4204214224234244254266 unmodified lines4334344354364374384394404419 unmodified lines45145245345445545645745845946046146246346446546646746846947047147247347447547647747847948013 unmodified lines4944954964974984995006 unmodified lines50750850951051151251351451516 unmodified lines53253353453553653753822 unmodified lines5615625635645655665675685695705715725735745755765775785795805815825837 unmodified lines59159259359459559659712 unmodified lines6106116126136146156166176186191 unmodified line6216226236246256266276286299 unmodified lines63964064164264364464564664764864965065165265313 unmodified lines6676686696706716726736746756766776786796806816826839 unmodified lines6936946956966976986997007017024 unmodified lines7077087097107117127137147157167177187197207217227237247257267277287297307317327333 unmodified lines7377387397407417427437447457467477483 unmodified lines75275375475575675775813 unmodified lines77277377477577677777826 unmodified lines8058068078088098108118128138141 unmodified line8168178188198208218228238248258268278288298308318328338343 unmodified lines83883984084184284384431 unmodified lines87687787887988088188288388412 unmodified lines8978988999009019029038 unmodified lines9129139149159169179189199209219229234 unmodified lines92892993093193293393411 unmodified lines# =====================================================================step2map = {"ational": "ate","tional": "tion","enci": "ence","anci": "ance","izer": "ize","iser": "ise","abli": "able","alli": "al","entli": "ent","eli": "e","ousli": "ous","ization": "ize","isation": "ise","ation": "ate","ator": "ate","alism": "al","iveness": "ive","fulness": "ful","ousness": "ous","aliti": "al","iviti": "ive","biliti": "ble",}step3map = {"icate": "ic","ative": "","alize": "al","alise": "al","iciti": "ic","ical": "ic","ful": "","ness": "",}def _has_vowel(s: str) -> bool:return any(c in "aeiou" for c in s)def _measure(s: str) -> int:# Reduce non-vowels (excluding y) to C, vowels (+y) to Vreduced = ""7 unmodified lines# count "VC" patternsreturn len(re.findall(r"VC", reduced))def _ends_double_consonant(s: str) -> bool:return len(s) >= 2 and s[-1] == s[-2] and s[-1] not in "aeiou"def _ends_cvc(s: str) -> bool:if len(s) < 3:return Falsec1, v, c2 = s[-3], s[-2], s[-1]return c1 not in "aeiou" and v in "aeiou" and c2 not in "aeiouwxy"def stem(word: str) -> str:if len(word) <= 2:return word36 unmodified lines# Step 2for suffix, replacement in step2map.items():if w.endswith(suffix):base = w[: -len(suffix)]if _measure(base) > 0:w = base + replacementbreak1 unmodified line# Step 3for suffix, replacement in step3map.items():if w.endswith(suffix):base = w[: -len(suffix)]if _measure(base) > 0:w = base + replacementbreak# Step 4suffixes_step4 = ("al","ance","ence","er","ic","able","ible","ant","ement","ment","ent","tion","sion","ou","ism","ate","iti","ous","ive","ize","ise",)if w.endswith(suffixes_step4):# find matching suffix lengthmatch = re.search(r"(ement|ment|tion|sion|ance|ence|able|ible|ism|ate|iti|ous|ive|ize|ise|ant|ent|al|er|ic|ou)$",w,)if match:suffix_len = len(match.group(1))base = w[:-suffix_len]12 unmodified linesreturn w# =====================================================================# Synonym Map (Ported from synonyms.ts)# =====================================================================53 unmodified linesif other != s:synonymMap[s].add(other)def get_synonyms(stemmed_term: str) -> List[str]:return list(synonymMap.get(stemmed_term, []))# =====================================================================# CJK Segmenter (Ported from cjk-segmenter.ts)# =====================================================================CJK_RE = re.compile(r"[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\uac00-\ud7a3]")CJK_RUN_RE = re.compile(r"[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\uac00-\ud7a3]+")HANGUL_RE = re.compile(r"[\uac00-\ud7a3]")KANA_RE = re.compile(r"[\u3040-\u309f\u30a0-\u30ff]")HANGUL_BLOCK_RE = re.compile(r"[가-]+")jieba_loaded = Falsejieba_instance = Nonedef get_jieba():global jieba_loaded, jieba_instanceif jieba_loaded:1 unmodified linejieba_loaded = Truetry:import jiebajieba_instance = jiebaexcept ImportError:print("[search] Install jieba to improve Chinese word segmentation (pip install jieba)")return jieba_instancedef has_cjk(text: str) -> bool:return bool(CJK_RE.search(text))def segment_cjk(text: str) -> List[str]:if not has_cjk(text):return [text]34 unmodified linesreturn out# =====================================================================# SearchIndex (BM25 - Ported from search-index.ts)# =====================================================================class SearchIndex:def __init__(self):self.entries: Dict[str, Dict[str, Any]] = {}10 unmodified linesobs_id = obs.get("id")if not obs_id:returnterms = self.extract_terms(obs)term_freq: Dict[str, int] = {}term_count = 068 unmodified linesfor q_item in query_terms:term = q_item["term"]weight = q_item["weight"]matching_docs = self.inverted_index.get(term)if matching_docs:df = len(matching_docs)6 unmodified linesdoc_len = entry["termCount"]numerator = tf * (self.k1 + 1)denominator = tf + self.k1 * (1 - self.b + self.b * (doc_len / avg_doc_len))bm25_score = idf * (numerator / denominator) * weightscores[obs_id] = scores.get(obs_id, 0.0) + bm25_score9 unmodified linesobs_ids = self.inverted_index.get(index_term, set())prefix_df = len(obs_ids)prefix_idf = (math.log((N - prefix_df + 0.5) / (prefix_df + 0.5) + 1) * 0.5)for obs_id in obs_ids:entry = self.entries[obs_id]doc_terms = self.doc_term_counts.get(obs_id, {})tf = doc_terms.get(index_term, 0)doc_len = entry["termCount"]numerator = tf * (self.k1 + 1)denominator = tf + self.k1 * (1 - self.b + self.b * (doc_len / avg_doc_len))scores[obs_id] = (scores.get(obs_id, 0.0)+ prefix_idf * (numerator / denominator) * weight)results = []for obs_id, score in scores.items():entry = self.entries[obs_id]results.append({"obsId": obs_id, "sessionId": entry["sessionId"], "score": score})results.sort(key=lambda x: x["score"], reverse=True)return results[:limit]13 unmodified linesself.clear()if not data:returnfor k, v in data.get("entries", []):self.entries[k] = vfor term, ids in data.get("inverted", []):6 unmodified linesdef serialize_data(self) -> Dict[str, Any]:entries = list(self.entries.items())inverted = [(term, list(ids)) for term, ids in self.inverted_index.items()]doc_terms = [(id_, list(counts.items())) for id_, counts in self.doc_term_counts.items()]return {"v": 2,"entries": entries,16 unmodified linesdef tokenize(self, text: str) -> List[str]:# Strip special characters except valid separatorscleaned = re.sub(r"[^\w\s/.\\-_]", " ", text)out = []for raw in cleaned.split():if len(raw) < 2:22 unmodified lineshi = midreturn lo# =====================================================================# VectorIndex (Cosine Similarity - Ported from vector-index.ts)# =====================================================================def float32_to_base64(floats: List[float]) -> str:arr = array.array("f", floats)return base64.b64encode(arr.tobytes()).decode("utf-8")def base64_to_float32(b64: str) -> List[float]:arr = array.array("f")arr.frombytes(base64.b64decode(b64))return list(arr)def cosine_similarity(a: List[float], b: List[float]) -> float:if len(a) != len(b) or len(a) == 0:return 0.07 unmodified linesdenom = math.sqrt(norm_a) * math.sqrt(norm_b)return dot / denom if denom != 0.0 else 0.0class VectorIndex:def __init__(self):self.vectors: Dict[str, Dict[str, Any]] = {}12 unmodified linesresults = []for obs_id, entry in self.vectors.items():score = cosine_similarity(query, entry["embedding"])results.append({"obsId": obs_id, "sessionId": entry["sessionId"], "score": score})results.sort(key=lambda x: x["score"], reverse=True)return results[:limit]1 unmodified linedef size(self) -> int:return len(self.vectors)def validate_dimensions(self, expected: int) -> Tuple[List[Dict[str, Any]], Set[int]]:mismatches = []seen_dimensions = set()for obs_id, entry in self.vectors.items():9 unmodified linesdef serialize_data(self) -> List[Any]:data = []for obs_id, entry in self.vectors.items():data.append([obs_id,{"embedding": float32_to_base64(entry["embedding"]),"sessionId": entry["sessionId"],},])return datadef restore_from_data(self, data: List[Any]) -> None:13 unmodified linescontinueself.vectors[obs_id] = {"embedding": base64_to_float32(emb_b64),"sessionId": sess_id,}except Exception:continue# =====================================================================# Gemini Embedding Client (Urllib POST completion)# =====================================================================class GeminiEmbeddingProvider:def __init__(self, api_key: str):self.name = "gemini"9 unmodified linesdef embed_batch(self, texts: List[str]) -> List[List[float]]:results: List[List[float]] = []batch_limit = 100for i in range(0, len(texts), batch_limit):chunk = texts[i : i + batch_limit]payload = {"requests": [{4 unmodified linesfor t in chunk]}req_data = json.dumps(payload).encode("utf-8")url = f"{self.api_url}?key={self.api_key}"req = urllib.request.Request(url,data=req_data,headers={"Content-Type": "application/json"},method="POST",)try:with urllib.request.urlopen(req, timeout=30.0) as response:resp_data = json.loads(response.read().decode("utf-8"))for emb in resp_data.get("embeddings", []):values = emb.get("values", [])results.append(self._l2_normalize(values))except Exception as e:raise RuntimeError(f"Gemini embedding batch call failed: {e}")return resultsdef _l2_normalize(self, vec: List[float]) -> List[float]:3 unmodified linesreturn vecreturn [x / norm for x in vec]# =====================================================================# HybridSearch (Triple Stream - Ported from hybrid-search.ts)# =====================================================================class HybridSearch:def __init__(self,3 unmodified lineskv: Any,bm25_weight: float = 0.4,vector_weight: float = 0.6,graph_weight: float = 0.3,):self.bm25 = bm25self.vector = vector13 unmodified linesquery_embedding = self.embedding_provider.embed(query)vector_results = self.vector.search(query_embedding, limit * 2)except Exception:pass # Fallback to BM25# Build scores mappingscores: Dict[str, Dict[str, Any]] = {}26 unmodified lines}has_vector = len(vector_results) > 0effective_bm25_w = self.bm25_weighteffective_vector_w = self.vector_weight if has_vector else 0.0total_w = effective_bm25_w + effective_vector_wif total_w > 0:effective_bm25_w /= total_w1 unmodified linecombined = []for obs_id, s in scores.items():combined.append({"obsId": obs_id,"sessionId": s["sessionId"],"bm25Score": s["bm25Score"],"vectorScore": s["vectorScore"],"graphScore": s["graphScore"],"combinedScore": (effective_bm25_w * (1.0 / (RRF_K + s["bm25Rank"]))+ effective_vector_w * (1.0 / (RRF_K + s["vectorRank"]))),})combined.sort(key=lambda x: x["combinedScore"], reverse=True)return combined[:limit]3 unmodified lines# OpenAI Embedding Client (D5.1)# =====================================================================class OpenAIEmbeddingProvider:"""OpenAI text-embedding-3-small provider (1536 dims).31 unmodified lineswith urllib.request.urlopen(req, timeout=30.0) as response:resp_data = json.loads(response.read().decode("utf-8"))# Sort by index to preserve orderembeddings_sorted = sorted(resp_data.get("data", []), key=lambda e: e["index"])for emb in embeddings_sorted:results.append(self._l2_normalize(emb["embedding"]))except Exception as e:12 unmodified lines# SentenceTransformer Local Provider (D5.2)# =====================================================================class SentenceTransformerProvider:"""Local sentence-transformers provider (optional install).8 unmodified linesself.name = "sentence-transformers"try:from sentence_transformers import SentenceTransformer # type: ignoreself._model = SentenceTransformer(model_name)self.dimensions = self._model.get_sentence_embedding_dimension()print(f"[search] SentenceTransformerProvider loaded: {model_name} ({self.dimensions} dims)")except ImportError:raise ImportError("sentence-transformers is not installed. "4 unmodified linesreturn self.embed_batch([text])[0]def embed_batch(self, texts: List[str]) -> List[List[float]]:embeddings = self._model.encode(texts, show_progress_bar=False, normalize_embeddings=True)return [emb.tolist() for emb in embeddings]
17 unmodified lines18192021222317 unmodified lines__all__ = ["KV","normalize_folder_path", "validate_agent_id", "generate_id", "fingerprint_id","save_image_to_disk", "delete_image", "touch_image", "is_managed_image_path",]17 unmodified lines18192021222324252627282917 unmodified lines__all__ = ["KV","normalize_folder_path","validate_agent_id","generate_id","fingerprint_id","save_image_to_disk","delete_image","touch_image","is_managed_image_path",]
21 unmodified lines2223242526272822 unmodified lines515253545556574 unmodified lines62636465666721 unmodified linesreturn Falseresolved = os.path.abspath(file_path)normalized_images_dir = os.path.abspath(IMAGES_DIR)return resolved.startswith(normalized_images_dir + os.sep) or resolved == normalized_images_dirdef save_image_to_disk(base64_data: str) -> Tuple[str, int]:22 unmodified linesext = "webp"elif "gif" in meta:ext = "gif"clean_base64 = base64_data[comma_idx + 1:]elif base64_data.startswith("/9j/"):ext = "jpg"4 unmodified linesreturn file_path, 0import base64buffer = base64.b64decode(clean_base64)with open(file_path, "wb") as f:f.write(buffer)21 unmodified lines2223242526272829303122 unmodified lines545556575859604 unmodified lines6566676869707121 unmodified linesreturn Falseresolved = os.path.abspath(file_path)normalized_images_dir = os.path.abspath(IMAGES_DIR)return (resolved.startswith(normalized_images_dir + os.sep)or resolved == normalized_images_dir)def save_image_to_disk(base64_data: str) -> Tuple[str, int]:22 unmodified linesext = "webp"elif "gif" in meta:ext = "gif"clean_base64 = base64_data[comma_idx + 1 :]elif base64_data.startswith("/9j/"):ext = "jpg"4 unmodified linesreturn file_path, 0import base64buffer = base64.b64decode(clean_base64)with open(file_path, "wb") as f:f.write(buffer)
71 unmodified lines7273747576777879807 unmodified lines88899091929394959671 unmodified lines# component in the raw input before normpath has a chance to resolve it.raw_parts = path.replace("\\", "/").split("/")if any(part == ".." for part in raw_parts):raise ValueError(f"folder_path contains path traversal segment '..': {path!r}")# 2. OS-level normalisation (resolves duplicate separators, etc.)normalized = os.path.normpath(path)7 unmodified lines# Guard: also reject any ".." that somehow survives normalisation.parts = normalized.split("/")if any(part == ".." for part in parts):raise ValueError(f"folder_path contains path traversal segment '..': {path!r}")if not normalized:raise ValueError("folder_path is empty after normalization")71 unmodified lines727374757677787 unmodified lines8687888990919271 unmodified lines# component in the raw input before normpath has a chance to resolve it.raw_parts = path.replace("\\", "/").split("/")if any(part == ".." for part in raw_parts):raise ValueError(f"folder_path contains path traversal segment '..': {path!r}")# 2. OS-level normalisation (resolves duplicate separators, etc.)normalized = os.path.normpath(path)7 unmodified lines# Guard: also reject any ".." that somehow survives normalisation.parts = normalized.split("/")if any(part == ".." for part in parts):raise ValueError(f"folder_path contains path traversal segment '..': {path!r}")if not normalized:raise ValueError("folder_path is empty after normalization")
20 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535420 unmodified lineswith open(template_path, "r", encoding="utf-8") as f:template = f.read()nonce = base64.urlsafe_b64encode(secrets.token_bytes(16)).decode("utf-8").rstrip("=")# D2.2: Never embed the raw AGENTCACHE_SECRET in page source.# Replace the placeholder with an empty string — the viewer authenticates# via the Authorization header set programmatically after load.html = (template.replace("__AGENTCACHE_VIEWER_NONCE__", nonce).replace("__AGENTCACHE_VERSION__", "0.9.8").replace("__AGENTCACHE_AUTO_TOKEN__", ""))csp = "; ".join(["default-src 'none'","base-uri 'none'","frame-ancestors 'self' https://huggingface.co https://*.hf.space","object-src 'none'","form-action 'none'",f"script-src 'nonce-{nonce}'","script-src-attr 'none'","style-src 'unsafe-inline'",("connect-src 'self' https: http://localhost:* http://127.0.0.1:* ""wss: ws://localhost:* ws://127.0.0.1:* wss://localhost:* wss://127.0.0.1:*"),"img-src 'self' data:","font-src 'self'",])res = make_response(html)res.headers["Content-Type"] = "text/html; charset=utf-8"20 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565720 unmodified lineswith open(template_path, "r", encoding="utf-8") as f:template = f.read()nonce = (base64.urlsafe_b64encode(secrets.token_bytes(16)).decode("utf-8").rstrip("="))# D2.2: Never embed the raw AGENTCACHE_SECRET in page source.# Replace the placeholder with an empty string — the viewer authenticates# via the Authorization header set programmatically after load.html = (template.replace("__AGENTCACHE_VIEWER_NONCE__", nonce).replace("__AGENTCACHE_VERSION__", "0.9.8").replace("__AGENTCACHE_AUTO_TOKEN__", ""))csp = "; ".join(["default-src 'none'","base-uri 'none'","frame-ancestors 'self' https://huggingface.co https://*.hf.space","object-src 'none'","form-action 'none'",f"script-src 'nonce-{nonce}'","script-src-attr 'none'","style-src 'unsafe-inline'",("connect-src 'self' https: http://localhost:* http://127.0.0.1:* ""wss: ws://localhost:* ws://127.0.0.1:* wss://localhost:* wss://127.0.0.1:*"),"img-src 'self' data:","font-src 'self'",])res = make_response(html)res.headers["Content-Type"] = "text/html; charset=utf-8"
132 unmodified lines133134135136137138139132 unmodified linesif index_empty or not index_in_sync:reason = "empty" if index_empty else "out of sync"print(f"[persistence] Search index is {reason}. Rebuilding in background thread...")t_rebuild = threading.Thread(target=_rebuild_index,args=(kv,),132 unmodified lines133134135136137138139140141132 unmodified linesif index_empty or not index_in_sync:reason = "empty" if index_empty else "out of sync"print(f"[persistence] Search index is {reason}. Rebuilding in background thread...")t_rebuild = threading.Thread(target=_rebuild_index,args=(kv,),
2 unmodified lines3456788 unmodified lines1718192021222 unmodified lines2526272829301 unmodified line32333435363719 unmodified lines57585960616263646566676869707172737475767778798081828384858687888990919293949596971 unmodified line9910010110210310410510610710810911011111211312 unmodified lines1261271281291301311321331341351361371381391405 unmodified lines14614714814915015113 unmodified lines16516616716816917014 unmodified lines18518618718818919031 unmodified lines2222232242252262272 unmodified lines2302312322332342352362372382392 unmodified linesIntegration tests for REST endpoints using the Flask test client."""import sysimport osimport json8 unmodified lines# Fixtures# ---------------------------------------------------------------------------@pytest.fixture(scope="module")def flask_app(tmp_path_factory):tmp_dir = tmp_path_factory.mktemp("api_test_db")2 unmodified linesos.environ.pop("AGENTMEMORY_SECRET", None)from db import StateKVoriginal_init = StateKV.__init__def patched_init(self, db_path_arg=None, **kwargs):1 unmodified lineStateKV.__init__ = patched_initimport app as app_moduleos.environ.pop("AGENTCACHE_SECRET", None)os.environ.pop("AGENTMEMORY_SECRET", None)flask_application = app_module.create_app()19 unmodified lines# POST /agentcache/agent/observe# ---------------------------------------------------------------------------class TestAgentObserve:def test_valid_payload_returns_201(self, client):resp = _post(client, "/agentcache/agent/observe", {"folderPath": "/home/user/test-project","agentId": "kiro","text": "Implemented new authentication middleware","timestamp": _now(),})assert resp.status_code == 201data = resp.get_json()assert "observationId" in dataassert data["observationId"].startswith("fobs_")def test_missing_folder_path_returns_400(self, client):resp = _post(client, "/agentcache/agent/observe", {"agentId": "kiro","text": "Some work","timestamp": _now(),})assert resp.status_code == 400def test_missing_agent_id_returns_400(self, client):resp = _post(client, "/agentcache/agent/observe", {"folderPath": "/home/user/proj","text": "Some work","timestamp": _now(),})assert resp.status_code == 400def test_missing_text_returns_400(self, client):resp = _post(client, "/agentcache/agent/observe", {"folderPath": "/home/user/proj","agentId": "kiro","timestamp": _now(),})assert resp.status_code == 4001 unmodified line# POST /agentcache/search# ---------------------------------------------------------------------------class TestSearch:def test_search_with_query_returns_200(self, client):# Seed data first_post(client, "/agentcache/agent/observe", {"folderPath": "/home/user/search-proj","agentId": "kiro","text": "Refactored the authentication system","timestamp": _now(),})resp = _post(client, "/agentcache/search", {"query": "authentication"})assert resp.status_code == 200data = resp.get_json()12 unmodified lines# GET /agentcache/folders# ---------------------------------------------------------------------------class TestFolders:def test_get_folders_returns_200(self, client):# Ensure at least one folder exists from earlier tests_post(client, "/agentcache/agent/observe", {"folderPath": "/home/user/folders-check","agentId": "kiro","text": "Check folders endpoint","timestamp": _now(),})resp = client.get("/agentcache/folders")assert resp.status_code == 200data = resp.get_json()5 unmodified lines# GET /agentcache/health# ---------------------------------------------------------------------------class TestHealth:def test_health_returns_200(self, client):resp = client.get("/agentcache/health")13 unmodified lines# GET /agentcache/livez# ---------------------------------------------------------------------------class TestLivez:def test_livez_returns_200_no_auth(self, client):resp = client.get("/agentcache/livez")14 unmodified lines# Authentication# ---------------------------------------------------------------------------class TestAuthentication:def test_protected_endpoint_returns_401_with_wrong_token(self, client):os.environ["AGENTCACHE_SECRET"] = "correct-secret"31 unmodified lines# Additional endpoint smoke tests# ---------------------------------------------------------------------------class TestMemoriesEndpoint:def test_memories_list_returns_200(self, client):resp = client.get("/agentcache/memories")2 unmodified linesassert "memories" in datadef test_remember_valid_payload_returns_201(self, client):resp = _post(client, "/agentcache/remember", {"content": "API test memory content","type": "fact",})assert resp.status_code == 201def test_forget_nonexistent_id(self, client):2 unmodified lines34567898 unmodified lines181920212223242 unmodified lines272829303132331 unmodified line3536373839404119 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181 unmodified line12012112212312412512612712812913013113213313413513613713813912 unmodified lines1521531541551561571581591601611621631641651661671681691701715 unmodified lines17717817918018118218313 unmodified lines19719819920020120220314 unmodified lines21821922022122222322431 unmodified lines2562572582592602612622 unmodified lines2652662672682692702712722732742752762772782 unmodified linesIntegration tests for REST endpoints using the Flask test client."""import sysimport osimport json8 unmodified lines# Fixtures# ---------------------------------------------------------------------------@pytest.fixture(scope="module")def flask_app(tmp_path_factory):tmp_dir = tmp_path_factory.mktemp("api_test_db")2 unmodified linesos.environ.pop("AGENTMEMORY_SECRET", None)from db import StateKVoriginal_init = StateKV.__init__def patched_init(self, db_path_arg=None, **kwargs):1 unmodified lineStateKV.__init__ = patched_initimport app as app_moduleos.environ.pop("AGENTCACHE_SECRET", None)os.environ.pop("AGENTMEMORY_SECRET", None)flask_application = app_module.create_app()19 unmodified lines# POST /agentcache/agent/observe# ---------------------------------------------------------------------------class TestAgentObserve:def test_valid_payload_returns_201(self, client):resp = _post(client,"/agentcache/agent/observe",{"folderPath": "/home/user/test-project","agentId": "kiro","text": "Implemented new authentication middleware","timestamp": _now(),},)assert resp.status_code == 201data = resp.get_json()assert "observationId" in dataassert data["observationId"].startswith("fobs_")def test_missing_folder_path_returns_400(self, client):resp = _post(client,"/agentcache/agent/observe",{"agentId": "kiro","text": "Some work","timestamp": _now(),},)assert resp.status_code == 400def test_missing_agent_id_returns_400(self, client):resp = _post(client,"/agentcache/agent/observe",{"folderPath": "/home/user/proj","text": "Some work","timestamp": _now(),},)assert resp.status_code == 400def test_missing_text_returns_400(self, client):resp = _post(client,"/agentcache/agent/observe",{"folderPath": "/home/user/proj","agentId": "kiro","timestamp": _now(),},)assert resp.status_code == 4001 unmodified line# POST /agentcache/search# ---------------------------------------------------------------------------class TestSearch:def test_search_with_query_returns_200(self, client):# Seed data first_post(client,"/agentcache/agent/observe",{"folderPath": "/home/user/search-proj","agentId": "kiro","text": "Refactored the authentication system","timestamp": _now(),},)resp = _post(client, "/agentcache/search", {"query": "authentication"})assert resp.status_code == 200data = resp.get_json()12 unmodified lines# GET /agentcache/folders# ---------------------------------------------------------------------------class TestFolders:def test_get_folders_returns_200(self, client):# Ensure at least one folder exists from earlier tests_post(client,"/agentcache/agent/observe",{"folderPath": "/home/user/folders-check","agentId": "kiro","text": "Check folders endpoint","timestamp": _now(),},)resp = client.get("/agentcache/folders")assert resp.status_code == 200data = resp.get_json()5 unmodified lines# GET /agentcache/health# ---------------------------------------------------------------------------class TestHealth:def test_health_returns_200(self, client):resp = client.get("/agentcache/health")13 unmodified lines# GET /agentcache/livez# ---------------------------------------------------------------------------class TestLivez:def test_livez_returns_200_no_auth(self, client):resp = client.get("/agentcache/livez")14 unmodified lines# Authentication# ---------------------------------------------------------------------------class TestAuthentication:def test_protected_endpoint_returns_401_with_wrong_token(self, client):os.environ["AGENTCACHE_SECRET"] = "correct-secret"31 unmodified lines# Additional endpoint smoke tests# ---------------------------------------------------------------------------class TestMemoriesEndpoint:def test_memories_list_returns_200(self, client):resp = client.get("/agentcache/memories")2 unmodified linesassert "memories" in datadef test_remember_valid_payload_returns_201(self, client):resp = _post(client,"/agentcache/remember",{"content": "API test memory content","type": "fact",},)assert resp.status_code == 201def test_forget_nonexistent_id(self, client):
2 unmodified lines3456789 unmodified lines1819202122231 unmodified line2526272829302 unmodified linesTests for the /auth.md agent onboarding route."""import sysimport osimport pytest9 unmodified linesos.environ.pop("AGENTMEMORY_SECRET", None)from db import StateKVoriginal_init = StateKV.__init__def patched_init(self, db_path_arg=None, **kwargs):1 unmodified lineStateKV.__init__ = patched_initimport app as app_moduleflask_application = app_module.create_app()StateKV.__init__ = original_initflask_application.config["TESTING"] = True2 unmodified lines34567899 unmodified lines192021222324251 unmodified line272829303132332 unmodified linesTests for the /auth.md agent onboarding route."""import sysimport osimport pytest9 unmodified linesos.environ.pop("AGENTMEMORY_SECRET", None)from db import StateKVoriginal_init = StateKV.__init__def patched_init(self, db_path_arg=None, **kwargs):1 unmodified lineStateKV.__init__ = patched_initimport app as app_moduleflask_application = app_module.create_app()StateKV.__init__ = original_initflask_application.config["TESTING"] = True
2 unmodified lines3456787 unmodified lines16171819202122236 unmodified lines303132333435363738394041424344453 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031042 unmodified lines1071081091101111121131141151161171181191201211224 unmodified lines1271281291301311321331341351361371381391401411421432 unmodified lines1461471481491501514 unmodified lines1561571581591601611621631641651661671682 unmodified linesTests for context(), export_data(), and token budget enforcement."""import sysimport osimport datetime7 unmodified lines# Helpers# ---------------------------------------------------------------------------def _make_kv(tmp_path):from db import StateKVos.environ.pop("AGENTCACHE_SECRET", None)return StateKV(db_path=str(tmp_path / "test.db"))6 unmodified lines# context() tests# ---------------------------------------------------------------------------class TestContext:def test_empty_db_returns_minimal_context(self, tmp_path):"""Empty DB should return a well-formed but empty context."""from functions import contextkv = _make_kv(tmp_path)result = context(kv, {"sessionId": "sess_test_empty","project": "/home/user/my-project","budget": 2000,})assert isinstance(result, dict)assert "context" in resultassert "blocks" in result3 unmodified linesdef test_raises_on_missing_session_id(self, tmp_path):from functions import contextkv = _make_kv(tmp_path)with pytest.raises(ValueError):context(kv, {"project": "/home/user/proj"})def test_raises_on_missing_project(self, tmp_path):from functions import contextkv = _make_kv(tmp_path)with pytest.raises(ValueError):context(kv, {"sessionId": "sess_x"})def test_respects_token_budget(self, tmp_path):"""Context output tokens should not exceed the requested budget."""from functions import context, lesson_save, KVkv = _make_kv(tmp_path)project = "/home/user/budget-test"# Add many lessons to push towards the budgetfor i in range(20):lesson_save(kv, {"content": f"Lesson {i}: " + ("x " * 100),"project": project,"confidence": 0.9,})budget = 500result = context(kv, {"sessionId": "sess_budget","project": project,"budget": budget,})# Token estimate is len/3 — check that total tokens respects budgetassert result["tokens"] <= budget + 50 # small headroom for header/footerdef test_context_includes_xml_wrapper(self, tmp_path):"""Non-empty context should be wrapped in <agentcache-context>."""from functions import context, lesson_savekv = _make_kv(tmp_path)project = "/home/user/xml-test"lesson_save(kv, {"content": "Always validate user input before processing","project": project,"confidence": 0.8,})result = context(kv, {"sessionId": "sess_xml","project": project,"budget": 2000,})if result["blocks"] > 0:assert "<agentcache-context" in result["context"]2 unmodified linesdef test_token_budget_env_var_respected(self, tmp_path, monkeypatch):"""TOKEN_BUDGET env var should be used when no budget param given."""from functions import context, lesson_savekv = _make_kv(tmp_path)project = "/home/user/env-budget"monkeypatch.setenv("TOKEN_BUDGET", "100")for i in range(10):lesson_save(kv, {"content": f"Important lesson {i}: " + ("word " * 50),"project": project,"confidence": 0.9,})result = context(kv, {"sessionId": "sess_env_budget", "project": project})# Should use TOKEN_BUDGET=100 from env4 unmodified lines# export_data() tests# ---------------------------------------------------------------------------class TestExportData:def test_export_returns_folders_and_memories(self, tmp_path):from functions import folder_observe, remember, export_datakv = _make_kv(tmp_path)folder_observe(kv, {"folderPath": "/home/user/export-test","agentId": "kiro","text": "Working on export feature","timestamp": _now(),})remember(kv, {"content": "Export data uses v2 format"})result = export_data(kv, {})2 unmodified linesdef test_export_empty_db(self, tmp_path):from functions import export_datakv = _make_kv(tmp_path)result = export_data(kv, {})assert isinstance(result, dict)4 unmodified lines# estimate_tokens()# ---------------------------------------------------------------------------class TestEstimateTokens:def test_empty_string(self):from functions import estimate_tokensassert estimate_tokens("") == 0def test_typical_text(self):from functions import estimate_tokenstext = "hello world this is a test" * 10tokens = estimate_tokens(text)# Should be approximately len/32 unmodified lines34567897 unmodified lines171819202122232425266 unmodified lines3334353637383940414243444546474849505152533 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271282 unmodified lines1311321331341351361371381391401411421431441451461471481491504 unmodified lines1551561571581591601611621631641651661671681691701711721731741751762 unmodified lines1791801811821831841854 unmodified lines1901911921931941951961971981992002012022032042052 unmodified linesTests for context(), export_data(), and token budget enforcement."""import sysimport osimport datetime7 unmodified lines# Helpers# ---------------------------------------------------------------------------def _make_kv(tmp_path):from db import StateKVos.environ.pop("AGENTCACHE_SECRET", None)return StateKV(db_path=str(tmp_path / "test.db"))6 unmodified lines# context() tests# ---------------------------------------------------------------------------class TestContext:def test_empty_db_returns_minimal_context(self, tmp_path):"""Empty DB should return a well-formed but empty context."""from functions import contextkv = _make_kv(tmp_path)result = context(kv,{"sessionId": "sess_test_empty","project": "/home/user/my-project","budget": 2000,},)assert isinstance(result, dict)assert "context" in resultassert "blocks" in result3 unmodified linesdef test_raises_on_missing_session_id(self, tmp_path):from functions import contextkv = _make_kv(tmp_path)with pytest.raises(ValueError):context(kv, {"project": "/home/user/proj"})def test_raises_on_missing_project(self, tmp_path):from functions import contextkv = _make_kv(tmp_path)with pytest.raises(ValueError):context(kv, {"sessionId": "sess_x"})def test_respects_token_budget(self, tmp_path):"""Context output tokens should not exceed the requested budget."""from functions import context, lesson_savekv = _make_kv(tmp_path)project = "/home/user/budget-test"# Add many lessons to push towards the budgetfor i in range(20):lesson_save(kv,{"content": f"Lesson {i}: " + ("x " * 100),"project": project,"confidence": 0.9,},)budget = 500result = context(kv,{"sessionId": "sess_budget","project": project,"budget": budget,},)# Token estimate is len/3 — check that total tokens respects budgetassert result["tokens"] <= budget + 50 # small headroom for header/footerdef test_context_includes_xml_wrapper(self, tmp_path):"""Non-empty context should be wrapped in <agentcache-context>."""from functions import context, lesson_savekv = _make_kv(tmp_path)project = "/home/user/xml-test"lesson_save(kv,{"content": "Always validate user input before processing","project": project,"confidence": 0.8,},)result = context(kv,{"sessionId": "sess_xml","project": project,"budget": 2000,},)if result["blocks"] > 0:assert "<agentcache-context" in result["context"]2 unmodified linesdef test_token_budget_env_var_respected(self, tmp_path, monkeypatch):"""TOKEN_BUDGET env var should be used when no budget param given."""from functions import context, lesson_savekv = _make_kv(tmp_path)project = "/home/user/env-budget"monkeypatch.setenv("TOKEN_BUDGET", "100")for i in range(10):lesson_save(kv,{"content": f"Important lesson {i}: " + ("word " * 50),"project": project,"confidence": 0.9,},)result = context(kv, {"sessionId": "sess_env_budget", "project": project})# Should use TOKEN_BUDGET=100 from env4 unmodified lines# export_data() tests# ---------------------------------------------------------------------------class TestExportData:def test_export_returns_folders_and_memories(self, tmp_path):from functions import folder_observe, remember, export_datakv = _make_kv(tmp_path)folder_observe(kv,{"folderPath": "/home/user/export-test","agentId": "kiro","text": "Working on export feature","timestamp": _now(),},)remember(kv, {"content": "Export data uses v2 format"})result = export_data(kv, {})2 unmodified linesdef test_export_empty_db(self, tmp_path):from functions import export_datakv = _make_kv(tmp_path)result = export_data(kv, {})assert isinstance(result, dict)4 unmodified lines# estimate_tokens()# ---------------------------------------------------------------------------class TestEstimateTokens:def test_empty_string(self):from functions import estimate_tokensassert estimate_tokens("") == 0def test_typical_text(self):from functions import estimate_tokenstext = "hello world this is a test" * 10tokens = estimate_tokens(text)# Should be approximately len/3
3 unmodified lines4567891011121314151617183 unmodified lines2223242526272814 unmodified lines4344454647484910 unmodified lines6061626364656667686970717273745 unmodified lines8081828384858616 unmodified lines10310410510610710810920 unmodified lines13013113213313413513614 unmodified lines1511521531541551561573 unmodified lines- 100 rapid schedule_save() calls result in exactly 1 save() call.- flush() triggers immediate save without waiting for debounce timer."""import sysimport osimport timeimport threadingimport unittest.mock as mocksys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))import pytestfrom db import StateKVfrom search import SearchIndex, VectorIndexfrom functions import IndexPersistence3 unmodified linesdef make_kv(tmp_path):return StateKV(db_path=str(tmp_path / 'test_debounce.db'))class TestDebounce:14 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, 'save', side_effect=counting_save):for _ in range(100):persistence.schedule_save()# Wait for the debounce timer to fire (2× debounce window is plenty)10 unmodified linesvector = VectorIndex()# Add a doc so the index is dirtybm25.add({'id': 'obs_test1','sessionId': 'sess1','title': 'hello world','facts': [],'concepts': [],'files': [],'type': 'other',})persistence = IndexPersistence(kv, bm25, vector)persistence.DEBOUNCE_SECONDS = FAST_DEBOUNCE5 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, 'save', side_effect=counting_save):for _ in range(100):persistence.schedule_save()time.sleep(FAST_DEBOUNCE * 4)16 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, 'save', side_effect=counting_save):persistence.schedule_save()# Timer is set but hasn't fired yet (60s window)assert save_call_count[0] == 0, "save() should not have been called yet"20 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, 'save', side_effect=counting_save):persistence.flush()assert save_call_count[0] == 114 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, 'save', side_effect=counting_save):# First burstfor _ in range(10):persistence.schedule_save()3 unmodified lines45678910111213141516173 unmodified lines2122232425262714 unmodified lines4243444546474810 unmodified lines59606162636465666768697071727374755 unmodified lines8182838485868716 unmodified lines10410510610710810911020 unmodified lines13113213313413513613714 unmodified lines1521531541551561571583 unmodified lines- 100 rapid schedule_save() calls result in exactly 1 save() call.- flush() triggers immediate save without waiting for debounce timer."""import sysimport osimport timeimport unittest.mock as mocksys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom search import SearchIndex, VectorIndexfrom functions import IndexPersistence3 unmodified linesdef make_kv(tmp_path):return StateKV(db_path=str(tmp_path / "test_debounce.db"))class TestDebounce:14 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, "save", side_effect=counting_save):for _ in range(100):persistence.schedule_save()# Wait for the debounce timer to fire (2× debounce window is plenty)10 unmodified linesvector = VectorIndex()# Add a doc so the index is dirtybm25.add({"id": "obs_test1","sessionId": "sess1","title": "hello world","facts": [],"concepts": [],"files": [],"type": "other",})persistence = IndexPersistence(kv, bm25, vector)persistence.DEBOUNCE_SECONDS = FAST_DEBOUNCE5 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, "save", side_effect=counting_save):for _ in range(100):persistence.schedule_save()time.sleep(FAST_DEBOUNCE * 4)16 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, "save", side_effect=counting_save):persistence.schedule_save()# Timer is set but hasn't fired yet (60s window)assert save_call_count[0] == 0, "save() should not have been called yet"20 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, "save", side_effect=counting_save):persistence.flush()assert save_call_count[0] == 114 unmodified linessave_call_count[0] += 1original_save()with mock.patch.object(persistence, "save", side_effect=counting_save):# First burstfor _ in range(10):persistence.schedule_save()
12345677 unmodified lines15161718192014 unmodified lines35363738394041424344454617 unmodified lines6465666768699 unmodified lines798081828384854 unmodified lines90919293949596976 unmodified lines1041051061071081094 unmodified lines11411511611711811985 unmodified lines20520620720820921033 unmodified lines24424524624724824925025125225315 unmodified lines26927027127227327427527620 unmodified lines29729829930030130233 unmodified lines3363373383393403413423433443453463476 unmodified lines35435535635735835936036136236318 unmodified lines38238338438538638725 unmodified lines413414415416417418419420"""Unit tests for folderColor() and folder_graph_build() — REQ-023–REQ-028."""import osimport sysimport tempfileimport pytest7 unmodified lines# Fixtures# ---------------------------------------------------------------------------@pytest.fixture()def kv(tmp_path):"""Return a fresh in-file StateKV backed by a temp SQLite database."""14 unmodified lines# Write folders index entryindex_key = f"{folder_path}:{agent_id}"kv.set(KV.folders, index_key, {"folderPath": folder_path,"agentId": agent_id,"obsCount": count,"lastUpdated": "2025-01-15T12:00:00.000Z",})# Write observation objects if text suppliedfor i, text in enumerate(obs_texts):17 unmodified lines# Tests — folderColor helper# ---------------------------------------------------------------------------def test_folder_color_returns_hsl_string():"""folderColor should return a string matching hsl(...) format."""color = folderColor("projects/alpha")9 unmodified linesdef test_folder_color_different_paths_produce_different_colors():"""Different paths should (almost always) produce different colors."""# Use very distinct paths to ensure hash differenceassert folderColor("projects/alpha") != folderColor("projects/omega-completely-different")def test_folder_color_hsl_values_in_range():4 unmodified linesparts = [p.strip().rstrip("%") for p in inner.split(",")]hue, sat, lig = int(parts[0]), int(parts[1]), int(parts[2])assert 0 <= hue < 360assert 55 <= sat <= 79 # 55 + (h % 25)assert 38 <= lig <= 51 # 38 + (h % 14)def test_folder_color_empty_string():6 unmodified lines# Tests — empty KV returns empty graph (REQ-023)# ---------------------------------------------------------------------------def test_empty_kv_returns_empty_graph(kv):"""Empty KV returns {nodes: [], edges: []}."""result = folder_graph_build(kv)4 unmodified lines# Tests — node construction (REQ-023, REQ-024)# ---------------------------------------------------------------------------def test_one_node_per_unique_folder_path(kv):"""Two agents in the same folder produce a single node (REQ-023)."""_write_pair(kv, "projects/alpha", "kiro", obs_count=3)85 unmodified lines# Tests — same-parent edges (REQ-025)# ---------------------------------------------------------------------------def test_same_parent_edge_created(kv):"""Two folders with the same parent get a same-parent edge."""_write_pair(kv, "projects/alpha", "kiro")33 unmodified lines# Tests — cross-reference edges (REQ-026)# ---------------------------------------------------------------------------def test_cross_ref_edge_when_obs_mentions_other_folder(kv):"""A cross-ref edge is created when folder A's obs text mentions folder B's path."""_write_pair(kv, "projects/alpha", "kiro",obs_texts=["I worked on projects/beta today"])_write_pair(kv, "projects/beta", "kiro", obs_texts=["nothing"])result = folder_graph_build(kv)15 unmodified linesdef test_cross_ref_edge_from_title_mention(kv):"""Cross-ref edges are also detected via obs titles."""_write_pair(kv, "projects/alpha", "kiro",obs_texts=["some text"])# Manually insert obs with a title that mentions the other folderobs = {"id": "obs_special",20 unmodified lines# Tests — agent-shared edges (REQ-027)# ---------------------------------------------------------------------------def test_agent_shared_edge_created(kv):"""Two folders with a common agent get an agent-shared edge."""_write_pair(kv, "projects/alpha", "kiro")33 unmodified lines# Tests — edge deduplication (REQ-028)# ---------------------------------------------------------------------------def test_no_duplicate_edges(kv):"""No two edges share the same (source, target, type) pair."""_write_pair(kv, "projects/alpha", "kiro",obs_texts=["mentions projects/beta"])_write_pair(kv, "projects/beta", "kiro",obs_texts=["mentions projects/alpha"])result = folder_graph_build(kv)seen = set()6 unmodified linesdef test_ab_and_ba_treated_as_same_edge(kv):"""(a, b, type) and (b, a, type) are considered the same edge."""# Both folders reference each other — should produce only one cross-ref edge_write_pair(kv, "projects/alpha", "kiro",obs_texts=["See also projects/beta for details"])_write_pair(kv, "projects/beta", "kiro",obs_texts=["Related to projects/alpha work"])result = folder_graph_build(kv)cross_edges = [e for e in result["edges"] if e["type"] == "cross-ref"]18 unmodified lines# Tests — return structure# ---------------------------------------------------------------------------def test_return_has_nodes_and_edges_keys(kv):"""Result always has 'nodes' and 'edges' keys."""_write_pair(kv, "projects/alpha", "kiro")25 unmodified linesdef test_edge_types_are_valid(kv):"""All edge types are one of the three valid values."""_write_pair(kv, "projects/alpha", "kiro",obs_texts=["mentions projects/beta"])_write_pair(kv, "projects/beta", "kiro")result = folder_graph_build(kv)12345677 unmodified lines1516171819202114 unmodified lines3637383940414243444546474849505117 unmodified lines697071727374759 unmodified lines8586878889909192934 unmodified lines98991001011021031041056 unmodified lines1121131141151161171184 unmodified lines12312412512612712812985 unmodified lines21521621721821922022133 unmodified lines25525625725825926026126226326426526615 unmodified lines28228328428528628728820 unmodified lines30931031131231331431533 unmodified lines3493503513523533543553563573583596 unmodified lines36636736836937037137237337437537637718 unmodified lines39639739839940040140225 unmodified lines428429430431432433434"""Unit tests for folderColor() and folder_graph_build() — REQ-023–REQ-028."""import osimport sysimport pytest7 unmodified lines# Fixtures# ---------------------------------------------------------------------------@pytest.fixture()def kv(tmp_path):"""Return a fresh in-file StateKV backed by a temp SQLite database."""14 unmodified lines# Write folders index entryindex_key = f"{folder_path}:{agent_id}"kv.set(KV.folders,index_key,{"folderPath": folder_path,"agentId": agent_id,"obsCount": count,"lastUpdated": "2025-01-15T12:00:00.000Z",},)# Write observation objects if text suppliedfor i, text in enumerate(obs_texts):17 unmodified lines# Tests — folderColor helper# ---------------------------------------------------------------------------def test_folder_color_returns_hsl_string():"""folderColor should return a string matching hsl(...) format."""color = folderColor("projects/alpha")9 unmodified linesdef test_folder_color_different_paths_produce_different_colors():"""Different paths should (almost always) produce different colors."""# Use very distinct paths to ensure hash differenceassert folderColor("projects/alpha") != folderColor("projects/omega-completely-different")def test_folder_color_hsl_values_in_range():4 unmodified linesparts = [p.strip().rstrip("%") for p in inner.split(",")]hue, sat, lig = int(parts[0]), int(parts[1]), int(parts[2])assert 0 <= hue < 360assert 55 <= sat <= 79 # 55 + (h % 25)assert 38 <= lig <= 51 # 38 + (h % 14)def test_folder_color_empty_string():6 unmodified lines# Tests — empty KV returns empty graph (REQ-023)# ---------------------------------------------------------------------------def test_empty_kv_returns_empty_graph(kv):"""Empty KV returns {nodes: [], edges: []}."""result = folder_graph_build(kv)4 unmodified lines# Tests — node construction (REQ-023, REQ-024)# ---------------------------------------------------------------------------def test_one_node_per_unique_folder_path(kv):"""Two agents in the same folder produce a single node (REQ-023)."""_write_pair(kv, "projects/alpha", "kiro", obs_count=3)85 unmodified lines# Tests — same-parent edges (REQ-025)# ---------------------------------------------------------------------------def test_same_parent_edge_created(kv):"""Two folders with the same parent get a same-parent edge."""_write_pair(kv, "projects/alpha", "kiro")33 unmodified lines# Tests — cross-reference edges (REQ-026)# ---------------------------------------------------------------------------def test_cross_ref_edge_when_obs_mentions_other_folder(kv):"""A cross-ref edge is created when folder A's obs text mentions folder B's path."""_write_pair(kv, "projects/alpha", "kiro", obs_texts=["I worked on projects/beta today"])_write_pair(kv, "projects/beta", "kiro", obs_texts=["nothing"])result = folder_graph_build(kv)15 unmodified linesdef test_cross_ref_edge_from_title_mention(kv):"""Cross-ref edges are also detected via obs titles."""_write_pair(kv, "projects/alpha", "kiro", obs_texts=["some text"])# Manually insert obs with a title that mentions the other folderobs = {"id": "obs_special",20 unmodified lines# Tests — agent-shared edges (REQ-027)# ---------------------------------------------------------------------------def test_agent_shared_edge_created(kv):"""Two folders with a common agent get an agent-shared edge."""_write_pair(kv, "projects/alpha", "kiro")33 unmodified lines# Tests — edge deduplication (REQ-028)# ---------------------------------------------------------------------------def test_no_duplicate_edges(kv):"""No two edges share the same (source, target, type) pair."""_write_pair(kv, "projects/alpha", "kiro", obs_texts=["mentions projects/beta"])_write_pair(kv, "projects/beta", "kiro", obs_texts=["mentions projects/alpha"])result = folder_graph_build(kv)seen = set()6 unmodified linesdef test_ab_and_ba_treated_as_same_edge(kv):"""(a, b, type) and (b, a, type) are considered the same edge."""# Both folders reference each other — should produce only one cross-ref edge_write_pair(kv, "projects/alpha", "kiro", obs_texts=["See also projects/beta for details"])_write_pair(kv, "projects/beta", "kiro", obs_texts=["Related to projects/alpha work"])result = folder_graph_build(kv)cross_edges = [e for e in result["edges"] if e["type"] == "cross-ref"]18 unmodified lines# Tests — return structure# ---------------------------------------------------------------------------def test_return_has_nodes_and_edges_keys(kv):"""Result always has 'nodes' and 'edges' keys."""_write_pair(kv, "projects/alpha", "kiro")25 unmodified linesdef test_edge_types_are_valid(kv):"""All edge types are one of the three valid values."""_write_pair(kv, "projects/alpha", "kiro", obs_texts=["mentions projects/beta"])_write_pair(kv, "projects/beta", "kiro")result = folder_graph_build(kv)
1234567891011121314151617181920212223242526272 unmodified lines303132333435363738394041424344454647484950515253541 unmodified line5657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Unit tests for folder_observe (REQ-008, REQ-010, REQ-011, REQ-015)."""import sysimport osimport pytestimport tempfileimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))from db import StateKVimport functionsfrom functions import folder_observe, KVdef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), 'test.db')return StateKV(db_path=db_path)def base_payload(**overrides):payload = {'folderPath': '/home/user/projects/myapp','agentId': 'kiro','text': 'Edited src/app.py to add a new route','timestamp': datetime.datetime.utcnow().isoformat() + 'Z',}payload.update(overrides)return payload2 unmodified linesclass TestFolderObserveMissingFields:def test_missing_folder_path(self, tmp_path):kv = make_kv(tmp_path)with pytest.raises(ValueError, match='folderPath'):folder_observe(kv, base_payload(folderPath=''))def test_missing_agent_id(self, tmp_path):kv = make_kv(tmp_path)with pytest.raises(ValueError, match='agentId'):folder_observe(kv, base_payload(agentId=''))def test_missing_text(self, tmp_path):kv = make_kv(tmp_path)with pytest.raises(ValueError, match='text'):folder_observe(kv, base_payload(text=''))def test_missing_timestamp_defaults(self, tmp_path):kv = make_kv(tmp_path)payload = base_payload()del payload['timestamp']# timestamp is required — should raisewith pytest.raises(ValueError, match='timestamp'):folder_observe(kv, payload)1 unmodified linedef test_returns_observation_id(self, tmp_path):kv = make_kv(tmp_path)result = folder_observe(kv, base_payload())assert 'observationId' in resultassert result['observationId'].startswith('fobs_')def test_obs_stored_in_kv(self, tmp_path):kv = make_kv(tmp_path)result = folder_observe(kv, base_payload())obs_id = result['observationId']fp = 'home/user/projects/myapp' # normalizedstored = kv.get(KV.folder_obs(fp, 'kiro'), obs_id)assert stored is not Noneassert stored['id'] == obs_iddef test_obs_count_incremented(self, tmp_path):kv = make_kv(tmp_path)folder_observe(kv, base_payload(text="First observation"))folder_observe(kv, base_payload(text="Second observation"))fp = 'home/user/projects/myapp'meta = kv.get(KV.folder_meta(fp, 'kiro'), 'meta')assert meta is not Noneassert meta['obsCount'] == 2def test_folders_index_upserted(self, tmp_path):kv = make_kv(tmp_path)folder_observe(kv, base_payload())fp = 'home/user/projects/myapp'entry = kv.get(KV.folders, f'{fp}:kiro')assert entry is not Noneassert entry['folderPath'] == fpassert entry['agentId'] == 'kiro'def test_text_capped_at_4000(self, tmp_path):kv = make_kv(tmp_path)long_text = 'x' * 5000result = folder_observe(kv, base_payload(text=long_text))fp = 'home/user/projects/myapp'stored = kv.get(KV.folder_obs(fp, 'kiro'), result['observationId'])assert len(stored['text']) <= 4000class TestFolderObserveCap:def test_cap_enforced(self, tmp_path, monkeypatch):monkeypatch.setenv('MAX_OBS_PER_FOLDER', '3')kv = make_kv(tmp_path)for i in range(3):folder_observe(kv, base_payload(text=f"observation {i}"))with pytest.raises(ValueError, match='limit'):folder_observe(kv, base_payload(text="observation 4"))class TestFolderObservePairIsolation:def test_different_pairs_isolated(self, tmp_path):kv = make_kv(tmp_path)folder_observe(kv, base_payload(folderPath='/home/user/proj-a', agentId='kiro'))folder_observe(kv, base_payload(folderPath='/home/user/proj-b', agentId='claude'))fp_a = 'home/user/proj-a'fp_b = 'home/user/proj-b'obs_a = kv.list(KV.folder_obs(fp_a, 'kiro'))obs_b = kv.list(KV.folder_obs(fp_b, 'claude'))ids_a = {o['id'] for o in obs_a}ids_b = {o['id'] for o in obs_b}assert ids_a.isdisjoint(ids_b)12345678910111213141516171819202122232425262 unmodified lines293031323334353637383940414243444546474849505152531 unmodified line555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120"""Unit tests for folder_observe (REQ-008, REQ-010, REQ-011, REQ-015)."""import sysimport osimport pytestimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import folder_observe, KVdef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), "test.db")return StateKV(db_path=db_path)def base_payload(**overrides):payload = {"folderPath": "/home/user/projects/myapp","agentId": "kiro","text": "Edited src/app.py to add a new route","timestamp": datetime.datetime.utcnow().isoformat() + "Z",}payload.update(overrides)return payload2 unmodified linesclass TestFolderObserveMissingFields:def test_missing_folder_path(self, tmp_path):kv = make_kv(tmp_path)with pytest.raises(ValueError, match="folderPath"):folder_observe(kv, base_payload(folderPath=""))def test_missing_agent_id(self, tmp_path):kv = make_kv(tmp_path)with pytest.raises(ValueError, match="agentId"):folder_observe(kv, base_payload(agentId=""))def test_missing_text(self, tmp_path):kv = make_kv(tmp_path)with pytest.raises(ValueError, match="text"):folder_observe(kv, base_payload(text=""))def test_missing_timestamp_defaults(self, tmp_path):kv = make_kv(tmp_path)payload = base_payload()del payload["timestamp"]# timestamp is required — should raisewith pytest.raises(ValueError, match="timestamp"):folder_observe(kv, payload)1 unmodified linedef test_returns_observation_id(self, tmp_path):kv = make_kv(tmp_path)result = folder_observe(kv, base_payload())assert "observationId" in resultassert result["observationId"].startswith("fobs_")def test_obs_stored_in_kv(self, tmp_path):kv = make_kv(tmp_path)result = folder_observe(kv, base_payload())obs_id = result["observationId"]fp = "home/user/projects/myapp" # normalizedstored = kv.get(KV.folder_obs(fp, "kiro"), obs_id)assert stored is not Noneassert stored["id"] == obs_iddef test_obs_count_incremented(self, tmp_path):kv = make_kv(tmp_path)folder_observe(kv, base_payload(text="First observation"))folder_observe(kv, base_payload(text="Second observation"))fp = "home/user/projects/myapp"meta = kv.get(KV.folder_meta(fp, "kiro"), "meta")assert meta is not Noneassert meta["obsCount"] == 2def test_folders_index_upserted(self, tmp_path):kv = make_kv(tmp_path)folder_observe(kv, base_payload())fp = "home/user/projects/myapp"entry = kv.get(KV.folders, f"{fp}:kiro")assert entry is not Noneassert entry["folderPath"] == fpassert entry["agentId"] == "kiro"def test_text_capped_at_4000(self, tmp_path):kv = make_kv(tmp_path)long_text = "x" * 5000result = folder_observe(kv, base_payload(text=long_text))fp = "home/user/projects/myapp"stored = kv.get(KV.folder_obs(fp, "kiro"), result["observationId"])assert len(stored["text"]) <= 4000class TestFolderObserveCap:def test_cap_enforced(self, tmp_path, monkeypatch):monkeypatch.setenv("MAX_OBS_PER_FOLDER", "3")kv = make_kv(tmp_path)for i in range(3):folder_observe(kv, base_payload(text=f"observation {i}"))with pytest.raises(ValueError, match="limit"):folder_observe(kv, base_payload(text="observation 4"))class TestFolderObservePairIsolation:def test_different_pairs_isolated(self, tmp_path):kv = make_kv(tmp_path)folder_observe(kv, base_payload(folderPath="/home/user/proj-a", agentId="kiro"))folder_observe(kv, base_payload(folderPath="/home/user/proj-b", agentId="claude"))fp_a = "home/user/proj-a"fp_b = "home/user/proj-b"obs_a = kv.list(KV.folder_obs(fp_a, "kiro"))obs_b = kv.list(KV.folder_obs(fp_b, "claude"))ids_a = {o["id"] for o in obs_a}ids_b = {o["id"] for o in obs_b}assert ids_a.isdisjoint(ids_b)
12345678910111213141516171819202122232425262728291 unmodified line313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Unit tests for forget() folder-based deletion (REQ-029–REQ-033)."""import sysimport osimport pytestimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))from db import StateKVfrom functions import folder_observe, forget, KVdef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), 'test.db')return StateKV(db_path=db_path)def add_obs(kv, folder='/home/user/proj', agent='kiro', n=1):ids = []for i in range(n):result = folder_observe(kv, {'folderPath': folder,'agentId': agent,'text': f'observation {i}','timestamp': datetime.datetime.utcnow().isoformat() + 'Z',})ids.append(result['observationId'])return ids1 unmodified linedef test_full_deletion_clears_obs(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, n=3)fp = 'home/user/proj'result = forget(kv, {'folderPath': '/home/user/proj', 'agentId': 'kiro'})assert result['deleted'] >= 3obs = kv.list(KV.folder_obs(fp, 'kiro'))assert len(obs) == 0def test_full_deletion_removes_index_entry(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv)fp = 'home/user/proj'forget(kv, {'folderPath': '/home/user/proj', 'agentId': 'kiro'})entry = kv.get(KV.folders, f'{fp}:kiro')assert entry is Nonedef test_full_deletion_removes_meta(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv)fp = 'home/user/proj'forget(kv, {'folderPath': '/home/user/proj', 'agentId': 'kiro'})meta = kv.get(KV.folder_meta(fp, 'kiro'), 'meta')assert meta is Nonedef test_deleted_count_matches(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, n=5)result = forget(kv, {'folderPath': '/home/user/proj', 'agentId': 'kiro'})assert result['deleted'] == 5class TestForgetPartial:def test_partial_deletion(self, tmp_path):kv = make_kv(tmp_path)ids = add_obs(kv, n=4)fp = 'home/user/proj'to_delete = ids[:2]result = forget(kv, {'folderPath': '/home/user/proj','agentId': 'kiro','observationIds': to_delete,})assert result['deleted'] == 2remaining = kv.list(KV.folder_obs(fp, 'kiro'))remaining_ids = {o['id'] for o in remaining}for oid in to_delete:assert oid not in remaining_idsdef test_partial_decrements_obs_count(self, tmp_path):kv = make_kv(tmp_path)ids = add_obs(kv, n=4)fp = 'home/user/proj'forget(kv, {'folderPath': '/home/user/proj','agentId': 'kiro','observationIds': ids[:2],})meta = kv.get(KV.folder_meta(fp, 'kiro'), 'meta')assert meta['obsCount'] == 2class TestForgetMemory:def test_delete_global_memory(self, tmp_path):kv = make_kv(tmp_path)from functions import rememberresult = remember(kv, {'content': 'Important insight', 'type': 'fact'})mem_id = result['memory']['id']forget_result = forget(kv, {'memoryId': mem_id})assert forget_result['deleted'] >= 1stored = kv.get(KV.memories, mem_id)assert stored is None12345678910111213141516171819202122232425262728293031321 unmodified line343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""Unit tests for forget() folder-based deletion (REQ-029–REQ-033)."""import sysimport osimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import folder_observe, forget, KVdef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), "test.db")return StateKV(db_path=db_path)def add_obs(kv, folder="/home/user/proj", agent="kiro", n=1):ids = []for i in range(n):result = folder_observe(kv,{"folderPath": folder,"agentId": agent,"text": f"observation {i}","timestamp": datetime.datetime.utcnow().isoformat() + "Z",},)ids.append(result["observationId"])return ids1 unmodified linedef test_full_deletion_clears_obs(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, n=3)fp = "home/user/proj"result = forget(kv, {"folderPath": "/home/user/proj", "agentId": "kiro"})assert result["deleted"] >= 3obs = kv.list(KV.folder_obs(fp, "kiro"))assert len(obs) == 0def test_full_deletion_removes_index_entry(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv)fp = "home/user/proj"forget(kv, {"folderPath": "/home/user/proj", "agentId": "kiro"})entry = kv.get(KV.folders, f"{fp}:kiro")assert entry is Nonedef test_full_deletion_removes_meta(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv)fp = "home/user/proj"forget(kv, {"folderPath": "/home/user/proj", "agentId": "kiro"})meta = kv.get(KV.folder_meta(fp, "kiro"), "meta")assert meta is Nonedef test_deleted_count_matches(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, n=5)result = forget(kv, {"folderPath": "/home/user/proj", "agentId": "kiro"})assert result["deleted"] == 5class TestForgetPartial:def test_partial_deletion(self, tmp_path):kv = make_kv(tmp_path)ids = add_obs(kv, n=4)fp = "home/user/proj"to_delete = ids[:2]result = forget(kv,{"folderPath": "/home/user/proj","agentId": "kiro","observationIds": to_delete,},)assert result["deleted"] == 2remaining = kv.list(KV.folder_obs(fp, "kiro"))remaining_ids = {o["id"] for o in remaining}for oid in to_delete:assert oid not in remaining_idsdef test_partial_decrements_obs_count(self, tmp_path):kv = make_kv(tmp_path)ids = add_obs(kv, n=4)fp = "home/user/proj"forget(kv,{"folderPath": "/home/user/proj","agentId": "kiro","observationIds": ids[:2],},)meta = kv.get(KV.folder_meta(fp, "kiro"), "meta")assert meta["obsCount"] == 2class TestForgetMemory:def test_delete_global_memory(self, tmp_path):kv = make_kv(tmp_path)from functions import rememberresult = remember(kv, {"content": "Important insight", "type": "fact"})mem_id = result["memory"]["id"]forget_result = forget(kv, {"memoryId": mem_id})assert forget_result["deleted"] >= 1stored = kv.get(KV.memories, mem_id)assert stored is None
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Unit tests for folder_graph_build (REQ-023–REQ-028)."""import sysimport osimport pytestimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))from db import StateKVfrom functions import folder_observe, folder_graph_builddef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), 'test.db')return StateKV(db_path=db_path)def add_obs(kv, folder, agent='kiro', text='obs'):folder_observe(kv, {'folderPath': folder,'agentId': agent,'text': text,'timestamp': datetime.datetime.utcnow().isoformat() + 'Z',})class TestGraphEmpty:def test_empty_kv_returns_empty(self, tmp_path):kv = make_kv(tmp_path)result = folder_graph_build(kv)assert result == {'nodes': [], 'edges': []}class TestGraphNodes:def test_one_node_per_folder(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, '/home/user/proj-a', agent='kiro')add_obs(kv, '/home/user/proj-a', agent='claude') # same folder, different agentadd_obs(kv, '/home/user/proj-b', agent='kiro')result = folder_graph_build(kv)node_ids = [n['id'] for n in result['nodes']]assert len(node_ids) == len(set(node_ids)) # no duplicates# 2 unique foldersassert len(result['nodes']) == 2def test_node_has_required_fields(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, '/home/user/proj')result = folder_graph_build(kv)node = result['nodes'][0]assert 'id' in nodeassert 'label' in nodeassert 'folderPath' in nodeassert 'agentIds' in nodeassert 'obsCount' in nodeassert 'color' in nodedef test_agent_ids_aggregated(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, '/home/user/proj', agent='kiro')add_obs(kv, '/home/user/proj', agent='claude')result = folder_graph_build(kv)node = result['nodes'][0]assert 'kiro' in node['agentIds']assert 'claude' in node['agentIds']class TestGraphEdges:def test_same_parent_edge(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, '/home/user/proj/src')add_obs(kv, '/home/user/proj/tests')result = folder_graph_build(kv)same_parent = [e for e in result['edges'] if e['type'] == 'same-parent']assert len(same_parent) >= 1def test_no_duplicate_edges(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, '/home/user/proj/src')add_obs(kv, '/home/user/proj/tests')result = folder_graph_build(kv)edge_keys = [(e['source'], e['target'], e['type']) for e in result['edges']]assert len(edge_keys) == len(set(edge_keys))def test_agent_shared_edge(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, '/home/user/proj-a', agent='kiro')add_obs(kv, '/home/user/proj-b', agent='kiro')result = folder_graph_build(kv)agent_edges = [e for e in result['edges'] if e['type'] == 'agent-shared']assert len(agent_edges) >= 1def test_cross_ref_edge(self, tmp_path):kv = make_kv(tmp_path)fp_b = 'home/user/proj-b'add_obs(kv, '/home/user/proj-a', text=f'Modified files in {fp_b}')add_obs(kv, '/home/user/proj-b', text='Normal work')result = folder_graph_build(kv)cross_ref = [e for e in result['edges'] if e['type'] == 'cross-ref']assert len(cross_ref) >= 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Unit tests for folder_graph_build (REQ-023–REQ-028)."""import sysimport osimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import folder_observe, folder_graph_builddef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), "test.db")return StateKV(db_path=db_path)def add_obs(kv, folder, agent="kiro", text="obs"):folder_observe(kv,{"folderPath": folder,"agentId": agent,"text": text,"timestamp": datetime.datetime.utcnow().isoformat() + "Z",},)class TestGraphEmpty:def test_empty_kv_returns_empty(self, tmp_path):kv = make_kv(tmp_path)result = folder_graph_build(kv)assert result == {"nodes": [], "edges": []}class TestGraphNodes:def test_one_node_per_folder(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, "/home/user/proj-a", agent="kiro")add_obs(kv, "/home/user/proj-a", agent="claude") # same folder, different agentadd_obs(kv, "/home/user/proj-b", agent="kiro")result = folder_graph_build(kv)node_ids = [n["id"] for n in result["nodes"]]assert len(node_ids) == len(set(node_ids)) # no duplicates# 2 unique foldersassert len(result["nodes"]) == 2def test_node_has_required_fields(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, "/home/user/proj")result = folder_graph_build(kv)node = result["nodes"][0]assert "id" in nodeassert "label" in nodeassert "folderPath" in nodeassert "agentIds" in nodeassert "obsCount" in nodeassert "color" in nodedef test_agent_ids_aggregated(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, "/home/user/proj", agent="kiro")add_obs(kv, "/home/user/proj", agent="claude")result = folder_graph_build(kv)node = result["nodes"][0]assert "kiro" in node["agentIds"]assert "claude" in node["agentIds"]class TestGraphEdges:def test_same_parent_edge(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, "/home/user/proj/src")add_obs(kv, "/home/user/proj/tests")result = folder_graph_build(kv)same_parent = [e for e in result["edges"] if e["type"] == "same-parent"]assert len(same_parent) >= 1def test_no_duplicate_edges(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, "/home/user/proj/src")add_obs(kv, "/home/user/proj/tests")result = folder_graph_build(kv)edge_keys = [(e["source"], e["target"], e["type"]) for e in result["edges"]]assert len(edge_keys) == len(set(edge_keys))def test_agent_shared_edge(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, "/home/user/proj-a", agent="kiro")add_obs(kv, "/home/user/proj-b", agent="kiro")result = folder_graph_build(kv)agent_edges = [e for e in result["edges"] if e["type"] == "agent-shared"]assert len(agent_edges) >= 1def test_cross_ref_edge(self, tmp_path):kv = make_kv(tmp_path)fp_b = "home/user/proj-b"add_obs(kv, "/home/user/proj-a", text=f"Modified files in {fp_b}")add_obs(kv, "/home/user/proj-b", text="Normal work")result = folder_graph_build(kv)cross_ref = [e for e in result["edges"] if e["type"] == "cross-ref"]assert len(cross_ref) >= 1
1234567891011121314151617181920212223242526272829303132333435363738394041424344455 unmodified lines515253545556575859606162636465666768691 unmodified line7172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Unit tests for migrate_sessions_to_folders (REQ-058–REQ-062)."""import sysimport osimport pytestimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))from db import StateKVfrom functions import migrate_sessions_to_folders, KVdef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), 'test.db')return StateKV(db_path=db_path)def seed_session(kv, session_id='sess_001', cwd='/home/user/proj', agent='kiro', obs_count=3):"""Seed a legacy session with observations into the old schema."""ts = datetime.datetime.utcnow().isoformat() + 'Z'session = {'id': session_id,'project': cwd,'cwd': cwd,'agentId': agent,'startedAt': ts,'updatedAt': ts,'status': 'completed',}kv.set(KV.sessions, session_id, session)obs_ids = []for i in range(obs_count):obs_id = f'obs_{i}'obs = {'id': obs_id,'sessionId': session_id,'timestamp': ts,'type': 'file_edit','title': f'Edit {i}','narrative': f'Edited file {i}','concepts': ['python'],'files': [f'src/file_{i}.py'],'importance': 5,}kv.set(KV.observations(session_id), obs_id, obs)obs_ids.append(obs_id)5 unmodified lineskv = make_kv(tmp_path)seed_session(kv)result = migrate_sessions_to_folders(kv, dry_run=True)assert result['migrated_sessions'] > 0assert result['migrated_observations'] > 0# No folder obs should have been writtenfp = 'home/user/proj'obs = kv.list(KV.folder_obs(fp, 'kiro'))assert len(obs) == 0def test_dry_run_returns_counts(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv, obs_count=5)result = migrate_sessions_to_folders(kv, dry_run=True)assert result['migrated_observations'] == 5assert result['dry_run'] is Trueclass TestMigrateActual:1 unmodified linekv = make_kv(tmp_path)seed_session(kv, obs_count=3)migrate_sessions_to_folders(kv, dry_run=False)fp = 'home/user/proj'obs = kv.list(KV.folder_obs(fp, 'kiro'))assert len(obs) == 3def test_skips_raw_observations(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv, obs_count=2)# Add a raw obskv.set(KV.observations('sess_001'), 'obs_0:raw', {'id': 'obs_0:raw', 'sessionId': 'sess_001','timestamp': datetime.datetime.utcnow().isoformat() + 'Z',})result = migrate_sessions_to_folders(kv, dry_run=False)# Raw obs should not be countedassert result['migrated_observations'] == 2def test_nondestructive(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv)migrate_sessions_to_folders(kv, dry_run=False)# Old session data still theresession = kv.get(KV.sessions, 'sess_001')assert session is not Nonedef test_unknown_fallback(self, tmp_path):kv = make_kv(tmp_path)# Session with no cwd or projectts = datetime.datetime.utcnow().isoformat() + 'Z'kv.set(KV.sessions, 'sess_no_path', {'id': 'sess_no_path', 'startedAt': ts, 'updatedAt': ts, 'status': 'completed',})kv.set(KV.observations('sess_no_path'), 'obs_x', {'id': 'obs_x', 'sessionId': 'sess_no_path','timestamp': ts, 'type': 'other', 'title': 'x', 'narrative': 'x',})result = migrate_sessions_to_folders(kv, dry_run=False)# Should succeed with 'unknown' fallbackassert result['migrated_sessions'] >= 1def test_returns_error_list(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv)result = migrate_sessions_to_folders(kv, dry_run=False)assert 'errors' in resultassert isinstance(result['errors'], list)12345678910111213141516171819202122232425262728293031323334353637383940414243444546475 unmodified lines535455565758596061626364656667686970711 unmodified line737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Unit tests for migrate_sessions_to_folders (REQ-058–REQ-062)."""import sysimport osimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import migrate_sessions_to_folders, KVdef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), "test.db")return StateKV(db_path=db_path)def seed_session(kv, session_id="sess_001", cwd="/home/user/proj", agent="kiro", obs_count=3):"""Seed a legacy session with observations into the old schema."""ts = datetime.datetime.utcnow().isoformat() + "Z"session = {"id": session_id,"project": cwd,"cwd": cwd,"agentId": agent,"startedAt": ts,"updatedAt": ts,"status": "completed",}kv.set(KV.sessions, session_id, session)obs_ids = []for i in range(obs_count):obs_id = f"obs_{i}"obs = {"id": obs_id,"sessionId": session_id,"timestamp": ts,"type": "file_edit","title": f"Edit {i}","narrative": f"Edited file {i}","concepts": ["python"],"files": [f"src/file_{i}.py"],"importance": 5,}kv.set(KV.observations(session_id), obs_id, obs)obs_ids.append(obs_id)5 unmodified lineskv = make_kv(tmp_path)seed_session(kv)result = migrate_sessions_to_folders(kv, dry_run=True)assert result["migrated_sessions"] > 0assert result["migrated_observations"] > 0# No folder obs should have been writtenfp = "home/user/proj"obs = kv.list(KV.folder_obs(fp, "kiro"))assert len(obs) == 0def test_dry_run_returns_counts(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv, obs_count=5)result = migrate_sessions_to_folders(kv, dry_run=True)assert result["migrated_observations"] == 5assert result["dry_run"] is Trueclass TestMigrateActual:1 unmodified linekv = make_kv(tmp_path)seed_session(kv, obs_count=3)migrate_sessions_to_folders(kv, dry_run=False)fp = "home/user/proj"obs = kv.list(KV.folder_obs(fp, "kiro"))assert len(obs) == 3def test_skips_raw_observations(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv, obs_count=2)# Add a raw obskv.set(KV.observations("sess_001"),"obs_0:raw",{"id": "obs_0:raw","sessionId": "sess_001","timestamp": datetime.datetime.utcnow().isoformat() + "Z",},)result = migrate_sessions_to_folders(kv, dry_run=False)# Raw obs should not be countedassert result["migrated_observations"] == 2def test_nondestructive(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv)migrate_sessions_to_folders(kv, dry_run=False)# Old session data still theresession = kv.get(KV.sessions, "sess_001")assert session is not Nonedef test_unknown_fallback(self, tmp_path):kv = make_kv(tmp_path)# Session with no cwd or projectts = datetime.datetime.utcnow().isoformat() + "Z"kv.set(KV.sessions,"sess_no_path",{"id": "sess_no_path","startedAt": ts,"updatedAt": ts,"status": "completed",},)kv.set(KV.observations("sess_no_path"),"obs_x",{"id": "obs_x","sessionId": "sess_no_path","timestamp": ts,"type": "other","title": "x","narrative": "x",},)result = migrate_sessions_to_folders(kv, dry_run=False)# Should succeed with 'unknown' fallbackassert result["migrated_sessions"] >= 1def test_returns_error_list(self, tmp_path):kv = make_kv(tmp_path)seed_session(kv)result = migrate_sessions_to_folders(kv, dry_run=False)assert "errors" in resultassert isinstance(result["errors"], list)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Unit tests for normalize_folder_path (REQ-002, REQ-063, REQ-064, REQ-066)."""import sysimport osimport pytestsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))from functions import normalize_folder_pathclass TestNormalizeFolderPath:def test_unix_path(self):assert normalize_folder_path('/home/user/projects/myapp') == 'home/user/projects/myapp'def test_windows_path(self):result = normalize_folder_path('C:\\Users\\foo\\projects\\myapp')assert '\\' not in resultassert 'Users' in result or 'users' in result.lower()def test_trailing_slash_stripped(self):result = normalize_folder_path('/home/user/projects/')assert not result.endswith('/')def test_leading_slash_stripped(self):result = normalize_folder_path('/home/user/projects')assert not result.startswith('/')def test_double_slashes_collapsed(self):result = normalize_folder_path('/home//user///projects')assert '//' not in resultdef test_empty_string_raises(self):with pytest.raises(ValueError):normalize_folder_path('')def test_path_traversal_raises(self):with pytest.raises(ValueError):normalize_folder_path('/home/user/../../etc/passwd')def test_length_cap(self):long_path = 'a/' * 300result = normalize_folder_path(long_path)assert len(result) <= 512def test_idempotent(self):path = '/home/user/projects/myapp'once = normalize_folder_path(path)twice = normalize_folder_path(once)assert once == twicedef test_relative_path(self):result = normalize_folder_path('projects/myapp/src')assert result == 'projects/myapp/src'def test_windows_forward_slashes(self):result = normalize_folder_path('C:/Users/foo/projects')assert '\\' not in resultdef test_single_segment(self):result = normalize_folder_path('/workspace')assert result == 'workspace'12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Unit tests for normalize_folder_path (REQ-002, REQ-063, REQ-064, REQ-066)."""import sysimport osimport pytestsys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from functions import normalize_folder_pathclass TestNormalizeFolderPath:def test_unix_path(self):assert (normalize_folder_path("/home/user/projects/myapp")== "home/user/projects/myapp")def test_windows_path(self):result = normalize_folder_path("C:\\Users\\foo\\projects\\myapp")assert "\\" not in resultassert "Users" in result or "users" in result.lower()def test_trailing_slash_stripped(self):result = normalize_folder_path("/home/user/projects/")assert not result.endswith("/")def test_leading_slash_stripped(self):result = normalize_folder_path("/home/user/projects")assert not result.startswith("/")def test_double_slashes_collapsed(self):result = normalize_folder_path("/home//user///projects")assert "//" not in resultdef test_empty_string_raises(self):with pytest.raises(ValueError):normalize_folder_path("")def test_path_traversal_raises(self):with pytest.raises(ValueError):normalize_folder_path("/home/user/../../etc/passwd")def test_length_cap(self):long_path = "a/" * 300result = normalize_folder_path(long_path)assert len(result) <= 512def test_idempotent(self):path = "/home/user/projects/myapp"once = normalize_folder_path(path)twice = normalize_folder_path(once)assert once == twicedef test_relative_path(self):result = normalize_folder_path("projects/myapp/src")assert result == "projects/myapp/src"def test_windows_forward_slashes(self):result = normalize_folder_path("C:/Users/foo/projects")assert "\\" not in resultdef test_single_segment(self):result = normalize_folder_path("/workspace")assert result == "workspace"
12345678910111213141516171819202122232425261 unmodified line28293031323334353637383940414243444546474849505152535455565758591 unmodified line61626364656667689 unmodified lines78798081828384855 unmodified lines91929394959697"""Unit tests for observation lookup index, backfill, and index sync validation."""import sysimport osimport pytestimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))from db import StateKVimport functionsfrom functions import folder_observe, folder_search, forget, backfill_obs_lookup_if_needed, verify_index_sync_on_boot, KVdef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), 'test_obs_lookup.db')return StateKV(db_path=db_path)def base_payload(folder="/home/user/proj", agent="kiro", text="Test observation"):return {'folderPath': folder,'agentId': agent,'text': text,'timestamp': datetime.datetime.utcnow().isoformat() + 'Z',}1 unmodified linedef test_lookup_added_on_observe(self, tmp_path):kv = make_kv(tmp_path)res = folder_observe(kv, base_payload())obs_id = res['observationId']# Verify entry in KV.obs_lookuplookup = kv.get(KV.obs_lookup, obs_id)assert lookup is not Noneassert lookup['folderPath'] == 'home/user/proj'assert lookup['agentId'] == 'kiro'def test_lookup_deleted_on_forget(self, tmp_path):kv = make_kv(tmp_path)res = folder_observe(kv, base_payload())obs_id = res['observationId']# Confirm it existsassert kv.get(KV.obs_lookup, obs_id) is not None# Delete it using forgetforget(kv, {"folderPath": "/home/user/proj","agentId": "kiro","observationIds": [obs_id],})# Confirm it is gone from both storesassert kv.get(KV.obs_lookup, obs_id) is Noneassert kv.get(KV.folder_obs('home/user/proj', 'kiro'), obs_id) is Nonedef test_backfill_populates_missing_lookups(self, tmp_path):kv = make_kv(tmp_path)1 unmodified line# Ingest observationsres1 = folder_observe(kv, base_payload(text="First"))res2 = folder_observe(kv, base_payload(text="Second"))obs1 = res1['observationId']obs2 = res2['observationId']# Manually clear the lookup index (simulating legacy data)kv.delete(KV.obs_lookup, obs1)9 unmodified lineslookup2 = kv.get(KV.obs_lookup, obs2)assert lookup1 is not Noneassert lookup2 is not Noneassert lookup1['folderPath'] == 'home/user/proj'assert lookup2['folderPath'] == 'home/user/proj'def test_verify_index_sync_detects_mismatch(self, tmp_path):kv = make_kv(tmp_path)5 unmodified lines# Ingest one observationres = folder_observe(kv, base_payload())obs_id = res['observationId']# BM25 size should be 1assert functions._bm25_index.size == 112345678910111213141516171819202122232425262728293031321 unmodified line34353637383940414243444546474849505152535455565758596061626364656667681 unmodified line70717273747576779 unmodified lines87888990919293945 unmodified lines100101102103104105106"""Unit tests for observation lookup index, backfill, and index sync validation."""import sysimport osimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVimport functionsfrom functions import (folder_observe,forget,backfill_obs_lookup_if_needed,verify_index_sync_on_boot,KV,)def make_kv(tmp_path):db_path = os.path.join(str(tmp_path), "test_obs_lookup.db")return StateKV(db_path=db_path)def base_payload(folder="/home/user/proj", agent="kiro", text="Test observation"):return {"folderPath": folder,"agentId": agent,"text": text,"timestamp": datetime.datetime.utcnow().isoformat() + "Z",}1 unmodified linedef test_lookup_added_on_observe(self, tmp_path):kv = make_kv(tmp_path)res = folder_observe(kv, base_payload())obs_id = res["observationId"]# Verify entry in KV.obs_lookuplookup = kv.get(KV.obs_lookup, obs_id)assert lookup is not Noneassert lookup["folderPath"] == "home/user/proj"assert lookup["agentId"] == "kiro"def test_lookup_deleted_on_forget(self, tmp_path):kv = make_kv(tmp_path)res = folder_observe(kv, base_payload())obs_id = res["observationId"]# Confirm it existsassert kv.get(KV.obs_lookup, obs_id) is not None# Delete it using forgetforget(kv,{"folderPath": "/home/user/proj","agentId": "kiro","observationIds": [obs_id],},)# Confirm it is gone from both storesassert kv.get(KV.obs_lookup, obs_id) is Noneassert kv.get(KV.folder_obs("home/user/proj", "kiro"), obs_id) is Nonedef test_backfill_populates_missing_lookups(self, tmp_path):kv = make_kv(tmp_path)1 unmodified line# Ingest observationsres1 = folder_observe(kv, base_payload(text="First"))res2 = folder_observe(kv, base_payload(text="Second"))obs1 = res1["observationId"]obs2 = res2["observationId"]# Manually clear the lookup index (simulating legacy data)kv.delete(KV.obs_lookup, obs1)9 unmodified lineslookup2 = kv.get(KV.obs_lookup, obs2)assert lookup1 is not Noneassert lookup2 is not Noneassert lookup1["folderPath"] == "home/user/proj"assert lookup2["folderPath"] == "home/user/proj"def test_verify_index_sync_detects_mismatch(self, tmp_path):kv = make_kv(tmp_path)5 unmodified lines# Ingest one observationres = folder_observe(kv, base_payload())obs_id = res["observationId"]# BM25 size should be 1assert functions._bm25_index.size == 1
1234562 unmodified lines91011121314151 unmodified line17181920212228 unmodified lines51525354555620 unmodified lines77787980818236 unmodified lines11912012112212312436 unmodified lines16116216316416516618 unmodified lines185186187188189190"""C1.1 — Unit tests for observe(), strip_private_data(), and folder_observe()."""import sysimport osimport datetime2 unmodified linessys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVimport functionsfrom functions import observe, folder_observe, strip_private_data, KV1 unmodified line# Helpers# ---------------------------------------------------------------------------def make_kv(tmp_path):return StateKV(db_path=str(tmp_path / "test.db"))28 unmodified lines# observe() — valid payload# ---------------------------------------------------------------------------class TestObserveValid:def test_returns_observation_id(self, tmp_path):kv = make_kv(tmp_path)20 unmodified lines# observe() — missing required fields# ---------------------------------------------------------------------------class TestObserveMissingFields:def test_missing_session_id_raises(self, tmp_path):kv = make_kv(tmp_path)36 unmodified lines# strip_private_data() — redaction# ---------------------------------------------------------------------------class TestStripPrivateData:def test_redacts_api_key_assignment(self):text = "api_key = sk-proj-abc123LONGKEY456789012345678901234567890"36 unmodified lines# MAX_OBS_PER_SESSION cap# ---------------------------------------------------------------------------class TestObserveSessionCap:def test_cap_raises_on_fourth_observation(self, tmp_path, monkeypatch):monkeypatch.setenv("MAX_OBS_PER_SESSION", "3")18 unmodified lines# folder_observe() — valid payload / fobs_ prefix# ---------------------------------------------------------------------------class TestFolderObserveCore:def test_returns_observation_id(self, tmp_path):kv = make_kv(tmp_path)12345672 unmodified lines1011121314151 unmodified line1718192021222328 unmodified lines5253545556575820 unmodified lines7980818283848536 unmodified lines12212312412512612712836 unmodified lines16516616716816917017118 unmodified lines190191192193194195196"""C1.1 — Unit tests for observe(), strip_private_data(), and folder_observe()."""import sysimport osimport datetime2 unmodified linessys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import observe, folder_observe, strip_private_data, KV1 unmodified line# Helpers# ---------------------------------------------------------------------------def make_kv(tmp_path):return StateKV(db_path=str(tmp_path / "test.db"))28 unmodified lines# observe() — valid payload# ---------------------------------------------------------------------------class TestObserveValid:def test_returns_observation_id(self, tmp_path):kv = make_kv(tmp_path)20 unmodified lines# observe() — missing required fields# ---------------------------------------------------------------------------class TestObserveMissingFields:def test_missing_session_id_raises(self, tmp_path):kv = make_kv(tmp_path)36 unmodified lines# strip_private_data() — redaction# ---------------------------------------------------------------------------class TestStripPrivateData:def test_redacts_api_key_assignment(self):text = "api_key = sk-proj-abc123LONGKEY456789012345678901234567890"36 unmodified lines# MAX_OBS_PER_SESSION cap# ---------------------------------------------------------------------------class TestObserveSessionCap:def test_cap_raises_on_fourth_observation(self, tmp_path, monkeypatch):monkeypatch.setenv("MAX_OBS_PER_SESSION", "3")18 unmodified lines# folder_observe() — valid payload / fobs_ prefix# ---------------------------------------------------------------------------class TestFolderObserveCore:def test_returns_observation_id(self, tmp_path):kv = make_kv(tmp_path)
6 unmodified lines7891011126 unmodified lines192021222324252627282930316 unmodified lines38394041424332 unmodified lines7677787980816 unmodified lines8889909192939495969 unmodified lines1061071081091101112 unmodified lines1141151161171181191201211221238 unmodified lines1321331341351361372 unmodified lines1401411421431441451461471481491501511521531541551563 unmodified lines1601611621631641652 unmodified lines1681691701711721731741751761771781791801811821836 unmodified lines1901911921931941952 unmodified lines1981992002012022032042052062072082092102112122132145 unmodified lines2202212222232242252 unmodified lines22822923023123223323423523623713 unmodified lines2512522532542552562574 unmodified lines2622632642652662673 unmodified lines2712722732742752762772781 unmodified line2802812822832842852865 unmodified lines2922932942952962974 unmodified lines3023033043053063076 unmodified linesNote: Each property test creates a fresh isolated SQLite DB per hypothesisexample using a shared counter, avoiding state accumulation between examples."""import sysimport osimport datetime6 unmodified linestry:from hypothesis import given, settings, assume, HealthCheckfrom hypothesis import strategies as stHYPOTHESIS_AVAILABLE = Trueexcept ImportError:HYPOTHESIS_AVAILABLE = Falsepytestmark = pytest.mark.skipif(not HYPOTHESIS_AVAILABLE,reason="hypothesis not installed — run: pip install hypothesis")# ---------------------------------------------------------------------------6 unmodified linesdef _fresh_kv():"""Create a brand-new isolated StateKV in a temp directory."""from db import StateKVos.environ.pop("AGENTCACHE_SECRET", None)_counter[0] += 1d = tempfile.mkdtemp(prefix=f"agmem_prop_{_counter[0]}_")32 unmodified lines# Two distinct (folderPath, agentId) pairs never share observations.# ---------------------------------------------------------------------------@settings(max_examples=50, deadline=None)@given(path1=_safe_path(),6 unmodified linesassume((path1, agent1) != (path2, agent2))from functions import folder_observe, KVkv = _fresh_kv()folder_observe(kv, {"folderPath": path1, "agentId": agent1, "text": text, "timestamp": _now()})scope1 = KV.folder_obs(path1, agent1)scope2 = KV.folder_obs(path2, agent2)9 unmodified lines# meta.obsCount == len(kv.list(folder_obs_scope))# ---------------------------------------------------------------------------@settings(max_examples=50, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_2_obs_count_consistency(path, agent, texts):from functions import folder_observe, KVkv = _fresh_kv()for text in texts:folder_observe(kv, {"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()})meta_scope = KV.folder_meta(path, agent)meta = kv.get(meta_scope, "meta")8 unmodified lines# Every written pair has a KV.folders entry.# ---------------------------------------------------------------------------@settings(max_examples=50, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_3_index_coverage(path, agent, text):from functions import folder_observe, KVkv = _fresh_kv()folder_observe(kv, {"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()})index_entries = kv.list(KV.folders)normalized_path = path.replace("\\", "/").strip("/")normalized_agent = agent.strip()matching = [e for e in index_entriesif e.get("folderPath") == normalized_path and e.get("agentId") == normalized_agent]assert len(matching) >= 13 unmodified lines# No stored obs text contains raw secrets after folder_observe().# ---------------------------------------------------------------------------@settings(max_examples=30, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_4_privacy_invariant(path, agent, prefix):from functions import folder_observe, KVkv = _fresh_kv()secret_text = f"My api_key = sk-proj-{prefix}abc123def456ghi789jkl012 in production"folder_observe(kv, {"folderPath": path,"agentId": agent,"text": secret_text,"timestamp": _now(),})obs_list = kv.list(KV.folder_obs(path, agent))for obs in obs_list:6 unmodified lines# folder_timeline() always returns results sorted newest-first.# ---------------------------------------------------------------------------@settings(max_examples=40, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_5_timeline_ordering(path, agent, n):from functions import folder_observe, folder_timelinekv = _fresh_kv()base_ts = datetime.datetime(2025, 1, 1, 0, 0, 0)for i in range(n):ts = (base_ts + datetime.timedelta(minutes=i)).isoformat() + "Z"folder_observe(kv, {"folderPath": path,"agentId": agent,"text": f"Observation number {i}","timestamp": ts,})results = folder_timeline(kv, limit=100, folder_path=path, agent_id=agent)timestamps = [r["timestamp"] for r in results]5 unmodified lines# After forget({folderPath, agentId}), all three scopes are empty.# ---------------------------------------------------------------------------@settings(max_examples=40, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_6_forget_completeness(path, agent, texts):from functions import folder_observe, forget, KVkv = _fresh_kv()for text in texts:folder_observe(kv, {"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()})assert len(kv.list(KV.folder_obs(path, agent))) > 013 unmodified lines# Superseded memories have parentId; at least one memory is always latest.# ---------------------------------------------------------------------------@settings(max_examples=30, suppress_health_check=[HealthCheck.filter_too_much], deadline=None)@given(base_content=st.text(alphabet="abcdefghijklmnopqrstuvwxyz ",4 unmodified lines)def test_property_7_memory_version_uniqueness(base_content, n_variants):from functions import remember, KVkv = _fresh_kv()for i in range(n_variants):3 unmodified linesall_mems = kv.list(KV.memories)# Build sets for validationall_ids = {m["id"] for m in all_mems}superseded_ids = {m["id"] for m in all_mems if m.get("isLatest") is False}# Every superseded memory must be referenced by exactly one newer memory via parentIdfor m in all_mems:pid = m.get("parentId")1 unmodified line# The parentId must point to a memory that exists and is marked isLatest=Falseparent = next((x for x in all_mems if x["id"] == pid), None)assert parent is not None, f"parentId {pid} not found in memories"assert parent.get("isLatest") is False, "Parent of superseding memory must be isLatest=False"# At least one memory must be latestlatest_count = sum(1 for m in all_mems if m.get("isLatest") is True)5 unmodified lines# normalize(normalize(p)) == normalize(p) for all valid inputs.# ---------------------------------------------------------------------------@settings(max_examples=100, deadline=None)@given(path=st.text(4 unmodified lines)def test_property_8_path_normalization_idempotency(path):from functions import normalize_folder_pathtry:normalized_once = normalize_folder_path(path)normalized_twice = normalize_folder_path(normalized_once)6 unmodified lines789101112136 unmodified lines20212223242526272829303132336 unmodified lines4041424344454632 unmodified lines798081828384856 unmodified lines92939495969798991001011021039 unmodified lines1131141151161171181192 unmodified lines1221231241251261271281291301311321331341358 unmodified lines1441451461471481491502 unmodified lines1531541551561571581591601611621631641651661671681691701711721731743 unmodified lines1781791801811821831842 unmodified lines1871881891901911921931941951961971981992002012022032042052066 unmodified lines2132142152162172182192 unmodified lines2222232242252262272282292302312322332342352362372382392402412425 unmodified lines2482492502512522532542 unmodified lines25725825926026126226326426526626726826927013 unmodified lines2842852862872882892902912922934 unmodified lines2982993003013023033043 unmodified lines3083093103113123133143151 unmodified line3173183193203213223233243255 unmodified lines3313323333343353363374 unmodified lines3423433443453463473486 unmodified linesNote: Each property test creates a fresh isolated SQLite DB per hypothesisexample using a shared counter, avoiding state accumulation between examples."""import sysimport osimport datetime6 unmodified linestry:from hypothesis import given, settings, assume, HealthCheckfrom hypothesis import strategies as stHYPOTHESIS_AVAILABLE = Trueexcept ImportError:HYPOTHESIS_AVAILABLE = Falsepytestmark = pytest.mark.skipif(not HYPOTHESIS_AVAILABLE,reason="hypothesis not installed — run: pip install hypothesis",)# ---------------------------------------------------------------------------6 unmodified linesdef _fresh_kv():"""Create a brand-new isolated StateKV in a temp directory."""from db import StateKVos.environ.pop("AGENTCACHE_SECRET", None)_counter[0] += 1d = tempfile.mkdtemp(prefix=f"agmem_prop_{_counter[0]}_")32 unmodified lines# Two distinct (folderPath, agentId) pairs never share observations.# ---------------------------------------------------------------------------@settings(max_examples=50, deadline=None)@given(path1=_safe_path(),6 unmodified linesassume((path1, agent1) != (path2, agent2))from functions import folder_observe, KVkv = _fresh_kv()folder_observe(kv, {"folderPath": path1, "agentId": agent1, "text": text, "timestamp": _now()})scope1 = KV.folder_obs(path1, agent1)scope2 = KV.folder_obs(path2, agent2)9 unmodified lines# meta.obsCount == len(kv.list(folder_obs_scope))# ---------------------------------------------------------------------------@settings(max_examples=50, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_2_obs_count_consistency(path, agent, texts):from functions import folder_observe, KVkv = _fresh_kv()for text in texts:folder_observe(kv,{"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()},)meta_scope = KV.folder_meta(path, agent)meta = kv.get(meta_scope, "meta")8 unmodified lines# Every written pair has a KV.folders entry.# ---------------------------------------------------------------------------@settings(max_examples=50, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_3_index_coverage(path, agent, text):from functions import folder_observe, KVkv = _fresh_kv()folder_observe(kv, {"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()})index_entries = kv.list(KV.folders)normalized_path = path.replace("\\", "/").strip("/")normalized_agent = agent.strip()matching = [efor e in index_entriesif e.get("folderPath") == normalized_pathand e.get("agentId") == normalized_agent]assert len(matching) >= 13 unmodified lines# No stored obs text contains raw secrets after folder_observe().# ---------------------------------------------------------------------------@settings(max_examples=30, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_4_privacy_invariant(path, agent, prefix):from functions import folder_observe, KVkv = _fresh_kv()secret_text = f"My api_key = sk-proj-{prefix}abc123def456ghi789jkl012 in production"folder_observe(kv,{"folderPath": path,"agentId": agent,"text": secret_text,"timestamp": _now(),},)obs_list = kv.list(KV.folder_obs(path, agent))for obs in obs_list:6 unmodified lines# folder_timeline() always returns results sorted newest-first.# ---------------------------------------------------------------------------@settings(max_examples=40, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_5_timeline_ordering(path, agent, n):from functions import folder_observe, folder_timelinekv = _fresh_kv()base_ts = datetime.datetime(2025, 1, 1, 0, 0, 0)for i in range(n):ts = (base_ts + datetime.timedelta(minutes=i)).isoformat() + "Z"folder_observe(kv,{"folderPath": path,"agentId": agent,"text": f"Observation number {i}","timestamp": ts,},)results = folder_timeline(kv, limit=100, folder_path=path, agent_id=agent)timestamps = [r["timestamp"] for r in results]5 unmodified lines# After forget({folderPath, agentId}), all three scopes are empty.# ---------------------------------------------------------------------------@settings(max_examples=40, deadline=None)@given(path=_safe_path(),2 unmodified lines)def test_property_6_forget_completeness(path, agent, texts):from functions import folder_observe, forget, KVkv = _fresh_kv()for text in texts:folder_observe(kv,{"folderPath": path, "agentId": agent, "text": text, "timestamp": _now()},)assert len(kv.list(KV.folder_obs(path, agent))) > 013 unmodified lines# Superseded memories have parentId; at least one memory is always latest.# ---------------------------------------------------------------------------@settings(max_examples=30, suppress_health_check=[HealthCheck.filter_too_much], deadline=None)@given(base_content=st.text(alphabet="abcdefghijklmnopqrstuvwxyz ",4 unmodified lines)def test_property_7_memory_version_uniqueness(base_content, n_variants):from functions import remember, KVkv = _fresh_kv()for i in range(n_variants):3 unmodified linesall_mems = kv.list(KV.memories)# Build sets for validation{m["id"] for m in all_mems}{m["id"] for m in all_mems if m.get("isLatest") is False}# Every superseded memory must be referenced by exactly one newer memory via parentIdfor m in all_mems:pid = m.get("parentId")1 unmodified line# The parentId must point to a memory that exists and is marked isLatest=Falseparent = next((x for x in all_mems if x["id"] == pid), None)assert parent is not None, f"parentId {pid} not found in memories"assert parent.get("isLatest") is False, ("Parent of superseding memory must be isLatest=False")# At least one memory must be latestlatest_count = sum(1 for m in all_mems if m.get("isLatest") is True)5 unmodified lines# normalize(normalize(p)) == normalize(p) for all valid inputs.# ---------------------------------------------------------------------------@settings(max_examples=100, deadline=None)@given(path=st.text(4 unmodified lines)def test_property_8_path_normalization_idempotency(path):from functions import normalize_folder_pathtry:normalized_once = normalize_folder_path(path)normalized_twice = normalize_folder_path(normalized_once)
2 unmodified lines3456787 unmodified lines16171819202122236 unmodified lines3031323334353637383940414243444546474849505152535455561 unmodified line5859606162633 unmodified lines6768697071727374754 unmodified lines8081828384858687888990913 unmodified lines95969798991001011021031041051061077 unmodified lines11511611711811912012112212312412512612711 unmodified lines1391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681693 unmodified lines1731741751761771781791801814 unmodified lines1861871881891901912 unmodified linesTests for remember(), forget(), and jaccard_similarity()."""import sysimport osimport datetime7 unmodified lines# Helpers# ---------------------------------------------------------------------------def _make_kv(tmp_path):from db import StateKVos.environ.pop("AGENTCACHE_SECRET", None)return StateKV(db_path=str(tmp_path / "test.db"))6 unmodified lines# jaccard_similarity# ---------------------------------------------------------------------------class TestJaccardSimilarity:def test_identical_strings(self):from functions import jaccard_similarityassert jaccard_similarity("hello world foo", "hello world foo") == 1.0def test_completely_different(self):from functions import jaccard_similarityscore = jaccard_similarity("apple banana cherry", "xyz uvw qrs")assert score == 0.0def test_partial_overlap(self):from functions import jaccard_similarityscore = jaccard_similarity("authentication security token", "authentication bearer token")assert 0.0 < score < 1.0def test_empty_strings(self):from functions import jaccard_similarityassert jaccard_similarity("", "") == 1.0def test_high_similarity_above_threshold(self):from functions import jaccard_similarity# These two should meet or exceed the 0.7 threshold used in remember()a = "Use parameterised queries to prevent SQL injection in all database calls"b = "Use parameterised queries to prevent SQL injection in database operations"1 unmodified linedef test_low_similarity_below_threshold(self):from functions import jaccard_similaritya = "Configure Redis as the session cache backend"b = "Deploy the React frontend to Vercel using GitHub Actions CI"assert jaccard_similarity(a, b) < 0.73 unmodified lines# remember()# ---------------------------------------------------------------------------class TestRemember:def test_creates_memory_with_is_latest_true(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)result = remember(kv, {"content": "Always use type hints in Python functions"})assert result["success"] is True4 unmodified linesdef test_memory_has_required_fields(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)result = remember(kv, {"content": "Prefer composition over inheritance","type": "architecture","concepts": ["design", "patterns"],})mem = result["memory"]assert "id" in memassert "content" in mem3 unmodified linesdef test_supersedes_memory_with_high_jaccard_similarity(self, tmp_path):from functions import remember, KVkv = _make_kv(tmp_path)first = remember(kv, {"content": "Always use parameterised SQL queries to prevent injection attacks in every database call"})first_id = first["memory"]["id"]# Highly similar content — should supersede the firstsecond = remember(kv, {"content": "Always use parameterised SQL queries to prevent injection attacks in every database operation"})second_mem = second["memory"]# Old memory should be marked as not latest7 unmodified linesdef test_independent_memory_with_low_jaccard_similarity(self, tmp_path):from functions import remember, KVkv = _make_kv(tmp_path)first = remember(kv, {"content": "Configure Redis as the session cache backend for high throughput"})first_id = first["memory"]["id"]# Very different content — should be independentsecond = remember(kv, {"content": "Deploy the React frontend to Vercel using GitHub Actions continuous deployment"})second_mem = second["memory"]# Old memory should remain latest11 unmodified linesdef test_remember_raises_on_empty_content(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)with pytest.raises(ValueError, match="content is required"):remember(kv, {"content": ""})def test_remember_strips_private_data(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)result = remember(kv, {"content": "API key is sk-proj-abc123def456ghi789jkl012mno345pqr678 for production"})assert "sk-proj-" not in result["memory"]["content"]assert "[REDACTED" in result["memory"]["content"]def test_remember_with_project_scoping(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)# Two very similar memories for different projects should not supersede each otherfirst = remember(kv, {"content": "Always use parameterised queries in all database operations","project": "project-alpha",})second = remember(kv, {"content": "Always use parameterised queries in all database operations","project": "project-beta",})# Both should remain independent (different projects)assert first["memory"]["isLatest"] is Trueassert second["memory"]["isLatest"] is True3 unmodified lines# forget()# ---------------------------------------------------------------------------class TestForget:def test_forget_memory_by_id(self, tmp_path):from functions import remember, forget, KVkv = _make_kv(tmp_path)result = remember(kv, {"content": "This memory will be forgotten"})mem_id = result["memory"]["id"]4 unmodified linesdef test_forget_returns_zero_for_nonexistent_memory(self, tmp_path):from functions import forgetkv = _make_kv(tmp_path)result = forget(kv, {"memoryId": "mem_nonexistent_id"})# Should still succeed (memory was already gone) — deleted may be 0 or 12 unmodified lines34567897 unmodified lines171819202122232425266 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566671 unmodified line697071727374753 unmodified lines79808182838485868788894 unmodified lines9495969798991001011021031041051061071081093 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351367 unmodified lines14414514614714814915015115215315415515615715815916016116216316416516616711 unmodified lines1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202213 unmodified lines2252262272282292302312322332342354 unmodified lines2402412422432442452462 unmodified linesTests for remember(), forget(), and jaccard_similarity()."""import sysimport osimport datetime7 unmodified lines# Helpers# ---------------------------------------------------------------------------def _make_kv(tmp_path):from db import StateKVos.environ.pop("AGENTCACHE_SECRET", None)return StateKV(db_path=str(tmp_path / "test.db"))6 unmodified lines# jaccard_similarity# ---------------------------------------------------------------------------class TestJaccardSimilarity:def test_identical_strings(self):from functions import jaccard_similarityassert jaccard_similarity("hello world foo", "hello world foo") == 1.0def test_completely_different(self):from functions import jaccard_similarityscore = jaccard_similarity("apple banana cherry", "xyz uvw qrs")assert score == 0.0def test_partial_overlap(self):from functions import jaccard_similarityscore = jaccard_similarity("authentication security token", "authentication bearer token")assert 0.0 < score < 1.0def test_empty_strings(self):from functions import jaccard_similarityassert jaccard_similarity("", "") == 1.0def test_high_similarity_above_threshold(self):from functions import jaccard_similarity# These two should meet or exceed the 0.7 threshold used in remember()a = "Use parameterised queries to prevent SQL injection in all database calls"b = "Use parameterised queries to prevent SQL injection in database operations"1 unmodified linedef test_low_similarity_below_threshold(self):from functions import jaccard_similaritya = "Configure Redis as the session cache backend"b = "Deploy the React frontend to Vercel using GitHub Actions CI"assert jaccard_similarity(a, b) < 0.73 unmodified lines# remember()# ---------------------------------------------------------------------------class TestRemember:def test_creates_memory_with_is_latest_true(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)result = remember(kv, {"content": "Always use type hints in Python functions"})assert result["success"] is True4 unmodified linesdef test_memory_has_required_fields(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)result = remember(kv,{"content": "Prefer composition over inheritance","type": "architecture","concepts": ["design", "patterns"],},)mem = result["memory"]assert "id" in memassert "content" in mem3 unmodified linesdef test_supersedes_memory_with_high_jaccard_similarity(self, tmp_path):from functions import remember, KVkv = _make_kv(tmp_path)first = remember(kv,{"content": "Always use parameterised SQL queries to prevent injection attacks in every database call"},)first_id = first["memory"]["id"]# Highly similar content — should supersede the firstsecond = remember(kv,{"content": "Always use parameterised SQL queries to prevent injection attacks in every database operation"},)second_mem = second["memory"]# Old memory should be marked as not latest7 unmodified linesdef test_independent_memory_with_low_jaccard_similarity(self, tmp_path):from functions import remember, KVkv = _make_kv(tmp_path)first = remember(kv,{"content": "Configure Redis as the session cache backend for high throughput"},)first_id = first["memory"]["id"]# Very different content — should be independentsecond = remember(kv,{"content": "Deploy the React frontend to Vercel using GitHub Actions continuous deployment"},)second_mem = second["memory"]# Old memory should remain latest11 unmodified linesdef test_remember_raises_on_empty_content(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)with pytest.raises(ValueError, match="content is required"):remember(kv, {"content": ""})def test_remember_strips_private_data(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)result = remember(kv,{"content": "API key is sk-proj-abc123def456ghi789jkl012mno345pqr678 for production"},)assert "sk-proj-" not in result["memory"]["content"]assert "[REDACTED" in result["memory"]["content"]def test_remember_with_project_scoping(self, tmp_path):from functions import rememberkv = _make_kv(tmp_path)# Two very similar memories for different projects should not supersede each otherfirst = remember(kv,{"content": "Always use parameterised queries in all database operations","project": "project-alpha",},)second = remember(kv,{"content": "Always use parameterised queries in all database operations","project": "project-beta",},)# Both should remain independent (different projects)assert first["memory"]["isLatest"] is Trueassert second["memory"]["isLatest"] is True3 unmodified lines# forget()# ---------------------------------------------------------------------------class TestForget:def test_forget_memory_by_id(self, tmp_path):from functions import remember, forget, KVkv = _make_kv(tmp_path)result = remember(kv, {"content": "This memory will be forgotten"})mem_id = result["memory"]["id"]4 unmodified linesdef test_forget_returns_zero_for_nonexistent_memory(self, tmp_path):from functions import forgetkv = _make_kv(tmp_path)result = forget(kv, {"memoryId": "mem_nonexistent_id"})# Should still succeed (memory was already gone) — deleted may be 0 or 1
7 unmodified lines89101112139 unmodified lines23242526272813 unmodified lines42434445464722 unmodified lines70717273747514 unmodified lines90919293949539 unmodified lines13513613713813914017 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811824 unmodified lines18718818919019119219319419519619719819924 unmodified lines22422522622722822943 unmodified lines2732742752762772782792802812825 unmodified lines2882892902912922932942952962972982993003013023036 unmodified lines3103113123133143153163173183193203213223233243254 unmodified lines3303313323333343353363373383393406 unmodified lines3473483493503513523533543553563572 unmodified lines3603613623633643653663673683693703713728 unmodified lines38138238338438538624 unmodified lines4114124134144154164174184194204214228 unmodified lines43143243343443543621 unmodified lines45845946046146246346446513 unmodified lines4794804814824834844854864874884894904914924934944954962 unmodified lines4995005015025035045055065075085095105115125135145155165175185195205215225235247 unmodified lines53253353453553653714 unmodified lines5525535545555565577 unmodified linesTests use the Flask test client — no running server required.The AGENTCACHE_SECRET env var is NOT set so all auth checks pass through."""import sysimport osimport json9 unmodified lines# Fixtures# ---------------------------------------------------------------------------@pytest.fixture(scope="module")def flask_app(tmp_path_factory):"""13 unmodified linesos.environ.pop("AGENTMEMORY_SECRET", None)import app as app_moduleos.environ.pop("AGENTCACHE_SECRET", None)os.environ.pop("AGENTMEMORY_SECRET", None)from db import StateKV22 unmodified lines# Helper# ---------------------------------------------------------------------------def _now_iso() -> str:return datetime.datetime.utcnow().isoformat() + "Z"14 unmodified lines# GET /agentcache/config/flags# ===========================================================================class TestHealthBlueprint:def test_livez_no_auth_required(self, client):"""GET /livez must respond 200 without any auth token (always open)."""39 unmodified lines# GET /agentcache/folder/observations# ===========================================================================class TestObservationsBlueprint:def test_agent_observe_valid_payload(self, client):"""POST /agent/observe with valid payload returns 201 with observationId."""17 unmodified linesdef test_agent_observe_missing_agent_id_returns_400(self, client):"""POST /agent/observe missing agentId returns 400."""payload = {"folderPath": "/home/user/proj", "text": "some work", "timestamp": _now_iso()}resp = _post_json(client, "/agentcache/agent/observe", payload)assert resp.status_code == 400def test_agent_observe_missing_text_returns_400(self, client):"""POST /agent/observe missing text returns 400."""payload = {"folderPath": "/home/user/proj", "agentId": "kiro", "timestamp": _now_iso()}resp = _post_json(client, "/agentcache/agent/observe", payload)assert resp.status_code == 400def test_folders_list_returns_200(self, client):"""GET /folders returns 200 with a folders list."""# Seed at least one observation first_post_json(client, "/agentcache/agent/observe", {"folderPath": "/home/user/proj-folders-test","agentId": "kiro","text": "Folders test observation","timestamp": _now_iso(),})resp = client.get("/agentcache/folders")assert resp.status_code == 200data = resp.get_json()4 unmodified lines"""GET /folder/observations with valid params returns 200."""# Seed an observation firstfp = "/home/user/proj-obs-test"_post_json(client, "/agentcache/agent/observe", {"folderPath": fp,"agentId": "kiro","text": "Obs for folder/observations test","timestamp": _now_iso(),})resp = client.get("/agentcache/folder/observations?folderPath=home/user/proj-obs-test&agentId=kiro")assert resp.status_code == 200data = resp.get_json()assert "observations" in data24 unmodified lines# POST /agentcache/forget# ===========================================================================class TestMemoriesBlueprint:def test_remember_valid_payload(self, client):"""POST /remember with valid payload returns 201."""43 unmodified linesdef test_forget_memory_by_id(self, client):"""POST /forget with memoryId deletes a global memory."""# Create a memory firstcreate_resp = _post_json(client, "/agentcache/remember", {"content": "This memory will be forgotten","type": "fact",})mem_id = create_resp.get_json()["memory"]["id"]# Forget itresp = _post_json(client, "/agentcache/forget", {"memoryId": mem_id})5 unmodified lines"""POST /forget with folderPath+agentId clears folder observations."""# Seed an observationfp = "/home/user/proj-to-forget"_post_json(client, "/agentcache/agent/observe", {"folderPath": fp,"agentId": "kiro","text": "Some work that will be forgotten","timestamp": _now_iso(),})resp = _post_json(client, "/agentcache/forget", {"folderPath": fp,"agentId": "kiro",})assert resp.status_code == 200data = resp.get_json()assert "deleted" in data6 unmodified lines# POST /agentcache/timeline# ===========================================================================class TestSearchBlueprint:def test_search_with_query_returns_200(self, client):"""POST /search with a query returns 200."""# Seed something searchable first_post_json(client, "/agentcache/agent/observe", {"folderPath": "/home/user/proj-search-test","agentId": "kiro","text": "Implemented authentication middleware for the app","timestamp": _now_iso(),})resp = _post_json(client, "/agentcache/search", {"query": "authentication"})assert resp.status_code == 2004 unmodified linesdef test_search_with_folder_filter(self, client):"""POST /search with folderPath filter returns 200."""resp = _post_json(client, "/agentcache/search", {"query": "test","folderPath": "/home/user/proj-search-test","agentId": "kiro",})assert resp.status_code == 200def test_timeline_returns_200(self, client):6 unmodified linesdef test_timeline_with_filters_returns_200(self, client):"""POST /timeline with folder/agent filters returns 200."""resp = _post_json(client, "/agentcache/timeline", {"folderPath": "/home/user/proj-search-test","agentId": "kiro","limit": 10,})assert resp.status_code == 200def test_timeline_results_sorted_descending(self, client):2 unmodified lines# Seed observations with distinct timestampsfor i in range(3):ts = datetime.datetime(2025, 6, 1, 10, i, 0).isoformat() + "Z"_post_json(client, "/agentcache/agent/observe", {"folderPath": fp, "agentId": "kiro","text": f"Observation {i}", "timestamp": ts,})resp = _post_json(client, "/agentcache/timeline", {"folderPath": fp, "agentId": "kiro",})assert resp.status_code == 200data = resp.get_json()timestamps = [o["timestamp"] for o in data["observations"]]8 unmodified lines# POST /agentcache/graph/build# ===========================================================================class TestGraphBlueprint:def test_graph_returns_200(self, client):"""GET /graph returns 200 with nodes and edges."""24 unmodified linesdef test_graph_nodes_have_required_fields(self, client):"""Graph nodes contain id, label, folderPath, agentIds, obsCount, color (REQ-024)."""# Seed some data_post_json(client, "/agentcache/agent/observe", {"folderPath": "/home/user/proj-graph-check","agentId": "kiro","text": "Graph node field check","timestamp": _now_iso(),})resp = client.get("/agentcache/graph")data = resp.get_json()if data["nodes"]:8 unmodified lines# POST /agentcache/mcp/tools# ===========================================================================class TestMcpBlueprint:def test_mcp_tools_list_returns_200(self, client):"""GET /mcp/tools returns 200 with a tools list."""21 unmodified lines"cache_folder_observations","cache_timeline",}assert required_tools.issubset(tool_names), \f"Missing tools: {required_tools - tool_names}"def test_mcp_tool_call_agent_observe(self, client):"""POST /mcp/tools agent_observe returns 200."""13 unmodified linesdef test_mcp_tool_call_cache_recall(self, client):"""POST /mcp/tools cache_recall returns 200."""resp = _post_json(client, "/agentcache/mcp/tools", {"name": "cache_recall","arguments": {"query": "authentication"},})assert resp.status_code == 200def test_mcp_tool_call_cache_diagnose(self, client):"""POST /mcp/tools cache_diagnose returns folderCount etc."""resp = _post_json(client, "/agentcache/mcp/tools", {"name": "cache_diagnose","arguments": {},})assert resp.status_code == 200data = resp.get_json()result = json.loads(data["content"][0]["text"])2 unmodified linesdef test_mcp_tool_call_cache_folders(self, client):"""POST /mcp/tools cache_folders returns list."""resp = _post_json(client, "/agentcache/mcp/tools", {"name": "cache_folders","arguments": {},})assert resp.status_code == 200def test_mcp_tool_call_cache_timeline(self, client):"""POST /mcp/tools cache_timeline returns list."""resp = _post_json(client, "/agentcache/mcp/tools", {"name": "cache_timeline","arguments": {"limit": 10},})assert resp.status_code == 200def test_mcp_tool_unknown_name_returns_400(self, client):"""POST /mcp/tools with unknown tool name returns 400."""resp = _post_json(client, "/agentcache/mcp/tools", {"name": "nonexistent_tool_xyz","arguments": {},})assert resp.status_code == 400def test_mcp_tool_missing_name_returns_400(self, client):7 unmodified lines# POST /agentcache/migrate# ===========================================================================class TestMigrationBlueprint:def test_migrate_dry_run_returns_200(self, client):"""POST /migrate with dry_run=true returns 200 with counts."""14 unmodified lines# Blueprint registration completeness# ===========================================================================class TestBlueprintRegistration:def test_all_expected_endpoints_registered(self, flask_app):"""All 7 blueprints contribute at least one route each."""7 unmodified lines8910111213149 unmodified lines2425262728293013 unmodified lines4445464748495022 unmodified lines7374757677787914 unmodified lines94959697989910039 unmodified lines14014114214314414514617 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992004 unmodified lines20520620720820921021121221321421521621721821922022122222324 unmodified lines24824925025125225325443 unmodified lines2982993003013023033043053063073083093103115 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393406 unmodified lines3473483493503513523533543553563573583593603613623633643653663674 unmodified lines3723733743753763773783793803813823833843853866 unmodified lines3933943953963973983994004014024034044054064072 unmodified lines4104114124134144154164174184194204214224234244254264274284294304314324338 unmodified lines44244344444544644744824 unmodified lines4734744754764774784794804814824834844854864874888 unmodified lines49749849950050150250321 unmodified lines52552652752852953053153253313 unmodified lines5475485495505515525535545555565575585595605615625635645655665675685695705715722 unmodified lines5755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116127 unmodified lines62062162262362462562614 unmodified lines6416426436446456466477 unmodified linesTests use the Flask test client — no running server required.The AGENTCACHE_SECRET env var is NOT set so all auth checks pass through."""import sysimport osimport json9 unmodified lines# Fixtures# ---------------------------------------------------------------------------@pytest.fixture(scope="module")def flask_app(tmp_path_factory):"""13 unmodified linesos.environ.pop("AGENTMEMORY_SECRET", None)import app as app_moduleos.environ.pop("AGENTCACHE_SECRET", None)os.environ.pop("AGENTMEMORY_SECRET", None)from db import StateKV22 unmodified lines# Helper# ---------------------------------------------------------------------------def _now_iso() -> str:return datetime.datetime.utcnow().isoformat() + "Z"14 unmodified lines# GET /agentcache/config/flags# ===========================================================================class TestHealthBlueprint:def test_livez_no_auth_required(self, client):"""GET /livez must respond 200 without any auth token (always open)."""39 unmodified lines# GET /agentcache/folder/observations# ===========================================================================class TestObservationsBlueprint:def test_agent_observe_valid_payload(self, client):"""POST /agent/observe with valid payload returns 201 with observationId."""17 unmodified linesdef test_agent_observe_missing_agent_id_returns_400(self, client):"""POST /agent/observe missing agentId returns 400."""payload = {"folderPath": "/home/user/proj","text": "some work","timestamp": _now_iso(),}resp = _post_json(client, "/agentcache/agent/observe", payload)assert resp.status_code == 400def test_agent_observe_missing_text_returns_400(self, client):"""POST /agent/observe missing text returns 400."""payload = {"folderPath": "/home/user/proj","agentId": "kiro","timestamp": _now_iso(),}resp = _post_json(client, "/agentcache/agent/observe", payload)assert resp.status_code == 400def test_folders_list_returns_200(self, client):"""GET /folders returns 200 with a folders list."""# Seed at least one observation first_post_json(client,"/agentcache/agent/observe",{"folderPath": "/home/user/proj-folders-test","agentId": "kiro","text": "Folders test observation","timestamp": _now_iso(),},)resp = client.get("/agentcache/folders")assert resp.status_code == 200data = resp.get_json()4 unmodified lines"""GET /folder/observations with valid params returns 200."""# Seed an observation firstfp = "/home/user/proj-obs-test"_post_json(client,"/agentcache/agent/observe",{"folderPath": fp,"agentId": "kiro","text": "Obs for folder/observations test","timestamp": _now_iso(),},)resp = client.get("/agentcache/folder/observations?folderPath=home/user/proj-obs-test&agentId=kiro")assert resp.status_code == 200data = resp.get_json()assert "observations" in data24 unmodified lines# POST /agentcache/forget# ===========================================================================class TestMemoriesBlueprint:def test_remember_valid_payload(self, client):"""POST /remember with valid payload returns 201."""43 unmodified linesdef test_forget_memory_by_id(self, client):"""POST /forget with memoryId deletes a global memory."""# Create a memory firstcreate_resp = _post_json(client,"/agentcache/remember",{"content": "This memory will be forgotten","type": "fact",},)mem_id = create_resp.get_json()["memory"]["id"]# Forget itresp = _post_json(client, "/agentcache/forget", {"memoryId": mem_id})5 unmodified lines"""POST /forget with folderPath+agentId clears folder observations."""# Seed an observationfp = "/home/user/proj-to-forget"_post_json(client,"/agentcache/agent/observe",{"folderPath": fp,"agentId": "kiro","text": "Some work that will be forgotten","timestamp": _now_iso(),},)resp = _post_json(client,"/agentcache/forget",{"folderPath": fp,"agentId": "kiro",},)assert resp.status_code == 200data = resp.get_json()assert "deleted" in data6 unmodified lines# POST /agentcache/timeline# ===========================================================================class TestSearchBlueprint:def test_search_with_query_returns_200(self, client):"""POST /search with a query returns 200."""# Seed something searchable first_post_json(client,"/agentcache/agent/observe",{"folderPath": "/home/user/proj-search-test","agentId": "kiro","text": "Implemented authentication middleware for the app","timestamp": _now_iso(),},)resp = _post_json(client, "/agentcache/search", {"query": "authentication"})assert resp.status_code == 2004 unmodified linesdef test_search_with_folder_filter(self, client):"""POST /search with folderPath filter returns 200."""resp = _post_json(client,"/agentcache/search",{"query": "test","folderPath": "/home/user/proj-search-test","agentId": "kiro",},)assert resp.status_code == 200def test_timeline_returns_200(self, client):6 unmodified linesdef test_timeline_with_filters_returns_200(self, client):"""POST /timeline with folder/agent filters returns 200."""resp = _post_json(client,"/agentcache/timeline",{"folderPath": "/home/user/proj-search-test","agentId": "kiro","limit": 10,},)assert resp.status_code == 200def test_timeline_results_sorted_descending(self, client):2 unmodified lines# Seed observations with distinct timestampsfor i in range(3):ts = datetime.datetime(2025, 6, 1, 10, i, 0).isoformat() + "Z"_post_json(client,"/agentcache/agent/observe",{"folderPath": fp,"agentId": "kiro","text": f"Observation {i}","timestamp": ts,},)resp = _post_json(client,"/agentcache/timeline",{"folderPath": fp,"agentId": "kiro",},)assert resp.status_code == 200data = resp.get_json()timestamps = [o["timestamp"] for o in data["observations"]]8 unmodified lines# POST /agentcache/graph/build# ===========================================================================class TestGraphBlueprint:def test_graph_returns_200(self, client):"""GET /graph returns 200 with nodes and edges."""24 unmodified linesdef test_graph_nodes_have_required_fields(self, client):"""Graph nodes contain id, label, folderPath, agentIds, obsCount, color (REQ-024)."""# Seed some data_post_json(client,"/agentcache/agent/observe",{"folderPath": "/home/user/proj-graph-check","agentId": "kiro","text": "Graph node field check","timestamp": _now_iso(),},)resp = client.get("/agentcache/graph")data = resp.get_json()if data["nodes"]:8 unmodified lines# POST /agentcache/mcp/tools# ===========================================================================class TestMcpBlueprint:def test_mcp_tools_list_returns_200(self, client):"""GET /mcp/tools returns 200 with a tools list."""21 unmodified lines"cache_folder_observations","cache_timeline",}assert required_tools.issubset(tool_names), (f"Missing tools: {required_tools - tool_names}")def test_mcp_tool_call_agent_observe(self, client):"""POST /mcp/tools agent_observe returns 200."""13 unmodified linesdef test_mcp_tool_call_cache_recall(self, client):"""POST /mcp/tools cache_recall returns 200."""resp = _post_json(client,"/agentcache/mcp/tools",{"name": "cache_recall","arguments": {"query": "authentication"},},)assert resp.status_code == 200def test_mcp_tool_call_cache_diagnose(self, client):"""POST /mcp/tools cache_diagnose returns folderCount etc."""resp = _post_json(client,"/agentcache/mcp/tools",{"name": "cache_diagnose","arguments": {},},)assert resp.status_code == 200data = resp.get_json()result = json.loads(data["content"][0]["text"])2 unmodified linesdef test_mcp_tool_call_cache_folders(self, client):"""POST /mcp/tools cache_folders returns list."""resp = _post_json(client,"/agentcache/mcp/tools",{"name": "cache_folders","arguments": {},},)assert resp.status_code == 200def test_mcp_tool_call_cache_timeline(self, client):"""POST /mcp/tools cache_timeline returns list."""resp = _post_json(client,"/agentcache/mcp/tools",{"name": "cache_timeline","arguments": {"limit": 10},},)assert resp.status_code == 200def test_mcp_tool_unknown_name_returns_400(self, client):"""POST /mcp/tools with unknown tool name returns 400."""resp = _post_json(client,"/agentcache/mcp/tools",{"name": "nonexistent_tool_xyz","arguments": {},},)assert resp.status_code == 400def test_mcp_tool_missing_name_returns_400(self, client):7 unmodified lines# POST /agentcache/migrate# ===========================================================================class TestMigrationBlueprint:def test_migrate_dry_run_returns_200(self, client):"""POST /migrate with dry_run=true returns 200 with counts."""14 unmodified lines# Blueprint registration completeness# ===========================================================================class TestBlueprintRegistration:def test_all_expected_endpoints_registered(self, flask_app):"""All 7 blueprints contribute at least one route each."""
2 unmodified lines34567891011122 unmodified lines1516171819208 unmodified lines2930313233343 unmodified lines3839404142433 unmodified lines47484950515253545556575859603 unmodified lines646566676869707172737475767778798081828384854 unmodified lines9091929394952 unmodified lines98991001011021031 unmodified line1051061071081091102 unmodified lines1131141151161171183 unmodified lines1221231241251261277 unmodified lines1351361371381391401411421431 unmodified line1451461471481491502 unmodified lines1531541551561571586 unmodified lines16516616716816917033 unmodified lines2042052062072082093 unmodified lines2132142152162172182192202212222232242252262272282292302312 unmodified linesTests for SearchIndex, HybridSearch, and synonym expansion."""import sysimport osimport pytestsys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))2 unmodified lines# SearchIndex unit tests# ---------------------------------------------------------------------------class TestSearchIndex:def _make_obs(self, obs_id, title, narrative="", concepts=None, obs_type="other"):return {8 unmodified linesdef test_add_and_exact_match_returns_rank_one(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_001", "authentication middleware refactor")idx.add(obs)3 unmodified linesdef test_prefix_matching(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_002", "authentication token validation")idx.add(obs)3 unmodified linesdef test_synonym_expansion_db_conn(self):"""'db conn' should find document indexed with 'database connection'."""from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_003", "database connection pooling setup", "configure database connection pool")idx.add(obs)results = idx.search("db conn")assert any(r["obsId"] == "obs_003" for r in results)def test_remove_document(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_004", "deploy kubernetes service mesh")idx.add(obs)3 unmodified linesdef test_empty_index_returns_empty(self):from search import SearchIndexidx = SearchIndex()results = idx.search("anything")assert results == []def test_multiple_docs_rank_order(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("obs_a", "authentication login system", "user authentication flow"))idx.add(self._make_obs("obs_b", "database migration script", "run database migration"))idx.add(self._make_obs("obs_c", "deployment pipeline CI", "CI CD pipeline deployment"))results = idx.search("authentication")assert results[0]["obsId"] == "obs_a"def test_size_property(self):from search import SearchIndexidx = SearchIndex()assert idx.size == 0idx.add(self._make_obs("x1", "title one"))4 unmodified linesdef test_clear(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("x1", "something"))idx.clear()2 unmodified linesdef test_dirty_flag_set_on_add(self):from search import SearchIndexidx = SearchIndex()assert idx._dirty is Falseidx.add(self._make_obs("x1", "test dirty flag"))1 unmodified linedef test_dirty_flag_set_on_remove(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("x1", "test remove dirty"))idx._dirty = False # reset manually2 unmodified linesdef test_dirty_flag_reset_after_restore(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("x1", "test restore"))data = idx.serialize_data()3 unmodified linesdef test_has_method(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_has", "has method test")assert not idx.has("obs_has")7 unmodified lines# VectorIndex unit tests# ---------------------------------------------------------------------------class TestVectorIndex:def test_dirty_flag_on_add(self):from search import VectorIndexvi = VectorIndex()assert vi._dirty is Falsevi.add("v1", "sess", [0.1, 0.2, 0.3])1 unmodified linedef test_dirty_flag_on_remove(self):from search import VectorIndexvi = VectorIndex()vi.add("v1", "sess", [0.1, 0.2, 0.3])vi._dirty = False2 unmodified linesdef test_dirty_flag_reset_after_restore(self):from search import VectorIndexvi = VectorIndex()vi.add("v1", "sess", [0.1, 0.2, 0.3])data = vi.serialize_data()6 unmodified lines# HybridSearch in BM25-only mode# ---------------------------------------------------------------------------class TestHybridSearchBM25Only:def _make_obs(self, obs_id, title, narrative=""):return {33 unmodified linesdef test_hybrid_returns_empty_for_no_matches(self):from search import SearchIndex, VectorIndex, HybridSearchbm25 = SearchIndex()hybrid = HybridSearch(bm25, VectorIndex(), None, None)assert hybrid.search("zzznomatch", 10) == []3 unmodified lines# Serialization round-trip# ---------------------------------------------------------------------------class TestSearchIndexSerialization:def test_roundtrip_preserves_search_results(self):from search import SearchIndexidx = SearchIndex()idx.add({"id": "rt_001","sessionId": "sess_rt","title": "serialization round trip test","narrative": "verify that index survives serialize/restore","concepts": ["test"],"files": [],"type": "other",})data = idx.serialize_data()idx2 = SearchIndex()2 unmodified lines34567891011122 unmodified lines151617181920218 unmodified lines303132333435363 unmodified lines404142434445463 unmodified lines50515253545556575859606162636465666768693 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081094 unmodified lines1141151161171181191202 unmodified lines1231241251261271281291 unmodified line1311321331341351361372 unmodified lines1401411421431441451463 unmodified lines1501511521531541551567 unmodified lines1641651661671681691701711721731741 unmodified line1761771781791801811822 unmodified lines1851861871881891901916 unmodified lines19819920020120220320433 unmodified lines2382392402412422432443 unmodified lines2482492502512522532542552562572582592602612622632642652662672682692702 unmodified linesTests for SearchIndex, HybridSearch, and synonym expansion."""import sysimport ossys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))2 unmodified lines# SearchIndex unit tests# ---------------------------------------------------------------------------class TestSearchIndex:def _make_obs(self, obs_id, title, narrative="", concepts=None, obs_type="other"):return {8 unmodified linesdef test_add_and_exact_match_returns_rank_one(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_001", "authentication middleware refactor")idx.add(obs)3 unmodified linesdef test_prefix_matching(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_002", "authentication token validation")idx.add(obs)3 unmodified linesdef test_synonym_expansion_db_conn(self):"""'db conn' should find document indexed with 'database connection'."""from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_003","database connection pooling setup","configure database connection pool",)idx.add(obs)results = idx.search("db conn")assert any(r["obsId"] == "obs_003" for r in results)def test_remove_document(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_004", "deploy kubernetes service mesh")idx.add(obs)3 unmodified linesdef test_empty_index_returns_empty(self):from search import SearchIndexidx = SearchIndex()results = idx.search("anything")assert results == []def test_multiple_docs_rank_order(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("obs_a", "authentication login system", "user authentication flow"))idx.add(self._make_obs("obs_b", "database migration script", "run database migration"))idx.add(self._make_obs("obs_c", "deployment pipeline CI", "CI CD pipeline deployment"))results = idx.search("authentication")assert results[0]["obsId"] == "obs_a"def test_size_property(self):from search import SearchIndexidx = SearchIndex()assert idx.size == 0idx.add(self._make_obs("x1", "title one"))4 unmodified linesdef test_clear(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("x1", "something"))idx.clear()2 unmodified linesdef test_dirty_flag_set_on_add(self):from search import SearchIndexidx = SearchIndex()assert idx._dirty is Falseidx.add(self._make_obs("x1", "test dirty flag"))1 unmodified linedef test_dirty_flag_set_on_remove(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("x1", "test remove dirty"))idx._dirty = False # reset manually2 unmodified linesdef test_dirty_flag_reset_after_restore(self):from search import SearchIndexidx = SearchIndex()idx.add(self._make_obs("x1", "test restore"))data = idx.serialize_data()3 unmodified linesdef test_has_method(self):from search import SearchIndexidx = SearchIndex()obs = self._make_obs("obs_has", "has method test")assert not idx.has("obs_has")7 unmodified lines# VectorIndex unit tests# ---------------------------------------------------------------------------class TestVectorIndex:def test_dirty_flag_on_add(self):from search import VectorIndexvi = VectorIndex()assert vi._dirty is Falsevi.add("v1", "sess", [0.1, 0.2, 0.3])1 unmodified linedef test_dirty_flag_on_remove(self):from search import VectorIndexvi = VectorIndex()vi.add("v1", "sess", [0.1, 0.2, 0.3])vi._dirty = False2 unmodified linesdef test_dirty_flag_reset_after_restore(self):from search import VectorIndexvi = VectorIndex()vi.add("v1", "sess", [0.1, 0.2, 0.3])data = vi.serialize_data()6 unmodified lines# HybridSearch in BM25-only mode# ---------------------------------------------------------------------------class TestHybridSearchBM25Only:def _make_obs(self, obs_id, title, narrative=""):return {33 unmodified linesdef test_hybrid_returns_empty_for_no_matches(self):from search import SearchIndex, VectorIndex, HybridSearchbm25 = SearchIndex()hybrid = HybridSearch(bm25, VectorIndex(), None, None)assert hybrid.search("zzznomatch", 10) == []3 unmodified lines# Serialization round-trip# ---------------------------------------------------------------------------class TestSearchIndexSerialization:def test_roundtrip_preserves_search_results(self):from search import SearchIndexidx = SearchIndex()idx.add({"id": "rt_001","sessionId": "sess_rt","title": "serialization round trip test","narrative": "verify that index survives serialize/restore","concepts": ["test"],"files": [],"type": "other",})data = idx.serialize_data()idx2 = SearchIndex()
123456789101112131415161718192021222324252627282930313 unmodified lines3536373839404121 unmodified lines636465666768697071727374757677787980818283848586878889902 unmodified lines93949596"""Unit tests for folder_timeline (REQ-020, REQ-021, REQ-022, REQ-071)."""import sysimport osimport pytestimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))from db import StateKVfrom functions import folder_observe, folder_timelinedef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), 'test.db')return StateKV(db_path=db_path)def ts(offset_seconds=0):dt = datetime.datetime(2025, 1, 15, 10, 0, 0) + datetime.timedelta(seconds=offset_seconds)return dt.isoformat() + 'Z'def add_obs(kv, folder='/home/user/proj', agent='kiro', timestamp=None, text='obs'):return folder_observe(kv, {'folderPath': folder,'agentId': agent,'text': text,'timestamp': timestamp or ts(),})class TestTimelineOrdering:3 unmodified linesadd_obs(kv, timestamp=ts(60))add_obs(kv, timestamp=ts(30))results = folder_timeline(kv)timestamps = [r['timestamp'] for r in results]assert timestamps == sorted(timestamps, reverse=True)def test_empty_returns_empty(self, tmp_path):21 unmodified linesclass TestTimelineFilters:def test_folder_filter(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, folder='/home/user/proj-a', timestamp=ts(0))add_obs(kv, folder='/home/user/proj-b', timestamp=ts(1))results = folder_timeline(kv, folder_path='home/user/proj-a')assert all(r['folderPath'] == 'home/user/proj-a' for r in results)assert len(results) == 1def test_agent_filter(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, agent='kiro', timestamp=ts(0))add_obs(kv, agent='claude', timestamp=ts(1))results = folder_timeline(kv, agent_id='kiro')assert all(r['agentId'] == 'kiro' for r in results)def test_before_filter(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, timestamp=ts(0)) # 10:00:00add_obs(kv, timestamp=ts(60)) # 10:01:00add_obs(kv, timestamp=ts(120)) # 10:02:00results = folder_timeline(kv, before=ts(90))# Should only include obs before 10:01:30for r in results:assert r['timestamp'] < ts(90)def test_after_filter(self, tmp_path):kv = make_kv(tmp_path)2 unmodified linesadd_obs(kv, timestamp=ts(120))results = folder_timeline(kv, after=ts(30))for r in results:assert r['timestamp'] > ts(30)1234567891011121314151617181920212223242526272829303132333435363 unmodified lines4041424344454621 unmodified lines686970717273747576777879808182838485868788899091929394952 unmodified lines9899100101"""Unit tests for folder_timeline (REQ-020, REQ-021, REQ-022, REQ-071)."""import sysimport osimport datetimesys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))from db import StateKVfrom functions import folder_observe, folder_timelinedef make_kv(tmp_path):db_path = os.path.join(str(tmp_path), "test.db")return StateKV(db_path=db_path)def ts(offset_seconds=0):dt = datetime.datetime(2025, 1, 15, 10, 0, 0) + datetime.timedelta(seconds=offset_seconds)return dt.isoformat() + "Z"def add_obs(kv, folder="/home/user/proj", agent="kiro", timestamp=None, text="obs"):return folder_observe(kv,{"folderPath": folder,"agentId": agent,"text": text,"timestamp": timestamp or ts(),},)class TestTimelineOrdering:3 unmodified linesadd_obs(kv, timestamp=ts(60))add_obs(kv, timestamp=ts(30))results = folder_timeline(kv)timestamps = [r["timestamp"] for r in results]assert timestamps == sorted(timestamps, reverse=True)def test_empty_returns_empty(self, tmp_path):21 unmodified linesclass TestTimelineFilters:def test_folder_filter(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, folder="/home/user/proj-a", timestamp=ts(0))add_obs(kv, folder="/home/user/proj-b", timestamp=ts(1))results = folder_timeline(kv, folder_path="home/user/proj-a")assert all(r["folderPath"] == "home/user/proj-a" for r in results)assert len(results) == 1def test_agent_filter(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, agent="kiro", timestamp=ts(0))add_obs(kv, agent="claude", timestamp=ts(1))results = folder_timeline(kv, agent_id="kiro")assert all(r["agentId"] == "kiro" for r in results)def test_before_filter(self, tmp_path):kv = make_kv(tmp_path)add_obs(kv, timestamp=ts(0)) # 10:00:00add_obs(kv, timestamp=ts(60)) # 10:01:00add_obs(kv, timestamp=ts(120)) # 10:02:00results = folder_timeline(kv, before=ts(90))# Should only include obs before 10:01:30for r in results:assert r["timestamp"] < ts(90)def test_after_filter(self, tmp_path):kv = make_kv(tmp_path)2 unmodified linesadd_obs(kv, timestamp=ts(120))results = folder_timeline(kv, after=ts(30))for r in results:assert r["timestamp"] > ts(30)
.github/dependabot.yml+6-84
.github/workflows/automation.ymlAdded+128
.github/workflows/ci.ymlDeleted-59
.github/workflows/publish.ymlDeleted-124
INSTALL_FOR_AGENTS.md-18
automation.tmlAdded+39
hooks/powershell-hook.ps1Deleted-77
src/app.py+46-15
src/cache/__init__.py+35-12
src/cache/observe.py+1-5
src/cache/timeline.py+3-1
src/cli.py+70-13
src/connect.py+333-80
src/db.py+12-13
src/functions.py
src/import_data.py+24-20
src/mcp_stdio.py+47-16
src/replay_import.py+202-119
src/routes/graph.py+7-2
src/routes/health.py+25-13
src/routes/mcp.py+196-62
src/routes/memories.py+6
src/routes/migration.py+3
src/routes/observations.py+49-45
src/routes/search.py+10-2
src/search.py+174-80
src/storage/__init__.py+8-2
src/storage/images.py+6-2
src/storage/paths.py+2-6
src/viewer_helpers.py+22-19
src/workers.py+3-1
tests/test_api.py+76-37
tests/test_auth.py+3
tests/test_context.py+75-38
tests/test_debounce.py+19-18
tests/test_folder_graph_build.py+38-24
tests/test_folder_observe.py+44-43
tests/test_forget.py+54-44
tests/test_graph.py+45-42
tests/test_migration.py+69-47
tests/test_normalize.py+25-21
tests/test_obs_lookup.py+32-23
tests/test_observe_core.py+7-1
tests/test_properties.py+64-23
tests/test_remember.py+76-21
tests/test_route_regressions.py+169-79
tests/test_search.py+53-14
tests/test_timeline.py+30-25