Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.
TypeScript agent-memoryai-agentsanthropicclaude-codecursorgitknowledge-baseknowledge-graphllmmarkdownmcpmcp-servermodel-context-protocolnote-takingobsidianpkmragsecond-brainself-hostedzettelkasten
Launch readiness: write-time contradiction guards, first tests, reproducible releases (#4)
Ronalds Palacis18a0d7047c16
diff --git a/.env.example b/.env.exampleindex c9cb7db..c159d19 100644--- a/.env.example+++ b/.env.example@@ -50,3 +50,12 @@ ENGRAM_DATA_DIR="/data"# ENGRAM_STATE_DIR="/data/.engram" # override where token hashes persist (defaults to ENGRAM_DATA_DIR)# VAULT_DIR="/data" # fallback local vault (workspaces are normally connected in the UI)# AUTH_DISABLED="false" # single-user local mode: no Google auth, MCP open. NEVER true in production.+# ALLOWED_GITHUB_LOGINS="" # comma-separated GitHub usernames allowed to sign in (GitHub-only dashboard auth)+# VAULT_IGNORE="app,.git,node_modules,.next,.github,infra" # directory names never treated as vault content++# ── Escape hatches (env only — no Settings equivalent) ───────────────────────+# Reach for these if the app won't finish booting. Git sync runs off the startup path and+# serialises its subprocesses; if a vault still wedges the boot, disable sync, start clean,+# and reconnect the workspace.+# ENGRAM_DISABLE_GIT_SYNC="" # "1" to skip vault git sync entirely at boot+# ENGRAM_GIT_BOOT_DELAY_MS="" # ms to wait before the first sync (default 20000)diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 0000000..935269a--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,65 @@+name: Bug report+description: Something doesn't work the way it should+labels: ["bug"]+body:+ - type: markdown+ attributes:+ value: |+ Thanks for filing. Please don't paste real vault content, tokens, or secrets —+ redact anything private. Security issues go through+ [private reporting](https://github.com/rwnalds/engram/security/advisories/new) instead.++ - type: textarea+ id: what+ attributes:+ label: What happened?+ description: What you expected, and what you got instead.+ validations:+ required: true++ - type: textarea+ id: repro+ attributes:+ label: Steps to reproduce+ description: The tool call, the note's frontmatter, or the clicks that trigger it.+ placeholder: |+ 1. brain_write with path "..." and frontmatter "..."+ 2. brain_search for "..."+ 3. Expected the live note, got the superseded one+ validations:+ required: true++ - type: dropdown+ id: surface+ attributes:+ label: Where?+ multiple: true+ options:+ - MCP over HTTP (hosted dashboard)+ - MCP over stdio (local)+ - Dashboard UI+ - Curator / brain_capture+ - Deploy (Railway / Render / Docker)+ - Not sure+ validations:+ required: true++ - type: input+ id: client+ attributes:+ label: MCP client+ placeholder: Claude Code, Claude Desktop, Cursor, Cline, ...++ - type: input+ id: version+ attributes:+ label: Version+ description: Release tag, image tag, or commit SHA.+ placeholder: v0.1.0 / ghcr.io/rwnalds/engram:0.1.0 / main@abc1234++ - type: textarea+ id: logs+ attributes:+ label: Logs or error output+ description: Pasted here it's automatically formatted as code — no backticks needed.+ render: shelldiff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 0000000..5de59c6--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,5 @@+blank_issues_enabled: true+contact_links:+ - name: Security vulnerability+ url: https://github.com/rwnalds/engram/security/advisories/new+ about: Report privately — please don't open a public issue for a security problem.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 0000000..a9ca40f--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,48 @@+name: Feature request+description: Suggest something Engram should do+labels: ["enhancement"]+body:+ - type: markdown+ attributes:+ value: |+ Engram is opinionated about a small number of things — files are the source of truth,+ git is the database, and "still true" is written down at write time rather than inferred+ at read time. Proposals that fit that grain are much likelier to land.++ - type: textarea+ id: problem+ attributes:+ label: What problem are you hitting?+ description: The situation, not the solution. What did an agent get wrong, or what couldn't you do?+ validations:+ required: true++ - type: textarea+ id: proposal+ attributes:+ label: What would you like it to do?+ validations:+ required: true++ - type: dropdown+ id: area+ attributes:+ label: Area+ multiple: true+ options:+ - Search / ranking / authority+ - Write path (conflicts, supersession, validation)+ - Frontmatter schema+ - MCP tools+ - Dashboard UI+ - Auth / tokens+ - Deploy / self-hosting+ - Obsidian compatibility+ validations:+ required: true++ - type: textarea+ id: alternatives+ attributes:+ label: Anything you've tried, or prior art+ description: Existing tools, workarounds, or how another project solves it.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2e332ee..fca87ea 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -31,6 +31,11 @@ jobs:- name: Lintrun: bun run lint+ # Covers the ranking/authority math the product's central claim rests on:+ # a retired fact must stop surfacing. See lib/vault/stale-truth.test.ts.+ - name: Test+ run: bun test+# `next build` type-checks (tsc) and compiles every route — the real gate.- name: Buildrun: bun run builddiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..8f5b3ff--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,160 @@+name: Release++# Cut a release by pushing a tag: git tag v0.1.0 && git push origin v0.1.0+#+# Two images, deliberately. `engram` is the stdio MCP server (Dockerfile.mcp) — the official MCP+# registry entry io.github.rwnalds/engram declares that exact OCI reference in server.json, so+# repointing this tag at anything else breaks the registry listing. `engram-app` is the dashboard+# + HTTP MCP server (Dockerfile), which is what Railway and Render deploy.+#+# Before this workflow existed the ghcr images were pushed by hand, so they drifted from `main`+# with nothing to reproduce them.++on:+ push:+ tags: ["v*"]+ # Lets you re-run a release build without moving the tag.+ workflow_dispatch:+ inputs:+ tag:+ description: "Tag to build (e.g. v0.1.0)"+ required: true++permissions:+ contents: write+ packages: write++env:+ REGISTRY: ghcr.io++jobs:+ # The version lives in three hand-maintained places. If they disagree, server.json ends up+ # advertising an OCI reference that was never built — a 404 for anyone following the registry.+ verify-version:+ name: verify version matches the tag+ runs-on: ubuntu-latest+ outputs:+ version: ${{ steps.v.outputs.version }}+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ inputs.tag || github.ref }}++ - id: v+ name: Check package.json and server.json against the tag+ run: |+ set -euo pipefail+ RAW="${{ inputs.tag || github.ref_name }}"+ VERSION="${RAW#v}"+ PKG=$(jq -r .version package.json)+ SRV=$(jq -r .version server.json)+ OCI=$(jq -r '.packages[0].identifier' server.json)++ echo "tag=$VERSION package.json=$PKG server.json=$SRV"+ echo "server.json OCI identifier: $OCI"++ fail=0+ [ "$PKG" = "$VERSION" ] || { echo "::error::package.json version ($PKG) != tag ($VERSION)"; fail=1; }+ [ "$SRV" = "$VERSION" ] || { echo "::error::server.json version ($SRV) != tag ($VERSION)"; fail=1; }+ [ "$OCI" = "${{ env.REGISTRY }}/${{ github.repository }}:$VERSION" ] || {+ echo "::error::server.json packages[0].identifier ($OCI) does not point at ${{ env.REGISTRY }}/${{ github.repository }}:$VERSION"; fail=1; }+ [ "$fail" -eq 0 ] || exit 1++ echo "version=$VERSION" >> "$GITHUB_OUTPUT"++ # Same gate as CI. A tag that cannot build must not become a published image.+ verify-build:+ name: lint + test + build+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ inputs.tag || github.ref }}+ - uses: oven-sh/setup-bun@v2+ with:+ bun-version: latest+ - run: bun install --frozen-lockfile+ - run: bun run lint+ - run: bun test+ - run: bun run build+ env:+ NEXT_TELEMETRY_DISABLED: "1"++ images:+ name: ${{ matrix.name }}+ runs-on: ubuntu-latest+ needs: [verify-version, verify-build]+ strategy:+ fail-fast: false+ matrix:+ include:+ # The MCP registry's contract. Do not rename or repoint.+ - name: engram (stdio MCP)+ image: engram+ dockerfile: Dockerfile.mcp+ # What the Railway/Render deploy buttons pull.+ - name: engram-app (dashboard + HTTP MCP)+ image: engram-app+ dockerfile: Dockerfile+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ inputs.tag || github.ref }}++ - uses: docker/setup-qemu-action@v3+ - uses: docker/setup-buildx-action@v3++ - uses: docker/login-action@v3+ with:+ registry: ${{ env.REGISTRY }}+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ - name: Build and push (amd64 + arm64)+ uses: docker/build-push-action@v6+ with:+ context: .+ file: ${{ matrix.dockerfile }}+ platforms: linux/amd64,linux/arm64+ push: true+ tags: |+ ${{ env.REGISTRY }}/${{ github.repository_owner }}/${{ matrix.image }}:${{ needs.verify-version.outputs.version }}+ ${{ env.REGISTRY }}/${{ github.repository_owner }}/${{ matrix.image }}:latest+ cache-from: type=gha,scope=${{ matrix.image }}+ cache-to: type=gha,scope=${{ matrix.image }},mode=max++ - name: Show the published manifest+ run: |+ docker buildx imagetools inspect \+ ${{ env.REGISTRY }}/${{ github.repository_owner }}/${{ matrix.image }}:${{ needs.verify-version.outputs.version }}++ release:+ name: GitHub release+ runs-on: ubuntu-latest+ needs: [verify-version, images]+ if: startsWith(github.ref, 'refs/tags/')+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Create the release+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ VERSION: ${{ needs.verify-version.outputs.version }}+ run: |+ set -euo pipefail+ {+ echo "## Images"+ echo+ echo '```'+ echo "# stdio MCP server (Claude Desktop, Cursor, registries)"+ echo "docker pull ghcr.io/${{ github.repository_owner }}/engram:${VERSION}"+ echo+ echo "# dashboard + HTTP MCP server (self-hosted team)"+ echo "docker pull ghcr.io/${{ github.repository_owner }}/engram-app:${VERSION}"+ echo '```'+ echo+ echo "Both are multi-arch (linux/amd64, linux/arm64)."+ } > notes.md+ gh release create "v${VERSION}" --title "v${VERSION}" --notes-file notes.md --generate-notesdiff --git a/.gitignore b/.gitignoreindex c134a2a..51c6560 100644--- a/.gitignore+++ b/.gitignore@@ -15,6 +15,9 @@ next-env.d.ts.engram/**/.engram/.engram-data/+# scratch vault + app state built by `bun test` (see test/setup.ts)+.test-vault/+.test-data/sample-vault/.gitignore# local working notes (not part of the OSS repo)HANDOFF.mddiff --git a/.mailmap b/.mailmapnew file mode 100644index 0000000..35a6b08--- /dev/null+++ b/.mailmap@@ -0,0 +1,4 @@+# Collapse the three identities this repo was authored under into one.+# Affects `git shortlog`, `git log`, and GitHub's blame/history views.+Ronalds Palacis <[email protected]> <[email protected]>+Ronalds Palacis <[email protected]> <[email protected]>diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e3cbbad..9fb5aa1 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -22,7 +22,7 @@ Point it at your own vault: `VAULT_DIR=/path/to/vault bun dev`.- base-ui primitives have **no `asChild`**.- Next 16 route handlers: `params` is a **Promise** (`const { path } = await params`).- **Files are the source of truth** — there is no database. The vault is markdown; app state- (tokens, workspaces, settings) lives under `CORTEX_DATA_DIR`/`ENGRAM_DATA_DIR`, never inside a vault.+ (tokens, workspaces, settings) lives under `ENGRAM_DATA_DIR`, never inside a vault.- The MCP layer exposes **only** vault tools — never repo/workspace/GitHub internals.- Match the surrounding code's naming, comment density, and idiom.@@ -31,7 +31,7 @@ Point it at your own vault: `VAULT_DIR=/path/to/vault bun dev`.1. `bun run lint` and `bun run build` both pass (CI runs these on every PR).2. **Verify in the running app**, not just in theory — drive the actual flow you changed.3. Update docs (`README.md`, `DEPLOY.md`, `.env.example`) if you changed behavior or config.-4. Never commit secrets, tokens, or real vault content. `.cortex-data` / `.engram-data` are gitignored.+4. Never commit secrets, tokens, or real vault content. `.engram-data` is gitignored.## Scopediff --git a/DEPLOY.md b/DEPLOY.mdindex 51cca1b..7a1d760 100644--- a/DEPLOY.md+++ b/DEPLOY.md@@ -4,15 +4,12 @@ Engram deploys as one container (this repo). Vault repos are **connected in the(Workspaces) — no repo lives in this repo, and no laptop keeps a vault copy. The activeworkspace is what the dashboard shows and what agents read/write.-## 1. Push this repo to GitHub-Already a git repo — create a remote and push `main`.--## 2. Dashboard login — Google OAuth+## 1. Dashboard login — Google OAuth1. Google Cloud Console → Credentials → Create OAuth client ID → Web application.2. Redirect URI: `https://<your-app>.up.railway.app/api/auth/callback`3. Copy the Client ID + Secret.-## 3. Railway+## 2. Railway1. **New Project → Deploy from GitHub repo** → this repo (builds via root `Dockerfile`).2. **Add a Volume**, mount path `/data`.3. **Variables** — only these five are required on the host; the rest are optional and@@ -24,7 +21,7 @@ Already a git repo — create a remote and push `main`.| `AUTH_SECRET` | `openssl rand -base64 32`, or Railway "Generate" || `APP_URL` | `https://<your-app>.up.railway.app` || `ALLOWED_EMAILS` | comma-separated team emails (Google login) |-| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | from step 2 |+| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | from step 1 |Deploy, then sign in with Google. These five bootstrap **auth + infra** — they gate loginitself (or say where state lives), so they can't live behind the login and must be env.@@ -42,12 +39,12 @@ Note `ARCHIVE_FOLDERS` (default `archive,archives,_archive,trash`): notes in thedemoted in search and excluded from agent results by default — how you retire a note withoutdeleting it.-## 4. Connect a vault repo (in the dashboard → Workspaces)+## 3. Connect a vault repo (in the dashboard → Workspaces)Two ways — pick one:- **URL + token (zero setup):** paste the repo URL + a GitHub token with access. Works withno GitHub OAuth app — the simplest path, especially for self-hosting.-- **Connect GitHub (nicer):** if you set the GitHub OAuth app in step 5, click *Connect GitHub*+- **Connect GitHub (nicer):** if you set the GitHub OAuth app in step 4, click *Connect GitHub*and pick a repo from a list.Add repos, switch the active one, remove — all in the UI. MCP tokens (per teammate/agent) are@@ -55,7 +52,7 @@ created on the **Connect** page, each **`read` or `write`** scope. A read-only tcall the write tools — give one to an agent you don't want mutating the vault. Every write isrecorded in the git log with which token or human caused it.-## 5. (Optional) GitHub OAuth app — for the "Connect GitHub" flow+## 4. (Optional) GitHub OAuth app — for the "Connect GitHub" flowEach deployment uses **its own** GitHub OAuth app (secrets can't be shared, and the callback ishost-specific — so there's no shared central app for self-hosters):1. GitHub → Settings → Developer settings → **OAuth Apps → New OAuth App**.@@ -63,9 +60,9 @@ host-specific — so there's no shared central app for self-hosters):3. Paste the Client ID / Secret into the dashboard **Settings → GitHub** (or set`GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` in Railway — the Settings value wins).-Skip this entirely if you use the URL + token path in step 4.+Skip this entirely if you use the URL + token path in step 3.-## 6. Connect agents to the MCP+## 5. Connect agents to the MCPDashboard → **Connect** → copy the command. Agents always hit the same endpoint and only eversee the **active** vault:```bashdiff --git a/README.md b/README.mdindex 3a0942b..afb0e11 100644--- a/README.md+++ b/README.md@@ -36,7 +36,10 @@ powers full-text search + a wikilink **knowledge graph**.[](https://railway.com/deploy/engram?referralCode=PEidIe&utm_medium=integration&utm_source=template&utm_campaign=generic)[](https://render.com/deploy?repo=https://github.com/rwnalds/engram)++[](https://github.com/rwnalds/engram/actions/workflows/ci.yml)[](./LICENSE)+[](https://github.com/rwnalds/engram/pkgs/container/engram)> **Opinionated about _how_ it stores memory** — git-backed markdown, no database, agents write (not> just read), self-hosted. **Unopinionated about _what_ you keep in it** — any markdown vault, any folder@@ -45,6 +48,12 @@ powers full-text search + a wikilink **knowledge graph**.---+**[What it's for](#what-its-for)** · **[How it compares](#how-it-compares)** · **[Features](#features)** ·+**[Works with](#works-with)** · **[Quick start](#quick-start)** · **[MCP tools](#mcp-tools)** ·+**[Deploy](#deploy)** · **[FAQ](#faq)** · **[Contributing](#contributing)**++---+## What it's for- **Shared memory for a team running multiple agents** — one vault, many agents reading and writing@@ -56,6 +65,40 @@ powers full-text search + a wikilink **knowledge graph**.- **Memory you can see, not a black box** — a dashboard to search, watch (with diffs), and curate what your agents remember.- **Markdown RAG without the vector database** — full-text search + a link graph over human-readable files.+## How it compares++Most agent memory is built to answer *"what did I store about this?"* Engram is built to answer+*"what is still true about this?"* — a different question, and the one that bites when an agent+quotes a price you retired months ago.++| | **Engram** | Vector-store memory<br><sub>(mem0, Zep, …)</sub> | Markdown memory<br><sub>(Basic Memory, …)</sub> | Plain RAG over docs |+|---|---|---|---|---|+| **Storage** | markdown files, git is the database | embeddings in a vector DB | markdown files | embeddings in a vector DB |+| **Ranking** | relevance **× authority** | similarity | relevance | similarity |+| **Knows a fact is retired** | ✅ `superseded_by` + `valid_until`, enforced at search | — | — | — |+| **Explains what it withheld** | ✅ `excluded[]` with a reason per note | — | — | — |+| **Retire + replace atomically** | ✅ `brain_supersede`, one commit | — | — | — |+| **Refuses contradicting writes** | ✅ at write time, not read time | — | — | n/a (read-only) |+| **Audit trail** | ✅ git, per-write attribution, per-file diffs | varies | git, if you commit | — |+| **Per-agent access control** | ✅ read / write token scopes | varies | — | — |+| **Human UI** | ✅ dashboard, search, diffs, graph | varies | — | — |+| **Runs on** | your box, one container | mostly hosted SaaS | your box | your box |++The row that matters is the third one. Similarity search cannot tell a contradiction from a+duplicate — a retired price and a live one are textually identical, so the retired one often+*outranks* the live one by being longer and more detailed. That can't be fixed at read time, which+is why Engram writes the retirement down when it happens.++<p align="center">+ <img src="assets/screenshot-note.png" alt="Engram dashboard showing a note marked locked, superseding an earlier pricing note, with backlinks" width="900" />+</p>++<p align="center"><sub>This exact pair ships in <code>sample-vault/</code>. Run <code>bun dev</code>, search <code>acme price</code>,+and watch the retired note get withheld with a reason.</sub></p>++<sub>Categories, not feature-by-feature audits of specific products, and accurate to the best of my+knowledge as of July 2026. If something here misrepresents a tool you maintain, open a PR — I'll fix it.</sub>+## Features- **MCP server** — 15 `brain_*` tools over one bearer-authenticated HTTP endpoint (`POST /api/mcp`,@@ -74,6 +117,12 @@ powers full-text search + a wikilink **knowledge graph**.**`brain_supersede`** retires the old fact and links the new one in a single commit, so add-and-retirecan't drift apart. This is the difference between an agent that *remembers* and one that knows what's**still true**.+- **Write-time contradiction guards** — authority ranking fixes *reading*; these stop the vault+ accepting the contradiction in the first place. Engram refuses to create a second live note on a+ subject a live note already covers (the `acme-pricing-2026.md`-beside-`acme-pricing.md` bug) and+ points the agent at `brain_supersede` instead; refuses to overwrite a note the caller hasn't read;+ and warns when a `status:` isn't a word the ranking model knows, so a typo can't silently strip a+ note's authority.- **Audit trail + access control** — every write is attributed in **git** to the token or human thatmade it, with expandable **per-file diffs** in the activity feed. Give an agent a **read-only token**and it never even sees the write tools; a **write** token can create, edit, move, and archive.@@ -189,6 +238,13 @@ default** (even if it's `locked`). Or set **`valid_until: 2026-12-31`** on a notRetired matches don't vanish silently: `brain_search` returns them in an **`excluded`** list with areason (`"expired 2026-06-01"`), so the agent can say *what it ignored and why* instead of quoting it.+**What stops an agent just adding a second, contradicting note?**+Engram refuses the write. Told "the price is now X", an agent that can't overwrite a note it never+read will happily *add* `acme-pricing-2026.md` next to `acme-pricing.md` — nothing is corrupted, and+you now have two live notes disagreeing about one number. That write is rejected with a pointer to+`brain_supersede`, which retires the old note and adds the new one in a single commit. Pass+`allow_conflict: true` when both notes genuinely belong.+**How do I know what an agent changed?**Every write is committed to git attributed to the token or human behind it, and the dashboard'sactivity feed shows per-file diffs — a built-in audit trail for autonomous agents.@@ -217,6 +273,22 @@ full history.**Where does it run / is it self-hosted?**You host it. One Docker container on Railway / Render / Fly / any VM with a volume. Your keys, your data.+## Contributing++Issues and PRs welcome — especially where the validity model breaks against a vault shaped+differently from mine.++- **[CONTRIBUTING.md](./CONTRIBUTING.md)** — setup, conventions, and the pre-PR checklist.+- **[docs/curator.md](./docs/curator.md)** — how the optional Curator agent loop works.+- **[SECURITY.md](./SECURITY.md)** — please report vulnerabilities privately, not as an issue.++```bash+bun install && bun dev+bun test # the ranking/authority suite, incl. the stale-truth fixtures+```++If Engram is useful to you, **starring the repo** genuinely helps other people find it.+## StackNext.js 16 (App Router) · React 19 · TypeScript · Tailwind v4 · shadcn/ui · bun · MiniSearch ·diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..cf1ba3a--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,52 @@+# Security Policy++## Reporting a vulnerability++**Please do not open a public issue for a security problem.**++Report it privately through GitHub's [private vulnerability reporting](https://github.com/rwnalds/engram/security/advisories/new)+(Security → Report a vulnerability). That opens a private thread with the maintainers.++Please include what you can: what you found, how to reproduce it, and what an attacker gets out+of it. A rough report sent early beats a polished one sent late.++You can expect an initial response within **72 hours**, and an assessment within **7 days**. If a+fix is warranted you'll be credited in the release notes unless you'd rather not be.++## Supported versions++Engram is pre-1.0 and moves fast. Only the **latest release** and `main` receive fixes. If you're+self-hosting an older image, upgrading is the fix.++## What this project handles++Engram is self-hosted and holds credentials, so it's worth being specific about the surface:++- **Dashboard auth** — Google OAuth, with a session cookie signed by `AUTH_SECRET`, gated on an+ email allowlist (`ALLOWED_EMAILS`) or GitHub login allowlist (`ALLOWED_GITHUB_LOGINS`).+- **MCP auth** — per-agent bearer tokens, stored as SHA-256 hashes and shown in plaintext once.+ Each carries a `read` or `write` scope; a read-only token never sees the write tools.+- **OAuth 2.0 server** — Dynamic Client Registration + PKCE, so Claude.ai can connect as a custom+ connector. Served whenever `AUTH_SECRET` is set.+- **GitHub tokens** — used to clone and push vault repos. Encrypted at rest, keyed off `AUTH_SECRET`.+- **Vault content** — your notes. When the Curator is enabled, note content is sent to the+ Anthropic API. It is off by default.++### Things that are intended behaviour, not vulnerabilities++- **An instance with no `AUTH_SECRET` and no tokens is open.** That's local dev mode, and the+ README and DEPLOY.md both say so. Deploying it to a public URL that way is a misconfiguration.+- **`AUTH_DISABLED=true` disables dashboard auth.** Documented, and labelled never-in-production.+- **A `write`-scoped token can write anywhere in the vault.** Scopes are read/write, not+ per-folder. If you need narrower isolation, run a separate instance against a separate vault.+- **`brain_delete` deletes a note.** It's recoverable from git history, and the tool description+ steers toward archiving instead.++## Hardening a deployment++- Set `AUTH_SECRET` to a real random value (`openssl rand -base64 32`).+- Set `ALLOWED_EMAILS` (or `ALLOWED_GITHUB_LOGINS`) — an empty allowlist is not a filter.+- Give every agent its own token, scoped `read` unless it genuinely needs to write, and revoke+ tokens you no longer recognise on the Connect page.+- Keep `ENGRAM_DATA_DIR` on a volume you control; it holds token hashes and encrypted git tokens.+- Leave the Curator off unless you intend note content to reach the Anthropic API.diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.tsindex fd5b1c9..36ea7c5 100644--- a/app/api/mcp/route.ts+++ b/app/api/mcp/route.ts@@ -3,7 +3,7 @@ import { harnessEnabled } from "@/lib/settings";import { hasAnyToken, resolveToken, type TokenScope } from "@/lib/tokens";import { oauthEnabled, verifyAccessToken, wwwAuthenticate } from "@/lib/oauth";import { withActor } from "@/lib/actor";-import { TOOLS, TOOL_MAP } from "@/lib/mcp/tools";+import { TOOL_MAP, visibleTools } from "@/lib/mcp/tools";export const dynamic = "force-dynamic";@@ -42,14 +42,7 @@ async function handleMessage(msg: Json, caller: Caller): Promise<Json | null> {case "ping":return rpc(id, {});case "tools/list": {- // A read-only token never sees the write tools — it cannot be tempted to call them,- // and the model never wastes a turn discovering it is forbidden.- // The auto-filing harness stays hidden unless it's turned on (agents file notes themselves).- const tools = TOOLS.filter((t) => {- if (t.name === "brain_capture" && !harnessEnabled()) return false;- if (t.write && caller.scope !== "write") return false;- return true;- });+ const tools = visibleTools(caller.scope === "write", harnessEnabled());return rpc(id, {tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),});diff --git a/assets/screenshot-note.png b/assets/screenshot-note.pngnew file mode 100644index 0000000..ff36e58Binary files /dev/null and b/assets/screenshot-note.png differdiff --git a/bunfig.toml b/bunfig.tomlnew file mode 100644index 0000000..e5bfa37--- /dev/null+++ b/bunfig.toml@@ -0,0 +1,4 @@+[test]+# Pins VAULT_DIR/ENGRAM_DATA_DIR before any module imports lib/config.ts, which reads them at+# import time. Without this the suite passes or fails depending on test-file order.+preload = ["./test/setup.ts"]diff --git a/docs/curator.md b/docs/curator.mdindex 20b00bb..651a954 100644--- a/docs/curator.md+++ b/docs/curator.md@@ -16,7 +16,7 @@ any token with `write` scope, in every Curator mode, including `off`.| Scope | Sees | Can ||---|---|---|| `read` | 8 tools | search, read, list, tree, backlinks, graph, recent, schema |-| `write` | 14 tools | everything above, plus create, edit, append, move, delete |+| `write` | 15 tools | everything above, plus write, edit, append, move, supersede, create-folder, delete (`brain_capture` makes 16 when the Curator is `full`) |A read-only token never *sees* the write tools in `tools/list`, so the model is never tempted andnever wastes a turn discovering it is forbidden. Calling one anyway returns a clear error.diff --git a/lib/agent.ts b/lib/agent.tsindex d0086b2..6c7eec3 100644--- a/lib/agent.ts+++ b/lib/agent.ts@@ -2,8 +2,8 @@ import Anthropic from "@anthropic-ai/sdk";import { DEFAULT_CURATOR_MODEL, SUPPORTED_MODEL_IDS } from "@/lib/models";import { anthropicApiKey } from "@/lib/settings";import { TOOLS, type Tool } from "@/lib/mcp/tools";-import { getNote, readVaultFile, vaultConventions } from "@/lib/vault/store";-import { normalizeNotePath } from "@/lib/vault/write";+import { readVaultFile, vaultConventions } from "@/lib/vault/store";+import { normalizeNotePath, guardOverwrite } from "@/lib/vault/write";import { withActor } from "@/lib/actor";/**@@ -109,25 +109,6 @@ const MUTATION_KIND: Record<string, keyof Manifest> = {brain_move: "moved",};-function noteExists(p: string): boolean {- try {- return getNote(normalizeNotePath(String(p))) !== null;- } catch {- return false;- }-}--/**- * Structural read-before-overwrite. Not a size heuristic like the one in write.ts — this refuses- * the write outright until the loop has actually opened the note, so a same-size clobber is- * caught too. Returns an error message for the model, or null to proceed.- */-export function guardOverwrite(toolName: string, target: string, readPaths: ReadonlySet<string>): string | null {- if (toolName !== "brain_write" && toolName !== "brain_edit") return null;- if (!target || !noteExists(target) || readPaths.has(target)) return null;- return `${target} already exists and you have not read it in this session. Call brain_read("${target}") first, then write back the full content you intend to keep — or use brain_append to add to it.`;-}-export interface AgentOpts {profile: AgentProfile;/** chat: the conversation. capture: a single user turn holding the rough dump. */@@ -184,7 +165,7 @@ export async function* agentStream(opts: AgentOpts): AsyncGenerator<AgentEvent>const target = typeof input.path === "string" ? normalizeNotePath(input.path) : "";- const blocked = guardOverwrite(name, target, readPaths);+ const blocked = guardOverwrite(name, target, (p) => readPaths.has(p));if (blocked) return { error: blocked };const out = await withActor(opts.actor ?? "curator", () => tool.handler(input));diff --git a/lib/mcp/session.ts b/lib/mcp/session.tsnew file mode 100644index 0000000..2ad4c80--- /dev/null+++ b/lib/mcp/session.ts@@ -0,0 +1,57 @@+import { currentActor } from "@/lib/actor";++/**+ * What each caller has read recently, so the write path can enforce read-before-overwrite.+ *+ * The Curator loop gets this for free — it's one process with one `readPaths` set per run. MCP has+ * no session: every `tools/call` is an independent HTTP POST, so "have you read this note?" has+ * nowhere to live. This is that missing session, keyed by the authenticated caller's name and aged+ * out on a sliding window. It is a safety interlock, not state the protocol depends on — losing it+ * costs one extra brain_read, which is exactly the behaviour we want anyway.+ *+ * Deliberately in-memory: a restart forgetting that an agent read a note is the safe direction to+ * fail, and it keeps a single-binary deploy free of another store.+ */++/** How long a read counts for. Long enough for a multi-step task, short enough that a stale read doesn't authorise a clobber an hour later. */+const TTL_MS = 30 * 60 * 1000;+/** Cap per actor, so a long-lived token that reads thousands of notes can't grow without bound. */+const MAX_PATHS = 500;++const reads = new Map<string, Map<string, number>>();++function bucket(actor: string): Map<string, number> {+ let b = reads.get(actor);+ if (!b) {+ b = new Map();+ reads.set(actor, b);+ }+ return b;+}++/** Drop expired entries, then the oldest ones if the bucket is still over cap. */+function prune(b: Map<string, number>, now: number): void {+ for (const [p, at] of b) if (now - at > TTL_MS) b.delete(p);+ if (b.size <= MAX_PATHS) return;+ const oldestFirst = [...b].sort((x, y) => x[1] - y[1]);+ for (let i = 0; i < oldestFirst.length - MAX_PATHS; i++) b.delete(oldestFirst[i][0]);+}++export function recordRead(relPath: string, now: number = Date.now()): void {+ if (!relPath) return;+ const b = bucket(currentActor());+ b.set(relPath, now);+ prune(b, now);+}++export function hasRead(relPath: string, now: number = Date.now()): boolean {+ const b = reads.get(currentActor());+ if (!b) return false;+ const at = b.get(relPath);+ return at != null && now - at <= TTL_MS;+}++/** Test seam. */+export function resetSessions(): void {+ reads.clear();+}diff --git a/lib/mcp/tools.test.ts b/lib/mcp/tools.test.tsnew file mode 100644index 0000000..f4b6468--- /dev/null+++ b/lib/mcp/tools.test.ts@@ -0,0 +1,90 @@+import { describe, expect, test } from "bun:test";+import { TOOLS, TOOL_MAP, visibleTools } from "./tools";++/**+ * The access-control claim, pinned.+ *+ * "A read-only token never even sees the write tools" is asserted in the README, DEPLOY.md and+ * docs/curator.md. It is the reason a teammate's agent can be handed a token safely. Until now+ * nothing verified it, so adding a tool and forgetting `write: true` would quietly hand every+ * read-only caller a mutation primitive.+ */++const MUTATORS = [+ "brain_write",+ "brain_edit",+ "brain_append",+ "brain_move",+ "brain_create_folder",+ "brain_supersede",+ "brain_capture",+ "brain_delete",+];++describe("write flags", () => {+ test("every known mutating tool is marked write: true", () => {+ for (const name of MUTATORS) {+ expect(TOOL_MAP.get(name)?.write).toBe(true);+ }+ });++ test("no tool named like a mutation is missing its write flag", () => {+ // Catches a new tool added without `write: true` — the failure mode that would silently+ // expose a mutation to read-only callers.+ const suspicious = TOOLS.filter(+ (t) => /write|edit|append|move|delete|create|supersede|capture|rename/i.test(t.name) && !t.write,+ );+ expect(suspicious.map((t) => t.name)).toEqual([]);+ });+});++describe("visibleTools", () => {+ test("a read-only caller sees no write tool at all", () => {+ const names = visibleTools(false, true).map((t) => t.name);+ for (const m of MUTATORS) expect(names).not.toContain(m);+ });++ test("a read-only caller still gets the full read surface", () => {+ const names = visibleTools(false, true).map((t) => t.name);+ for (const r of ["brain_schema", "brain_search", "brain_read", "brain_list", "brain_backlinks", "brain_graph"]) {+ expect(names).toContain(r);+ }+ });++ test("a write caller sees the write tools", () => {+ const names = visibleTools(true, true).map((t) => t.name);+ expect(names).toContain("brain_write");+ expect(names).toContain("brain_supersede");+ });++ test("brain_capture is hidden unless the harness is on, for either scope", () => {+ expect(visibleTools(true, false).map((t) => t.name)).not.toContain("brain_capture");+ expect(visibleTools(false, false).map((t) => t.name)).not.toContain("brain_capture");+ expect(visibleTools(true, true).map((t) => t.name)).toContain("brain_capture");+ });++ test("read-only visibility is a strict subset of write visibility", () => {+ const write = new Set(visibleTools(true, true).map((t) => t.name));+ const read = visibleTools(false, true).map((t) => t.name);+ expect(read.length).toBeLessThan(write.size);+ for (const n of read) expect(write.has(n)).toBe(true);+ });+});++describe("tool surface", () => {+ test("every tool has a name, a description and an input schema", () => {+ for (const t of TOOLS) {+ expect(t.name).toMatch(/^brain_/);+ expect(t.description.length).toBeGreaterThan(0);+ expect(t.inputSchema).toBeTruthy();+ }+ });++ test("tool names are unique", () => {+ expect(TOOL_MAP.size).toBe(TOOLS.length);+ });++ test("brain_write advertises the supersede path — the guard's error is only half the lesson", () => {+ expect(TOOL_MAP.get("brain_write")?.description).toContain("brain_supersede");+ });+});diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex 83be6a2..bc7b554 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -9,17 +9,20 @@ import {searchNotes,vaultConventions,} from "@/lib/vault/store";-import { effectiveAuthority } from "@/lib/vault/authority";+import { effectiveAuthority, isUnrecognizedStatus, knownStatusWords } from "@/lib/vault/authority";import { extractSection, listHeadings } from "@/lib/vault/parse";import {appendNote,createFolder,deleteNote,+ guardOverwrite,moveNote,+ normalizeNotePath,supersedeNote,writeNote,writeNoteRaw,} from "@/lib/vault/write";+import { hasRead, recordRead } from "./session";// eslint-disable-next-line @typescript-eslint/no-explicit-anytype Args = Record<string, any>;@@ -52,7 +55,8 @@ async function writeFromArgs(a: Args): Promise<string> {const raw = contentStr.trim() !== "" ? contentStr : !hasFm && bodyStr.trim().startsWith("---") ? bodyStr : "";// strict: an agent that hand-writes unparseable YAML is refused, not silently accepted.// allowShrink: only when the caller explicitly says it means to replace the note.- const opts = { strict: true, allowShrink: a.overwrite === true };+ // allowConflict: only when the caller says a near-duplicate note is deliberate.+ const opts = { strict: true, allowShrink: a.overwrite === true, allowConflict: a.allow_conflict === true };if (raw.trim() !== "") return writeNoteRaw(p, raw, opts);if (bodyStr.trim() !== "" || hasFm) return writeNote(p, bodyStr, fm, opts);throw new Error(@@ -61,11 +65,16 @@ async function writeFromArgs(a: Args): Promise<string> {}/**- * Report a write, warning loudly when the note's YAML did not survive the round-trip.- * Unparseable frontmatter is silently discarded on read, so a note claiming `status: locked`- * would rank as an ordinary note forever. The agent that wrote it should hear about it now.+ * Report a write, warning loudly when the note's frontmatter will not do what the writer meant.+ * Both failures here are silent on read: unparseable YAML is discarded wholesale, and an+ * unrecognised `status:` falls through to `current`. Either way a note claiming to be the source+ * of truth ranks as an ordinary one. The agent that wrote it should hear about it now.*/-async function writeResult(a: Args) {+async function writeResult(a: Args, toolName: string) {+ // Read-before-overwrite. The Curator loop has enforced this for a while; over MCP a coding agent+ // could still clobber a note it had never opened, protected only by the size heuristic in write.ts.+ const blocked = guardOverwrite(toolName, a.path ? normalizeNotePath(String(a.path)) : "", hasRead);+ if (blocked) throw new Error(blocked);const p = await writeFromArgs(a);const n = getNote(p);if (n?.frontmatterError) {@@ -75,6 +84,13 @@ async function writeResult(a: Args) {warning: `Frontmatter was written but cannot be parsed (${n.frontmatterError}). Its status, tags and title are being ignored. Usual cause: an unquoted ":" in a value — quote it, e.g. title: "Decision: X". Re-write the note to fix.`,};}+ if (isUnrecognizedStatus(n?.status)) {+ return {+ ok: true,+ path: p,+ warning: `status: "${n?.status}" is not a status this vault's ranking model recognises, so the note is being treated as plain \`current\`. If you meant it to outrank or be outranked by others, use one of: ${knownStatusWords().join(", ")}. Check for a typo.`,+ };+ }return { ok: true, path: p };}@@ -151,7 +167,12 @@ export const TOOLS: Tool[] = [}: {}),};- if (!section) return { ...base, content: n.raw };+ // Only a full read authorises a later overwrite. A section read shows you one heading, not+ // what you would destroy — so it deliberately does not unlock brain_write/brain_edit.+ if (!section) {+ recordRead(n.path);+ return { ...base, content: n.raw };+ }const found = extractSection(n.body, String(section));if (found === null) {@@ -221,7 +242,8 @@ export const TOOLS: Tool[] = [name: "brain_write",write: true,description:- "Create or overwrite a note. PREFER `body` (markdown, no frontmatter) + `frontmatter` (an object): the YAML is serialised for you and always parses. Hand-writing frontmatter into `content` risks invalid YAML — a note whose frontmatter fails to parse loses its status, tags and title on every read, so a note claiming `status: locked` would rank as an ordinary one. Such a write is REJECTED. Follow SCHEMA.md: kebab-case path, dated names for daily/decisions, frontmatter with title/type/tags/status. Path vault-relative (e.g. decisions/foo-2026-07-09.md).",+ "Create or overwrite a note. PREFER `body` (markdown, no frontmatter) + `frontmatter` (an object): the YAML is serialised for you and always parses. Hand-writing frontmatter into `content` risks invalid YAML — a note whose frontmatter fails to parse loses its status, tags and title on every read, so a note claiming `status: locked` would rank as an ordinary one. Such a write is REJECTED. Follow SCHEMA.md: kebab-case path, dated names for daily/decisions, frontmatter with title/type/tags/status. Path vault-relative (e.g. decisions/foo-2026-07-09.md).\n\n" ++ "WHEN A FACT CHANGED, DON'T CREATE A DATED SIBLING. Writing `acme-pricing-2026.md` next to a live `acme-pricing.md` leaves two live notes disagreeing about one number, and the older one usually matches the query better — this is exactly how a retired price gets quoted. Such a write is REJECTED; use brain_supersede instead, which retires the old note and adds the new one in a single commit. `allow_conflict: true` overrides it when both notes genuinely belong.",inputSchema: {type: "object",properties: {@@ -230,10 +252,11 @@ export const TOOLS: Tool[] = [frontmatter: { type: "object", description: "YAML frontmatter object: title, type, tags, status, related, ..." },content: s("full raw markdown incl. frontmatter — alternative to body+frontmatter"),overwrite: { type: "boolean", description: "confirm you mean to replace an existing note with much shorter content (default false)" },+ allow_conflict: { type: "boolean", description: "confirm a near-duplicate of a live note is deliberate — prefer brain_supersede (default false)" },},required: ["path"],},- handler: async (a) => await writeResult(a),+ handler: async (a) => await writeResult(a, "brain_write"),},{name: "brain_edit",@@ -248,10 +271,11 @@ export const TOOLS: Tool[] = [body: s("markdown body (alternative to content; pair with `frontmatter`)"),frontmatter: { type: "object", description: "YAML frontmatter object (with `body`)" },overwrite: { type: "boolean", description: "confirm you mean to replace an existing note with much shorter content (default false)" },+ allow_conflict: { type: "boolean", description: "confirm a near-duplicate of a live note is deliberate — prefer brain_supersede (default false)" },},required: ["path"],},- handler: async (a) => await writeResult(a),+ handler: async (a) => await writeResult(a, "brain_edit"),},{name: "brain_append",@@ -335,3 +359,21 @@ export const TOOLS: Tool[] = [];export const TOOL_MAP = new Map(TOOLS.map((t) => [t.name, t]));++/**+ * The tools a caller may see, given its scope.+ *+ * A read-only token never sees the write tools — it cannot be tempted to call them, and the model+ * never wastes a turn discovering it is forbidden. This is a claim the README, DEPLOY.md and+ * docs/curator.md all make out loud, so it lives here as one function the route calls and the+ * tests can pin, rather than as a filter expression inline in a request handler.+ *+ * The auto-filing harness stays hidden unless it's turned on — agents file notes themselves.+ */+export function visibleTools(canWrite: boolean, harnessOn: boolean): Tool[] {+ return TOOLS.filter((t) => {+ if (t.name === "brain_capture" && !harnessOn) return false;+ if (t.write && !canWrite) return false;+ return true;+ });+}diff --git a/lib/vault/authority.test.ts b/lib/vault/authority.test.tsnew file mode 100644index 0000000..6040506--- /dev/null+++ b/lib/vault/authority.test.ts@@ -0,0 +1,141 @@+import { describe, expect, test } from "bun:test";+import {+ authorityOf,+ effectiveAuthority,+ isUnrecognizedStatus,+ overlayValidity,+ weightOf,+ type Authority,+} from "./authority";++const DAY = 24 * 60 * 60 * 1000;+const NOW = Date.UTC(2026, 6, 20); // 2026-07-20++describe("authorityOf", () => {+ test("a note with no status is current — a vault using no conventions ranks purely by relevance", () => {+ expect(authorityOf({ path: "clients/acme.md" })).toBe("current");+ });++ test("classifies each status vocabulary", () => {+ expect(authorityOf({ path: "a.md", status: "locked" })).toBe("authoritative");+ expect(authorityOf({ path: "a.md", status: "canonical" })).toBe("authoritative");+ expect(authorityOf({ path: "a.md", status: "superseded" })).toBe("superseded");+ expect(authorityOf({ path: "a.md", status: "retired" })).toBe("superseded");+ expect(authorityOf({ path: "a.md", status: "draft" })).toBe("provisional");+ expect(authorityOf({ path: "a.md", status: "proposed" })).toBe("provisional");+ });++ test("status words are matched in tags too", () => {+ expect(authorityOf({ path: "a.md", tags: ["pricing", "locked"] })).toBe("authoritative");+ });++ test("matches whole tokens inside compound values, not substrings", () => {+ expect(authorityOf({ path: "a.md", status: "draft-for-approval" })).toBe("provisional");+ // "wip" must not match inside "wiped"+ expect(authorityOf({ path: "a.md", status: "wiped" })).toBe("current");+ });++ test("folder beats frontmatter — a locked note in archive/ is still archived", () => {+ expect(authorityOf({ path: "archive/old-pricing.md", status: "locked" })).toBe("archived");+ });++ test("superseded beats authoritative — dead however loudly it calls itself canonical", () => {+ expect(authorityOf({ path: "a.md", status: "canonical", tags: ["superseded"] })).toBe("superseded");+ });+});++describe("weightOf", () => {+ test("orders the classes so authority can outrank relevance", () => {+ const order: Authority[] = ["authoritative", "current", "provisional", "superseded", "archived"];+ const weights = order.map(weightOf);+ for (let i = 1; i < weights.length; i++) expect(weights[i]).toBeLessThan(weights[i - 1]);+ });++ test("authoritative outweighs current by enough to flip a close match", () => {+ expect(weightOf("authoritative")).toBeGreaterThan(weightOf("current") * 2);+ });+});++describe("overlayValidity", () => {+ test("a live note passes through untouched", () => {+ expect(overlayValidity("current", null, null, NOW)).toEqual({ authority: "current", retired: false });+ });++ test("an explicit superseded_by retires the note and names its replacement", () => {+ const r = overlayValidity("current", null, "price-live", NOW);+ expect(r.retired).toBe(true);+ expect(r.authority).toBe("superseded");+ expect(r.reason).toBe("superseded by price-live");+ });++ test("an expired valid_until retires the note and dates it", () => {+ const r = overlayValidity("current", NOW - DAY, null, NOW);+ expect(r.retired).toBe(true);+ expect(r.authority).toBe("superseded");+ expect(r.reason).toContain("expired");+ });++ test("a valid_until in the future does not retire", () => {+ expect(overlayValidity("current", NOW + DAY, null, NOW).retired).toBe(false);+ });++ test("a blessing does not outlive its expiry — locked-but-stale is still retired", () => {+ // The hole this closes: `authoritative` is a static 3.5x forever, so without the overlay a+ // stale canonical doc outranks a fresh working note indefinitely.+ const r = overlayValidity("authoritative", NOW - DAY, null, NOW);+ expect(r.authority).toBe("superseded");+ expect(r.retired).toBe(true);+ });++ test("archived wins over everything and is reported as archived, not superseded", () => {+ const r = overlayValidity("archived", NOW - DAY, "something", NOW);+ expect(r.authority).toBe("archived");+ expect(r.reason).toBe("archived");+ });++ test("explicit supersession is reported ahead of expiry when both apply", () => {+ const r = overlayValidity("current", NOW - DAY, "price-live", NOW);+ expect(r.reason).toBe("superseded by price-live");+ });+});++describe("effectiveAuthority", () => {+ test("combines text classification with temporal validity in one call", () => {+ const r = effectiveAuthority(+ { path: "pricing/acme.md", status: "locked", validUntil: NOW - DAY },+ NOW,+ );+ expect(r.authority).toBe("superseded");+ expect(r.retired).toBe(true);+ });+});++describe("isUnrecognizedStatus", () => {+ test("no status is not a mistake", () => {+ expect(isUnrecognizedStatus(undefined)).toBe(false);+ expect(isUnrecognizedStatus("")).toBe(false);+ expect(isUnrecognizedStatus(" ")).toBe(false);+ });++ test("accepts every word the ranking model acts on", () => {+ for (const s of ["locked", "canonical", "superseded", "retired", "draft", "proposed"]) {+ expect(isUnrecognizedStatus(s)).toBe(false);+ }+ });++ test("accepts common neutral statuses a vault is entitled to use", () => {+ for (const s of ["active", "current", "done", "in-progress", "published"]) {+ expect(isUnrecognizedStatus(s)).toBe(false);+ }+ });++ test("flags the silent-failure case: a typo that falls through to `current`", () => {+ expect(isUnrecognizedStatus("lokced")).toBe(true);+ expect(isUnrecognizedStatus("supersded")).toBe(true);+ });++ test("is case-insensitive and tolerates compound values", () => {+ expect(isUnrecognizedStatus("LOCKED")).toBe(false);+ expect(isUnrecognizedStatus("draft-for-approval")).toBe(false);+ });+});diff --git a/lib/vault/authority.ts b/lib/vault/authority.tsindex 23041de..330d260 100644--- a/lib/vault/authority.ts+++ b/lib/vault/authority.ts@@ -11,11 +11,37 @@ import { ARCHIVE_FOLDERS } from "@/lib/config";export type Authority = "authoritative" | "current" | "provisional" | "superseded" | "archived";/** Status/tag words that mark a note as the source of truth for whatever it covers. */-const AUTHORITATIVE = ["locked", "canonical", "source-of-truth", "authoritative"];+export const AUTHORITATIVE = ["locked", "canonical", "source-of-truth", "authoritative"];/** Words that mark a note as no longer true. */-const SUPERSEDED = ["superseded", "deprecated", "obsolete", "replaced", "retired", "dead"];+export const SUPERSEDED = ["superseded", "deprecated", "obsolete", "replaced", "retired", "dead"];/** Words that mark a note as not yet decided. A `proposed` decision is not a decision. */-const PROVISIONAL = ["draft", "proposed", "exploring", "tentative", "wip", "idea"];+export const PROVISIONAL = ["draft", "proposed", "exploring", "tentative", "wip", "idea"];++/**+ * Words that carry no authority but are common, legitimate `status:` values. Listing them keeps+ * the typo check quiet about statuses a vault is entitled to use — `active` means `current`, and+ * saying so is not a mistake.+ */+export const NEUTRAL_STATUS = ["current", "active", "live", "done", "complete", "completed", "open", "in-progress", "ongoing", "published"];++/** Every status word the ranking model recognises or tolerates. */+export function knownStatusWords(): string[] {+ return [...AUTHORITATIVE, ...SUPERSEDED, ...PROVISIONAL, ...NEUTRAL_STATUS];+}++/**+ * True when `status:` contains no word the ranking model recognises.+ *+ * A typo here fails silently and expensively: `status: lokced` matches nothing, so the note falls+ * through to `current` and a document meant to be the source of truth ranks as an ordinary one —+ * the exact failure the authority model exists to prevent, reintroduced by a transposition. There+ * is no correct list of statuses for every vault, so this warns rather than refuses.+ */+export function isUnrecognizedStatus(status: string | undefined): boolean {+ const v = (status ?? "").trim().toLowerCase();+ if (v === "") return false;+ return !knownStatusWords().some((w) => hasWord(v, w));+}/** Multiplier applied to a note's search score. Files are truth; this only reorders hits. */const WEIGHT: Record<Authority, number> = {diff --git a/lib/vault/conflict.ts b/lib/vault/conflict.tsnew file mode 100644index 0000000..f8101f4--- /dev/null+++ b/lib/vault/conflict.ts@@ -0,0 +1,112 @@+import { listNotes } from "./store";+import { overlayValidity, authorityOf } from "./authority";+import { stemOf } from "./parse";+import type { NoteMeta } from "./types";++/**+ * Refuse to create a second note asserting a fact an existing live note already asserts.+ *+ * The failure this exists for: an agent is told "our price is now X". It cannot overwrite a note+ * it never read, so it does the agreeable thing and *adds* one — `clients/acme-pricing-2026.md`+ * next to `clients/acme-pricing.md`. Nothing is corrupted, no guard trips, and the vault now holds+ * two live notes disagreeing about one number. Authority ranking cannot save this: both are+ * `current`, both match "price", and the older one is often the wordier and better-matching of the+ * two. The contradiction has to be refused at write time, because by read time both look equally true.+ *+ * The rule is deliberately narrow, because a guard that cries wolf gets `allow_conflict: true`+ * pasted into every call and stops meaning anything. It fires only on **near-duplicate names**:+ * two stems that are identical once dates and recency words are stripped. `acme-pricing-2026`+ * collides with `acme-pricing`; `acme-pricing-uk` does not collide with `acme-pricing`, because a+ * region-specific note is a real distinction and not this bug.+ */++/** Tokens that say "when" or "which version", never "about what". Stripped before comparing. */+const NOISE = new Set([+ // recency / versioning+ "new", "old", "latest", "current", "final", "updated", "revised", "copy", "duplicate",+ "v1", "v2", "v3", "v4", "rev", "revision",+ // months, long and short+ "january", "february", "march", "april", "may", "june", "july",+ "august", "september", "october", "november", "december",+ "jan", "feb", "mar", "apr", "jun", "jul", "aug", "sep", "sept", "oct", "nov", "dec",+ // quarters+ "q1", "q2", "q3", "q4",+]);++/** A 4-digit year, or any pure number (day, ISO fragment, `2026`, `07`, `09`). */+function isDateish(tok: string): boolean {+ return /^\d+$/.test(tok);+}++/**+ * Reduce a stem to the tokens that describe *what it is about*.+ * "acme-pricing-2026-07" and "acme-pricing-new" both reduce to {acme, pricing}.+ */+export function subjectTokens(stem: string): Set<string> {+ return new Set(+ stem+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter((t) => t.length > 0 && !isDateish(t) && !NOISE.has(t)),+ );+}++function sameSet(a: Set<string>, b: Set<string>): boolean {+ if (a.size !== b.size || a.size === 0) return false;+ for (const t of a) if (!b.has(t)) return false;+ return true;+}++export interface ConflictCandidate {+ path: string;+ title: string;+ authority: string;+}++/**+ * Live notes whose subject tokens are identical to `relPath`'s.+ *+ * Retired notes are not conflicts — a superseded or expired note is exactly what a replacement is+ * *supposed* to sit next to, and flagging it would refuse the correct workflow. Only `current` and+ * `authoritative` notes can be contradicted.+ */+export function findConflicts(relPath: string, now: number = Date.now()): ConflictCandidate[] {+ const mine = subjectTokens(stemOf(relPath));+ if (mine.size === 0) return [];++ const out: ConflictCandidate[] = [];+ for (const n of listNotes() as NoteMeta[]) {+ if (n.path === relPath) continue;+ if (!sameSet(mine, subjectTokens(n.slug))) continue;+ const eff = overlayValidity(+ authorityOf({ path: n.path, status: n.status, tags: n.tags }),+ n.validUntil,+ n.supersededBy,+ now,+ );+ if (eff.retired) continue;+ out.push({ path: n.path, title: n.title, authority: eff.authority });+ }+ return out;+}++/**+ * Throw if creating `relPath` would contradict a live note. Callers pass `allowConflict` to+ * override — the escape hatch is deliberate and named in the message, mirroring `overwrite`.+ */+export function guardConflict(relPath: string, isNewNote: boolean, allowConflict: boolean): void {+ if (allowConflict || !isNewNote) return;+ const clashes = findConflicts(relPath);+ if (clashes.length === 0) return;++ const list = clashes.map((c) => `${c.path} (${c.authority})`).join(", ");+ const first = clashes[0].path;+ throw new Error(+ `Refusing to create ${relPath}: ${list} already covers this and is still live. ` ++ `Two live notes on one subject is how a retired value keeps getting quoted — both match the query, ` ++ `and the older one often matches it better. ` ++ `If this replaces it, use brain_supersede(from: "${first}", to: "${relPath}") — that retires the old note ` ++ `and adds this one in a single commit, so they cannot drift apart. ` ++ `If it genuinely belongs alongside it, pass allow_conflict: true.`,+ );+}diff --git a/lib/vault/stale-truth.test.ts b/lib/vault/stale-truth.test.tsnew file mode 100644index 0000000..e00670e--- /dev/null+++ b/lib/vault/stale-truth.test.ts@@ -0,0 +1,246 @@+import { beforeAll, describe, expect, test } from "bun:test";+import fs from "node:fs";+import path from "node:path";++/**+ * The stale-truth eval: does the vault stop an agent quoting a fact that is no longer true?+ *+ * Every fixture pair here is written with *near-identical wording* on purpose. That is the whole+ * difficulty — a retired price and a live one are textually the same, so relevance alone cannot+ * separate them and often ranks the retired one higher (it is usually the longer, more detailed+ * document). If these tests pass, the product's central claim holds; if they regress, search+ * silently starts handing agents dead facts again, which is the failure Engram exists to prevent.+ */++// The vault path is fixed by test/setup.ts, preloaded before any module reads config.+const vault = process.env.VAULT_DIR!;++function write(rel: string, content: string) {+ const abs = path.join(vault, rel);+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ fs.writeFileSync(abs, content, "utf8");+}++const PAST = "2026-01-15";+const FUTURE = "2099-01-01";++// The retired note is deliberately WORDIER than its replacement: it should still lose.+write(+ "pricing/acme-pricing.md",+ `---+title: Acme Pricing+status: superseded+superseded_by: "[[acme-pricing-live]]"+superseded_at: 2026-06-01+---+Acme pricing. The Acme retainer price is EUR 2000 per month. This price covers the+full Acme engagement. Pricing questions about the Acme price should reference this+pricing note. Price reviewed quarterly.+`,+);++write(+ "pricing/acme-pricing-live.md",+ `---+title: Acme Pricing (current)+status: locked+---+The Acme retainer price is EUR 2500 per month.+`,+);++write(+ "pricing/beta-terms.md",+ `---+title: Beta Terms+valid_until: ${PAST}+---+Beta terms: the beta discount is 20 percent off the beta price.+`,+);++write(+ "pricing/gamma-terms.md",+ `---+title: Gamma Terms+valid_until: ${FUTURE}+---+Gamma terms: the gamma discount is 20 percent off the gamma price.+`,+);++write(+ "archive/legacy-pricing.md",+ `---+title: Legacy Pricing+---+Legacy pricing: the legacy price was EUR 900 per month.+`,+);++write(+ "pricing/widget-pricing.md",+ `---+title: Widget Pricing+---+The widget price is EUR 100.+`,+);++type Store = typeof import("./store");+type Write = typeof import("./write");+type Conflict = typeof import("./conflict");++let store: Store;+let writeMod: Write;+let conflict: Conflict;++beforeAll(async () => {+ store = await import("./store");+ writeMod = await import("./write");+ conflict = await import("./conflict");+ store.rebuildIndex();+});++describe("search withholds facts that are no longer true", () => {+ test("a superseded note is withheld even though it matches the query better", () => {+ const r = store.searchNotes("acme price pricing");+ const hitPaths = r.hits.map((h) => h.path);++ expect(hitPaths).toContain("pricing/acme-pricing-live.md");+ expect(hitPaths).not.toContain("pricing/acme-pricing.md");++ const ex = r.excluded.find((e) => e.path === "pricing/acme-pricing.md");+ expect(ex).toBeDefined();+ expect(ex!.reason).toContain("superseded by acme-pricing-live");+ });++ test("the exclusion is explainable — every withheld note carries a reason", () => {+ const r = store.searchNotes("acme price pricing");+ for (const e of r.excluded) expect(e.reason.length).toBeGreaterThan(0);+ });++ test("an expired note is withheld and the reason names the date", () => {+ const r = store.searchNotes("beta discount terms");+ expect(r.hits.map((h) => h.path)).not.toContain("pricing/beta-terms.md");+ const ex = r.excluded.find((e) => e.path === "pricing/beta-terms.md");+ expect(ex).toBeDefined();+ expect(ex!.reason).toContain("expired");+ expect(ex!.reason).toContain(PAST);+ });++ test("an unexpired note with the same shape is NOT withheld", () => {+ const r = store.searchNotes("gamma discount terms");+ expect(r.hits.map((h) => h.path)).toContain("pricing/gamma-terms.md");+ });++ test("an archived note is withheld and reported as archived", () => {+ const r = store.searchNotes("legacy price");+ expect(r.hits.map((h) => h.path)).not.toContain("archive/legacy-pricing.md");+ const ex = r.excluded.find((e) => e.path === "archive/legacy-pricing.md");+ expect(ex?.authority).toBe("archived");+ });++ test("withheld notes are recoverable on request, not hidden", () => {+ const r = store.searchNotes("acme price pricing", { includeInvalid: true });+ expect(r.hits.map((h) => h.path)).toContain("pricing/acme-pricing.md");+ });++ test("a retired note never outranks its live replacement when both are requested", () => {+ const r = store.searchNotes("acme price pricing", { includeInvalid: true });+ const live = r.hits.findIndex((h) => h.path === "pricing/acme-pricing-live.md");+ const dead = r.hits.findIndex((h) => h.path === "pricing/acme-pricing.md");+ expect(live).toBeGreaterThanOrEqual(0);+ expect(dead).toBeGreaterThan(live);+ });+});++describe("guardConflict refuses a second live note on one subject", () => {+ test("a dated sibling of a live note is refused, and the error names brain_supersede", () => {+ expect(() => conflict.guardConflict("pricing/widget-pricing-2026-07.md", true, false)).toThrow(+ /brain_supersede/,+ );+ });++ test("the refusal names the note it collides with", () => {+ expect(() => conflict.guardConflict("pricing/widget-pricing-new.md", true, false)).toThrow(+ /widget-pricing\.md/,+ );+ });++ test("allow_conflict is a real escape hatch", () => {+ expect(() => conflict.guardConflict("pricing/widget-pricing-2026-07.md", true, true)).not.toThrow();+ });++ test("overwriting an existing note is not a conflict — that is guardTruncation's job", () => {+ expect(() => conflict.guardConflict("pricing/widget-pricing-2026-07.md", false, false)).not.toThrow();+ });++ test("a genuinely distinct note is allowed — the guard must not cry wolf", () => {+ // A region-specific note is a real distinction, not the duplicate-price bug.+ expect(() => conflict.guardConflict("pricing/widget-pricing-uk.md", true, false)).not.toThrow();+ expect(() => conflict.guardConflict("pricing/gadget-pricing.md", true, false)).not.toThrow();+ expect(() => conflict.guardConflict("pricing/widget-warranty.md", true, false)).not.toThrow();+ });++ test("a retired note is not a conflict — a replacement is supposed to sit next to it", () => {+ // acme-pricing.md is superseded, so writing a fresh acme-pricing-2026 must not be blocked by it.+ expect(() => conflict.guardConflict("pricing/acme-pricing-2026.md", true, false)).not.toThrow();+ });++ test("findConflicts only reports live notes", () => {+ expect(conflict.findConflicts("pricing/acme-pricing-2026.md")).toHaveLength(0);+ const live = conflict.findConflicts("pricing/widget-pricing-2026.md");+ expect(live.map((c) => c.path)).toEqual(["pricing/widget-pricing.md"]);+ });+});++describe("subjectTokens", () => {+ test("strips dates and recency words, keeps the subject", () => {+ expect([...conflict.subjectTokens("acme-pricing-2026-07")].sort()).toEqual(["acme", "pricing"]);+ expect([...conflict.subjectTokens("acme-pricing-new")].sort()).toEqual(["acme", "pricing"]);+ expect([...conflict.subjectTokens("acme-pricing-v2")].sort()).toEqual(["acme", "pricing"]);+ expect([...conflict.subjectTokens("acme-pricing-q3")].sort()).toEqual(["acme", "pricing"]);+ });++ test("keeps meaningful qualifiers, so distinct notes stay distinct", () => {+ expect([...conflict.subjectTokens("acme-pricing-uk")].sort()).toEqual(["acme", "pricing", "uk"]);+ });+});++describe("supersedeNote is atomic", () => {+ test("retires the old note in place and creates the replacement in one operation", async () => {+ await writeMod.supersedeNote(+ "pricing/widget-pricing.md",+ "pricing/widget-pricing-2027.md",+ "repriced for 2027",+ "The widget price is EUR 150.",+ );++ const oldRaw = fs.readFileSync(path.join(vault, "pricing/widget-pricing.md"), "utf8");+ expect(oldRaw).toContain("status: superseded");+ expect(oldRaw).toContain("superseded_by:");+ expect(oldRaw).toContain("repriced for 2027");+ // Body preserved — backlinks and chronology survive, and the truncation guard cannot trip.+ expect(oldRaw).toContain("The widget price is EUR 100.");++ expect(fs.existsSync(path.join(vault, "pricing/widget-pricing-2027.md"))).toBe(true);+ });++ test("after superseding, search withholds the old note and returns the new one", () => {+ store.rebuildIndex();+ const r = store.searchNotes("widget price");+ expect(r.hits.map((h) => h.path)).toContain("pricing/widget-pricing-2027.md");+ expect(r.hits.map((h) => h.path)).not.toContain("pricing/widget-pricing.md");+ const ex = r.excluded.find((e) => e.path === "pricing/widget-pricing.md");+ expect(ex?.reason).toContain("superseded by widget-pricing-2027");+ });++ test("refuses to supersede a note into itself", () => {+ expect(writeMod.supersedeNote("pricing/a.md", "pricing/a.md")).rejects.toThrow();+ });++ test("refuses to supersede a note that does not exist", () => {+ expect(writeMod.supersedeNote("pricing/nope.md", "pricing/other.md")).rejects.toThrow(/does not exist/);+ });+});diff --git a/lib/vault/store.ts b/lib/vault/store.tsindex 90a1910..b55b01b 100644--- a/lib/vault/store.ts+++ b/lib/vault/store.ts@@ -6,7 +6,7 @@ import { VAULT_IGNORE } from "@/lib/config";import { activeVaultDir } from "@/lib/repos";import { scanVault } from "./scan";import { parseNote, stemOf } from "./parse";-import { authorityOf, authorityRules, isArchivedPath, overlayValidity, weightOf, type Authority } from "./authority";+import { authorityOf, authorityRules, isArchivedPath, isUnrecognizedStatus, overlayValidity, weightOf, type Authority } from "./authority";import type { Graph, GraphEdge, GraphNode, Note, NoteMeta, TreeNode } from "./types";interface IndexDoc {@@ -473,6 +473,7 @@ export function vaultConventions() {const statuses = new Map<string, number>();const types = new Set<string>();const malformed: Array<{ path: string; error: string }> = [];+ const unknownStatus: Array<{ path: string; status: string }> = [];let archived = 0;let superseded = 0;let expired = 0;@@ -482,6 +483,7 @@ export function vaultConventions() {folders.add(n.folder);if (n.type) types.add(n.type);if (n.status) statuses.set(n.status, (statuses.get(n.status) ?? 0) + 1);+ if (isUnrecognizedStatus(n.status)) unknownStatus.push({ path: n.path, status: n.status! });if (isArchivedPath(n.path)) archived++;if (n.frontmatterError) malformed.push({ path: n.path, error: n.frontmatterError });if (n.supersededBy) superseded++;@@ -502,6 +504,7 @@ export function vaultConventions() {integrity: {duplicateStems: [...s.duplicateStems.entries()].map(([stem, paths]) => ({ stem, paths })),malformedFrontmatter: malformed,+ unrecognizedStatus: unknownStatus,...(s.duplicateStems.size > 0? { duplicateStemWarning: "Wikilinks to a duplicated stem resolve to the first path only. Rename one." }: {}),@@ -511,6 +514,12 @@ export function vaultConventions() {"These notes open with `---` but their YAML is unparseable, so their status, tags and title are being ignored — they rank as ordinary notes regardless of what they claim. Usual cause: an unquoted `:` in a value. Fix by quoting it.",}: {}),+ ...(unknownStatus.length > 0+ ? {+ unrecognizedStatusWarning:+ "These notes carry a `status:` the ranking model does not recognise, so they rank as plain `current` no matter what they claim. Often a typo (`lokced`), sometimes a vault convention this instance has not been told about. See ranking.statusWords for the vocabulary.",+ }+ : {}),},};}diff --git a/lib/vault/write.ts b/lib/vault/write.tsindex 6c86032..2157563 100644--- a/lib/vault/write.ts+++ b/lib/vault/write.ts@@ -2,9 +2,10 @@ import fsp from "node:fs/promises";import path from "node:path";import matter from "gray-matter";import { activeVaultDir } from "@/lib/repos";-import { refreshPaths } from "./store";+import { refreshPaths, getNote } from "./store";import { humanize, stemOf } from "./parse";import { checkFrontmatter, frontmatterErrorMessage } from "./validate";+import { guardConflict } from "./conflict";import { requestSync } from "@/lib/git";import { currentActor } from "@/lib/actor";@@ -44,6 +45,12 @@ export interface WriteOpts {* A human in the editor is looking at what they're deleting; an agent usually is not.*/allowShrink?: boolean;+ /**+ * Permit creating a note that duplicates a live note's subject. Default false for agents.+ * See `guardConflict` — the common failure is an agent adding a second live price note+ * instead of superseding the first.+ */+ allowConflict?: boolean;}/** An existing note this size or larger is worth protecting from an accidental truncation. */@@ -77,6 +84,37 @@ async function guardTruncation(abs: string, relPath: string, next: string, allow);}+/**+ * Structural read-before-overwrite. Not a size heuristic like `guardTruncation` — this refuses the+ * write outright until the caller has actually opened the note, so a same-size clobber is caught+ * too. Returns an error message for the model, or null to proceed.+ *+ * Shared by the Curator loop (which tracks reads per run) and the MCP tools (which track them per+ * caller — see lib/mcp/session.ts). It used to live only in the loop, which left the surface that+ * matters most, a coding agent writing over MCP, protected by the size heuristic alone.+ */+export function guardOverwrite(toolName: string, target: string, hasRead: (p: string) => boolean): string | null {+ if (toolName !== "brain_write" && toolName !== "brain_edit") return null;+ if (!target || hasRead(target)) return null;+ let exists = false;+ try {+ exists = getNote(normalizeNotePath(target)) !== null;+ } catch {+ return null;+ }+ if (!exists) return null;+ return `${target} already exists and you have not read it in this session. Call brain_read("${target}") first, then write back the full content you intend to keep — or use brain_append to add to it.`;+}++async function fileExists(abs: string): Promise<boolean> {+ try {+ await fsp.access(abs);+ return true;+ } catch {+ return false;+ }+}+/** Write a note from a raw markdown string (frontmatter included). Used by the editor. */export async function writeNoteRaw(relPath: string, content: string, opts: WriteOpts = {}): Promise<string> {const p = normalizeNotePath(relPath);@@ -85,6 +123,9 @@ export async function writeNoteRaw(relPath: string, content: string, opts: Writeif (!check.ok) throw new Error(frontmatterErrorMessage(p, check.error!));}const abs = safeAbs(p);+ // Agents only. A human in the editor who names a note `pricing-2026` next to `pricing` can see+ // both in the sidebar and meant it; an agent usually has not looked.+ if (opts.strict) guardConflict(p, !(await fileExists(abs)), opts.allowConflict === true);await guardTruncation(abs, p, content, opts.allowShrink === true);await fsp.mkdir(path.dirname(abs), { recursive: true });await fsp.writeFile(abs, content, "utf8");diff --git a/package.json b/package.jsonindex 858fbca..bb4fca8 100644--- a/package.json+++ b/package.json@@ -2,6 +2,15 @@"name": "engram","version": "0.1.0","private": true,+ "author": "rwnalds",+ "homepage": "https://github.com/rwnalds/engram#readme",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/rwnalds/engram.git"+ },+ "bugs": {+ "url": "https://github.com/rwnalds/engram/issues"+ },"description": "Engram — a self-hosted MCP server + dashboard that gives Claude Code, Cursor, and Hermes agents shared long-term memory over a git-backed markdown vault. An agent-native second brain.","keywords": ["mcp",@@ -31,6 +40,7 @@"build": "next build","start": "next start","mcp:stdio": "bun scripts/mcp-stdio.ts",+ "test": "bun test","lint": "eslint","gen:secrets": "tsx scripts/gen-secrets.ts"},diff --git a/sample-vault/clients/acme/acme-pricing-2026.md b/sample-vault/clients/acme/acme-pricing-2026.mdnew file mode 100644index 0000000..dd1d296--- /dev/null+++ b/sample-vault/clients/acme/acme-pricing-2026.md@@ -0,0 +1,38 @@+---+title: Acme Pricing (2026)+type: doc+tags: [client, pricing]+status: locked+created: 2026-01-10+valid_until: 2026-12-31+supersedes: "[[acme-pricing]]"+related:+ - "[[acme]]"+---++# Acme Pricing (2026)++The Acme retainer price is **EUR 2,500 per month**.++| Field | Value |+|---|---|+| Retainer price | EUR 2,500 / month |+| Billing | Monthly |+| Term | 2026 renewal |++Supersedes [[acme-pricing]] — repriced for the 2026 renewal.++## Try it++This pair is the whole idea of Engram, in two files. Search the vault for **`acme price`**:++- This note comes back as a hit, marked `authoritative`.+- [[acme-pricing]] is **withheld**, and the agent is handed the reason — `superseded by+ acme-pricing-2026` — so it can say what it skipped instead of quoting EUR 2,000.++Note that the retired note is the *longer* one, and repeats "price" more often. Relevance alone+would rank it first. That's why the retirement has to be written down when it happens, rather+than inferred at read time.++`valid_until: 2026-12-31` is the passive half: after that date this note flags itself stale+without anyone remembering to retire it.diff --git a/sample-vault/clients/acme/acme-pricing.md b/sample-vault/clients/acme/acme-pricing.mdnew file mode 100644index 0000000..8b7fc59--- /dev/null+++ b/sample-vault/clients/acme/acme-pricing.md@@ -0,0 +1,39 @@+---+title: Acme Pricing (2025 pilot)+type: doc+tags: [client, pricing]+status: superseded+superseded_by: "[[acme-pricing-2026]]"+superseded_at: 2026-01-10+superseded_reason: repriced for the 2026 renewal+created: 2025-03-02+related:+ - "[[acme]]"+---++# Acme Pricing (2025 pilot)++> [!warning] Retired — kept for history+> This is the pilot pricing Acme signed in 2025. It was replaced by [[acme-pricing-2026]].+> Search withholds this note; agents are told it was superseded and why.++The Acme retainer price is **EUR 2,000 per month**, billed quarterly in advance. This price+covers the full Acme engagement: the pilot workspace, support, and quarterly reviews. Pricing+questions about the Acme retainer price should reference this pricing note. The price was+reviewed each quarter and held flat for the duration of the pilot.++| Field | Value |+|---|---|+| Retainer price | EUR 2,000 / month |+| Billing | Quarterly, in advance |+| Term | Pilot, 2025 |++## Why this note still exists++Deleting it would destroy the reasoning trail — you'd lose *why* the price changed and what+Acme actually agreed to in 2025. Superseding it keeps the history and takes it out of the+answer. That's the difference between an archive and a lie.++## Connected to+- [[acme]] — the client+- [[acme-pricing-2026]] — what replaced thisdiff --git a/sample-vault/clients/acme/acme.md b/sample-vault/clients/acme/acme.mdindex 680003c..611838b 100644--- a/sample-vault/clients/acme/acme.md+++ b/sample-vault/clients/acme/acme.md@@ -17,7 +17,9 @@ Example client note. Referred by [[ada-lovelace]]. Using [[engram]] as their tea|---|---|| Plan | Pilot || Started | 2026-01-15 |+| Pricing | see [[acme-pricing-2026]] |## Connected to- [[ada-lovelace]] — main contact- [[engram]] — what we're building for them+- [[acme-pricing-2026]] — current pricing (supersedes [[acme-pricing]])diff --git a/test/setup.ts b/test/setup.tsnew file mode 100644index 0000000..d40fdef--- /dev/null+++ b/test/setup.ts@@ -0,0 +1,31 @@+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++/**+ * Preloaded before any test module (see bunfig.toml).+ *+ * `lib/config.ts` resolves VAULT_DIR and ENGRAM_DATA_DIR at *import* time, and Bun shares one+ * module registry across test files. So whichever test file imports the store first would freeze+ * the vault path for every other file — a test that sets its own VAULT_DIR then silently reads the+ * bundled sample-vault, and fails or passes depending on file order. Setting it here, before any+ * module loads, makes the whole suite deterministic regardless of order.+ */++// Standard ESM rather than Bun's `import.meta.dir`: `next build` type-checks this file with tsc,+// which doesn't know Bun's extensions.+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+export const TEST_VAULT = path.join(root, ".test-vault");+export const TEST_DATA = path.join(root, ".test-data");++// Start from a clean vault every run, so a fixture left behind by a previous run can't+// mask a regression (or invent one).+fs.rmSync(TEST_VAULT, { recursive: true, force: true });+fs.rmSync(TEST_DATA, { recursive: true, force: true });+fs.mkdirSync(TEST_VAULT, { recursive: true });+fs.mkdirSync(TEST_DATA, { recursive: true });++process.env.VAULT_DIR = TEST_VAULT;+process.env.ENGRAM_DATA_DIR = TEST_DATA;+// Never let a test commit or push. The vault under test is not a git repo anyway, but be explicit.+process.env.GIT_SYNC_ENABLED = "false";