{
  "markdown": "<p align=\"center\">\n  <img src=\"docs/wordmark.svg\" alt=\"selvedge\" width=\"480\">\n</p>\n\n<p align=\"center\">\n  <a href=\"https://selvedge.sh\"><strong>selvedge.sh</strong></a>\n  &nbsp;·&nbsp;\n  <a href=\"https://pypi.org/project/selvedge/\"><strong>PyPI</strong></a>\n  &nbsp;·&nbsp;\n  <a href=\"https://github.com/masondelan/selvedge\"><strong>GitHub</strong></a>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://github.com/masondelan/selvedge/actions/workflows/test.yml\"><img src=\"https://github.com/masondelan/selvedge/actions/workflows/test.yml/badge.svg\" alt=\"Tests\"></a>\n  <a href=\"https://pypi.org/project/selvedge/\"><img src=\"https://img.shields.io/pypi/v/selvedge?cacheSeconds=3600\" alt=\"PyPI\"></a>\n  <a href=\"LICENSE\"><img src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" alt=\"License: MIT\"></a>\n</p>\n\n<!-- mcp-name: io.github.masondelan/selvedge -->\n\n**Long-term memory for AI-coded codebases — including what was already\ntried and rejected.**\n\nLine attribution tells you who wrote something. Selvedge tells your agent\nwhat *not* to write next: the approaches this codebase already tried,\nreverted, and why. It's a `git blame` for AI agents, for the *why* rather\nthan which model touched which line — captured live, by the agent, as the\nchange happens, so nothing downstream has to guess at it.\n\nSelvedge is a local MCP server. AI coding agents (Claude Code, Cursor,\nCopilot) call it as they work to log structured change events with\nreasoning. Your data stays in a SQLite file under `.selvedge/` next to\nyour code.\n\n**Local-first by default, team-server by choice, zero-LLM always.**\n\n---\n\nSix months ago, your AI agent added a column called `user_tier_v2`. You don't\nknow why. `git blame` points to a commit from `claude-code` with a generated\nmessage that says \"Update schema.\" The session that made the change is long\ngone — and so is the prompt that produced it.\n\nWith Selvedge, you run this instead:\n\n```bash\n$ selvedge blame user_tier_v2\n\n  user_tier_v2\n  Changed     2025-10-14 09:31:02\n  Agent       claude-code\n  Commit      3e7a991\n  Reasoning   User asked to add a grandfathering flag for legacy free-tier\n              users during the pricing migration. Stores the original tier\n              so we can backfill discounts without touching billing history.\n```\n\nThat reasoning was **captured by the agent in the moment** — written into\nSelvedge from the same context that produced the change. Not inferred from\nthe diff afterward by a second LLM. Not a hand-typed commit message.\n\n---\n\n<!-- DEMO GIF\n     Record a 30–45 second terminal session showing:\n     1. `selvedge status`  →  shows N total events\n     2. `selvedge blame payments.amount`  →  full output with reasoning\n     3. `selvedge diff users --since 30d`  →  table of recent changes\n     4. `selvedge search \"stripe\"`  →  filtered results\n     Use `vhs` (https://github.com/charmbracelet/vhs) or Asciinema.\n     Replace this comment block with: ![Selvedge demo](docs/demo.gif)\n-->\n\n---\n\n## Who Selvedge is for\n\nSelvedge has two audiences. Same tool, same `pip install`, same SQLite\nfile under `.selvedge/`. Different scale of pain.\n\n**Teams running long-term, AI-coded codebases.**\nWhen the project is big enough that you (or someone else) will touch it\nagain in six months, twelve months, three years — but most of it was written\nby an agent whose context evaporated the day each PR shipped. `git blame`\ntells you what changed. Selvedge tells you *why* — even after the agent\nsession, the prompt template, the developer who asked for it, and the model\nversion are all long gone. This is the original use case: production\ncodebases, schema decisions, migrations, dependency changes that need an\naudit trail that survives turnover.\n\n**Solo developers using Claude Code on everyday projects.**\nSide projects, weekend builds, the small internal tool you keep poking at.\nYou don't need enterprise governance — you just need to remember why you (or\nyour agent) did the thing you did yesterday, last week, last sprint. Run\n`selvedge init` once. Add four lines to your `CLAUDE.md`. From then on,\n`selvedge blame` is muscle memory — a way to talk to your past self when\nyour past self was an LLM.\n\nIf you've ever come back to your own AI-built project and thought \"what was\nthis *for* again?\", Selvedge is the missing piece.\n\n---\n\n## The problem\n\nHuman-written code leaks intent everywhere — commit messages, PR descriptions,\ninline comments, the Slack thread that preceded it. AI-written code doesn't.\nThe agent has perfect clarity about why it made each decision, but that\ncontext lives in the prompt and evaporates when the conversation ends.\n\nSix months later, your team is debugging a schema decision with no trail.\n`git blame` tells you *what* changed and *when*. It can't tell you *why*.\n\n**Selvedge captures the why — live, by the agent itself, as the change is\nmade.** The diff is git's job. The why is Selvedge's.\n\n---\n\n## What's new in v0.3.11\n\n**Abandoned alternatives are first-class, and the log can prove itself.**\n\n**Rejections and reverts are now stated outcomes, not inferences.**\n`change_type=\"reject\"` records \"we considered this and decided against it\"\nwithout writing the change — the counterpart to `revert` for paths never\ntaken. `prior_attempts` reads both as a new `confidence: \"exact\"` tier; the\nold proximity heuristic drops to tiebreaker. And the `expires_when` column\nthat shipped dormant in v0.3.8 gets its evaluator: a closed, machine-checkable\ngrammar — `library:NAME>=VERSION`, `entity:PATH:changes`, `date:ISO`,\n`manual:LABEL` — validated at write time, evaluated locally by\n`selvedge stale` with no network and no LLM. A rejection stored with the\ncondition that would invalidate it is a decision that knows when to die.\n\n**The event log is now tamper-evident.** Every logged event gets a SHA-256\nchain record in a sidecar table, same transaction, over every field except the\nlate-bound `git_commit` (git already witnesses that one). Two new\n`selvedge verify` checks: `chain_intact` fails hard when a chained row was\nedited, deleted, or reordered out-of-band — the check names the exact sequence\nnumber — and `chain_coverage` warns (never fails) about rows that predate the\nchain. Legitimate operations append boundary records instead of breaking the\nchain, so `migrate-paths` and a destructive-gated prune verify clean while a\nsilent `sqlite3` edit does not. `selvedge verify --json` publishes the\nattestation manifest. Honest scope, stated in the module itself: this detects\ncasual and accidental modification and produces an independently verifiable\nexport; it is not proof against a motivated local attacker.\n\n**Also:** the PreCompact reminder now distinguishes \"edited with no log\" from\n\"log exists but was truncated,\" and both hook surfaces have their determinism\npinned byte-for-byte in tests; capture-time nudges suggest recording the\ninvalidating condition when a reject/revert lands without one;\n`selvedge supersede` gains `-d/--diff`, `--revisit-after`, and\n`--expires-when` (#31); and an id-less supersede no longer re-opens every\nearlier revert on the path (#30). Tests 984 → 1114.\n\n---\n\n## What's new in v0.3.10\n\n**The memory comes to the agent, and the store gets its dials.** Two themes,\nshipped together because the config half is what the rest needed to read\nsettings from.\n\n**Delivery.** Selvedge already blocked re-edits of reverted entities. What was\nmissing was delivery when there is nothing to veto. Two new hooks:\n\n- **SessionStart** injects a compact digest as a session begins — decisions due\n  for a revisit, entities that were tried and reverted, recent changesets.\n- **PreCompact** fires just before context compaction destroys this session's\n  reasoning and names the watched entities you edited but never logged.\n\nBoth are quiet when they have nothing to say, size-capped, read-only, and\ntemplated. Neither can block anything — PreCompact deliberately declines the\nveto the hook API offers it. This is the answer to a measured failure mode:\n\"Delivery, Not Storage\" (arXiv:2607.20972) recorded a pull-model memory tool\ngoing unused entirely (zero voluntary memory operations across 114 turns\nagainst a pre-seeded store) while deterministic injection landed every time.\n\n**`selvedge export --format markdown`** renders the store as a reviewable\ndigest to commit next to it, so captured intent shows up in a pull request\ninstead of hiding inside a binary. Deterministic — regenerating with no new\nevents is a zero-line diff.\n\n**Config.** `.selvedge/config.toml` is now first-class, with a canonical\nprecedence chain that `selvedge doctor` prints per setting. It brings:\n\n- **`selvedge prune --include-events`** — the first path that can delete\n  captured reasoning, so it needs *both* a confirmation and\n  `SELVEDGE_DESTRUCTIVE=1`. Neither alone is enough, because `--yes` in a cron\n  entry defeats a prompt and a shell profile defeats an env var. Events\n  retention defaults to never.\n- **Event-size bounds** (`diff_bytes`, `reasoning_bytes`) that truncate loudly\n  — a marker in the text, a warning at write time, a count in `selvedge stats`.\n- **Secret-shape warnings** at `log_change`, extendable via\n  `redaction_patterns`, plus a `doctor` row that scans what's already stored.\n  Warn, never reject.\n\n**Also:** five review issues closed. The enforcement hook's allow path is\n**40% faster** (33.6 ms → 20.1 ms per gated call) and `SELVEDGE_HOOK_DISABLE=1`\nfinally short-circuits before the imports it was documented to skip;\n`log_change` no longer discards `revisit_after` / `constraint` / `stale_when`\non renames and supersedes; the CLI's `--json` and the MCP tools now return\nidentical structures; and the Docker image no longer ships the maintainer's\nown database. Tests 826 → 984.\n\n---\n\n---\n\n## Where Selvedge fits\n\n<p align=\"center\">\n  <img src=\"docs/ecosystem.svg\" alt=\"Where Selvedge fits in the broader AI-coded-codebase tooling stack\" width=\"720\">\n</p>\n\nAI agents call Selvedge as they work. Selvedge captures the *why*\ninto a durable, queryable store and emits it back out — as\n[Agent Trace](https://agent-trace.dev/) records for\ncross-tool readers, as observability metadata that links into\nSentry/Datadog stack traces, and as compliance artifacts for SOC 2\nand EU AI Act audits.\n\nSelvedge does **not** replace `git` (line-level what/when), PR review\ntools (review-time quality), agent observability (LLM call traces),\nor general-purpose code-host AI features. It sits between them — the\nprovenance-as-first-class-citizen layer that everything else\nreferences.\n\n---\n\n## How Selvedge compares\n\nThere's a fast-growing \"git blame for AI agents\" category. Here's where\nSelvedge fits — and where it deliberately doesn't.\n\n|  | Rejected paths | Reasoning source | Granularity | Mechanism | Grouping | Storage |\n|---|---|---|---|---|---|---|\n| **Selvedge** | **Queryable** — `prior_attempts` returns tried → reverted → re-opened | **Captured live**, by the agent in the same context that produced the change | **Entity** — DB column, table, env var, dep, API route, function | **MCP server** — agent calls it as work happens | **Changesets** — named feature/task slugs across many entities | SQLite, zero deps |\n| [OpenLore](https://github.com/clay-good/OpenLore) | Purged — `rejected` is an inactive status, dropped from the queryable store after each decision sync (the annotation survives in the synced spec markdown) | **Derived** — tree-sitter static analysis of code state, plus commit-gated decision notes | AST node (18 languages + 12 IaC) | MCP server — one-time index + commit-time certificates | Call-graph edges | SQLite graph in `.openlore/` |\n| [AgentDiff (sunilmallya)](https://github.com/sunilmallya/agentdiff) | None | **Inferred post-hoc** by Claude Haiku from the diff at session end | Line | Claude Code lifecycle hooks → local daemon | Session/task | JSONL on disk |\n| [AgentDiff (codeprakhar25)](https://github.com/codeprakhar25/agentdiff) | None | ed25519-signed cross-agent provenance | Line | Per-agent editor hooks + git hooks (sign at commit) | None | Signed traces in git refs |\n| [Origin](https://github.com/opsworks-co/origin-cli) | None — `rework` flags reverted AI code post-hoc, without rationale | Prompt receipts, captured live per turn | Line | Agent lifecycle hooks + git post-commit hook | None | Git notes + sessions branch |\n| [Git AI](https://github.com/git-ai-project/git-ai) | None | Attribution metadata | Line | **Agent-invoked checkpoint** → Git notes at commit | None | Git notes |\n| [BlamePrompt](https://github.com/Ekaanth/blameprompt) | None | Prompt receipts — prompt, cost, tools; no stated rationale | Line | Agent-lifecycle hooks + post-commit hook | None | Git notes |\n\n**Why \"rejected paths\" matter — the one that isn't copyable.** The expensive\nfailure isn't forgetting why a column exists. It's an agent confidently\nre-implementing something the team already killed for a good reason, six\nmonths after everyone who knew that left the context window. None of the\nline-attribution tools above surface rejected paths at all, and it isn't a\nfeature gap they can close in a release — a line-oriented store has no notion\nof an entity that persisted across a try → revert → retry cycle. See\n[`docs/demos/prior-attempts.md`](docs/demos/prior-attempts.md).\n\n**Why determinism matters.** Selvedge's reasoning is the agent's own intent,\nwritten from the same context window that produced the change. There is no\nmodel anywhere in the storage or retrieval path, so the same query returns the\nsame answer today and in two years, across model versions. Tools that infer\nreasoning post-hoc are running a second LLM that never saw the original\nprompt: what it produces is paraphrase, and re-running it can produce\ndifferent categories for the same change. As a Hacker News commenter put it\nabout a competing approach, *\"grep won't find your commit because you rejected\n'oauth-library'… unless there is deterministic enforcement\"*\n([0x457](https://news.ycombinator.com/item?id=47354263)).\n\nDeterminism alone is no longer a separator — OpenLore is deterministic-native\ntoo, and says so. The compound that separates is **append-only testimony**:\nreasoning the agent wrote itself, kept in a store where a rejection is a\nfirst-class record rather than an inactive status to be swept up.\n\n**Why \"entity-level\" matters.** Most tools attribute *lines*. Selvedge\nattributes *things you actually search for*: `users.email`,\n`env/STRIPE_SECRET_KEY`, `api/v1/checkout`, `deps/stripe`. The first\nquestion after `git blame` is usually *\"what's the history of this column\"*,\nnot *\"what's the history of lines 40–48 of users.py\"*.\n\n**Why \"captured live\" matters.** Not a differentiator on its own — every tool\nhere claims some flavour of it — but it's the *mechanism* that makes the\nreasoning trustworthy. Writing at the moment of the change, from the context\nthat produced it, is the reason there's no second model in the path to\nhallucinate an explanation. An empty `reasoning` field is itself an honest\nsignal: the agent didn't have one.\n\n<sub>Comparison current as of 2026-08-05; OpenLore at v2.1.8 / 265★,\nverified against its source. Corrections welcome as an issue.</sub>\n\n**Why \"changesets\" matter.** A Stripe billing rollout touches the `users`\ntable, two new env vars, three new API routes, one dependency, and four\nfunctions across the codebase. Tag every event with `changeset:add-stripe-billing`\nand you can pull the entire scope back later — even if the original PR was\nbroken into eight smaller ones over a month.\n\n**Selvedge ↔ Agent Trace.** [Agent Trace](https://agent-trace.dev/) is an\nopen AI code-attribution wire format published by Cursor (RFC, Jan 2026). Its\noriginal GitHub home went 404 in August 2026 and the multi-vendor momentum\nbehind it has faded, but the spec and schema still resolve at agent-trace.dev,\nfrozen at v0.1.0. Since **v0.3.9**, `selvedge export --format agent-trace`\nemits Agent Trace v0.1.0 records and `selvedge import --format agent-trace`\nreads them back — a portable, documented interchange format for file/line AI\nattribution, with reasoning and entity-level provenance carried in each\nrecord's `dev.selvedge` metadata. The mapping is in\n[`docs/agent-trace-interop.md`](docs/agent-trace-interop.md); Selvedge vendors\nthe schema and has no runtime dependency on the upstream project.\n\n---\n\n## Quickstart\n\n### Claude Code — install the plugin (recommended)\n\nTwo commands, inside Claude Code. No prior `pip install` — the plugin\nbootstraps the server itself via `uvx` (or `pipx`):\n\n```\n/plugin marketplace add masondelan/selvedge\n/plugin install selvedge@selvedge\n```\n\nThat's the whole agent-facing surface in one step:\n\n- the **MCP server** — 8 tools (`log_change`, `prior_attempts`, `blame`,\n  `diff`, `history`, `changeset`, `search`, `stale_decisions`);\n- a **skill** that tells the agent *when* to call them — before editing a\n  tracked entity, after any substantive change;\n- the **PreToolUse enforcement hook** — schema/migration edits are blocked\n  until `prior_attempts` has been checked this session, with the prior\n  reasoning in the block message;\n- **slash commands** — `/selvedge:status`, `/selvedge:blame <entity>`,\n  `/selvedge:history`, `/selvedge:prior-attempts <entity>`.\n\nThe store (`.selvedge/selvedge.db`) creates itself on the first logged change.\nTwo optional extras stay CLI-side: the post-commit hook that stamps each event\nwith its commit hash (`selvedge install-hook`), and — if you want the\n`selvedge` command on your own shell `PATH` — `pip install selvedge`, which the\nlauncher then prefers over `uvx` for an exact pinned version.\n\n> **Plugin or `selvedge setup` for Claude Code? Pick one.** Both wire the MCP\n> server; running both registers it twice. The plugin is the lighter path and\n> the one that updates itself. If you're on the plugin and only want the\n> post-commit commit-hash stamping, run `selvedge install-hook` on its own.\n\n### Any other MCP client — `selvedge setup`\n\nCursor, Copilot, Windsurf, Codex CLI, Gemini CLI, and the rest:\n\n```bash\npip install selvedge\ncd your-project\nselvedge setup\n```\n\nThat's it. `selvedge setup` is an interactive wizard: it detects which AI\ntools you have (Claude Code, Cursor, Copilot), writes the MCP entry into\neach one's config, drops the canonical agent-instructions block into your\nproject's prompt file (`CLAUDE.md` / `.cursorrules` /\n`copilot-instructions.md`), installs the PreToolUse enforcement hook into\n`.claude/settings.json` (Claude Code only — blocks schema/migration edits\nuntil `prior_attempts` has been checked; `--skip-enforcement-hook` to opt\nout), runs `selvedge init`, and installs the post-commit hook. Every\nmodified file gets a `.bak` written next to it before any change reaches\ndisk. Re-running is a no-op.\n\nFor CI bootstrap or `devcontainer.json` `postCreateCommand`:\n```bash\nselvedge setup --non-interactive --yes\n```\n\n**Verify the wiring** — open a second terminal in the same project:\n\n```bash\nselvedge watch\n```\n\nMake any change in your AI tool — add a column, rename a function, add an\nenv var. `selvedge watch` should print the new event within a second of\nthe agent calling `log_change`. If nothing arrives, run `selvedge doctor`\nfor a single-command health check that tells you which step is silently\nbroken.\n\n**Query your history:**\n\n```bash\nselvedge status                        # recent activity + missing-commit count\nselvedge diff users                    # all changes to the users table\nselvedge diff users.email              # changes to a specific column\nselvedge blame payments.amount         # what changed last and why\nselvedge history --since 30d           # last 30 days of changes\nselvedge history --since 15m           # last 15 minutes ('m' = minutes)\nselvedge changeset add-stripe-billing  # all events for a feature/task\nselvedge search \"stripe\"               # full-text search\nselvedge stats                         # log_change coverage report (per-agent)\nselvedge import migrations/            # backfill from migration files\nselvedge export --format csv           # dump history to CSV\n```\n\n<details>\n<summary><b>Manual install</b> — if you'd rather wire it up yourself</summary>\n\nIf you don't want to run the wizard, the four manual steps it automates:\n\n**1. Initialize in your project**\n\n```bash\ncd your-project\nselvedge init\n```\n\n**2. Register the MCP server**\n\nSelvedge is a standard stdio MCP server, so it works with any MCP client —\nClaude Code, Cursor, Windsurf, Codex CLI, Gemini CLI, and more. See\n**[Works with any MCP client](#works-with-any-mcp-client)** for the exact\nconfig per client. For Claude Code:\n\n```bash\nclaude mcp add selvedge -- selvedge-server\n```\n\n**3. Tell your agent to use it**\n\n```bash\nselvedge prompt --install CLAUDE.md\n```\n\nPoint `--install` at whichever prompt file your client reads — the block\nitself is identical across clients:\n\n| Client | Prompt file |\n|--------|-------------|\n| Claude Code | `CLAUDE.md` |\n| Codex CLI (and other `AGENTS.md`-aware tools) | `AGENTS.md` |\n| Cursor | `.cursor/rules/selvedge.md` (or legacy `.cursorrules`) |\n| Gemini CLI | `GEMINI.md` |\n\nThis installs the canonical agent-instructions block, sentinel-bracketed\n(`<!-- selvedge:start -->` / `<!-- selvedge:end -->`) so future\n`--install` calls update the bracketed region without disturbing\nanything else in the file. Or pipe it:\n\n```bash\nselvedge prompt | tee -a CLAUDE.md\n```\n\nPrefer to copy-paste? The same block is one click away on the website:\n**[selvedge.sh/prompt-block](https://selvedge.sh/prompt-block)** — with a\ncopy button and notes on what your agent does with it.\n\n**4. Install the post-commit hook**\n\n```bash\nselvedge install-hook\n```\n\nThat's the same four steps the wizard runs.\n\n</details>\n\n---\n\n## Works with any MCP client\n\nSelvedge is a standard stdio MCP server — its launch command is\n`selvedge-server`, put on your `PATH` by `pip install selvedge`. Any\nMCP-capable client can run it. Pick yours:\n\n<details>\n<summary><b>Claude Code</b></summary>\n\n```bash\nclaude mcp add selvedge -- selvedge-server\n```\n\nOr commit a project-level `.mcp.json` so your whole team gets it:\n\n```json\n{\n  \"mcpServers\": {\n    \"selvedge\": { \"command\": \"selvedge-server\" }\n  }\n}\n```\n\nDocs: <https://code.claude.com/docs/en/mcp>\n</details>\n\n<details>\n<summary><b>Cursor</b></summary>\n\n`.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (global):\n\n```json\n{\n  \"mcpServers\": {\n    \"selvedge\": { \"command\": \"selvedge-server\" }\n  }\n}\n```\n\nCursor's newer schema also accepts an explicit `\"type\": \"stdio\"`; the\n`command`-only form works too (Cursor infers stdio from `command`).\nDocs: <https://cursor.com/docs/mcp>\n</details>\n\n<details>\n<summary><b>Windsurf</b></summary>\n\n`~/.codeium/windsurf/mcp_config.json`:\n\n```json\n{\n  \"mcpServers\": {\n    \"selvedge\": { \"command\": \"selvedge-server\" }\n  }\n}\n```\n\nWindsurf hot-reloads the file — no restart needed. The in-app\n**Plugins → View raw config** button opens the exact file Cascade reads.\nDocs: <https://docs.windsurf.com/windsurf/cascade/mcp>\n</details>\n\n<details>\n<summary><b>Codex CLI</b></summary>\n\n`~/.codex/config.toml`:\n\n```toml\n[mcp_servers.selvedge]\ncommand = \"selvedge-server\"\n```\n\nOr run `codex mcp add selvedge -- selvedge-server`.\nDocs: <https://developers.openai.com/codex/config-reference>\n</details>\n\n<details>\n<summary><b>Gemini CLI</b></summary>\n\n`~/.gemini/settings.json` (or `.gemini/settings.json` per project):\n\n```json\n{\n  \"mcpServers\": {\n    \"selvedge\": { \"command\": \"selvedge-server\" }\n  }\n}\n```\n\nOr run `gemini mcp add -s user selvedge selvedge-server`.\nDocs: <https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md>\n</details>\n\n<details>\n<summary><b>Any other MCP client</b></summary>\n\nMost clients share the same JSON shape — point yours at:\n\n```json\n{\n  \"mcpServers\": {\n    \"selvedge\": { \"command\": \"selvedge-server\" }\n  }\n}\n```\n\nIf `selvedge-server` isn't found, use its absolute path (`which\nselvedge-server`).\n</details>\n\n---\n\n## How it works\n\nSelvedge runs as an MCP server. AI agents in tools like Claude Code call\nSelvedge's tools as they work — logging structured change events to a local\nSQLite database.\n\nEach event records:\n- **What** changed (entity path, change type, diff)\n- **When** (timestamp)\n- **Who** (agent, session ID)\n- **Why** (reasoning — captured from the agent's context in the moment)\n- **Where** (git commit, project)\n\nThe diff is git's job. The *why* is Selvedge's.\n\n---\n\n## Selvedge tracks its own history\n\nThis repo dogfoods Selvedge: its `.selvedge/selvedge.db` is committed, so a\nfresh clone ships with Selvedge's own why-history. Clone it and ask why any\npart of Selvedge changed:\n\n```bash\ngit clone https://github.com/masondelan/selvedge\ncd selvedge\nselvedge status                       # recent changes to Selvedge itself\nselvedge search \"telemetry\"           # why the opt-in heartbeat shipped\nselvedge blame selvedge/semantic.py   # why semantic search was added\n```\n\nEvery event was logged by the agents that built Selvedge — the same\n`log_change` calls this README asks you to make in your own project.\n\n---\n\n## Entity path conventions\n\n```\nusers.email           DB column (table.column)\nusers                 DB table\nsrc/auth.py::login    Function in a file (path::symbol)\nsrc/auth.py           File\napi/v1/users          API route\ndeps/stripe           Dependency\nenv/STRIPE_SECRET_KEY Environment variable\n```\n\nPrefix queries work everywhere: `users` returns `users`, `users.email`,\n`users.created_at`, and any other entity under the `users.` namespace.\n\n---\n\n## MCP tools\n\nWhen connected as an MCP server, Selvedge exposes:\n\n| Tool | Description |\n|------|-------------|\n| `log_change` | Record a change event with entity, diff, and reasoning. `rename_from` + `change_type=\"rename\"` records the dual-event rename pattern; `change_type=\"supersede\"` re-opens a reverted decision (append-only); optional `constraint` / `stale_when` keep the decision's principle and its invalidation condition queryable |\n| `diff` | History for an entity or entity prefix, each row annotated with `superseded_by` |\n| `blame` | Most recent change + context for an exact entity, plus the derived decision `status` (active / reverted / reopened) |\n| `history` | Filtered history across all entities |\n| `changeset` | All events grouped under a named feature/task slug |\n| `search` | Full-text search across all events |\n| `prior_attempts` | Prior change attempts on an entity + inferred outcome (tried → reverted → re-opened) — call it before editing. Optional `fuzzy` query adds semantically similar records (needs the `semantic` extra; falls back to substring) |\n| `stale_decisions` | Decisions due for a revisit: past their `revisit_after` and still in active use (`flag=\"revisit_due\"`), or whose `stale_when` condition matched a later change (`flag=\"review_suggested\"`) |\n\n---\n\n## CLI reference\n\n```\nselvedge init [--path PATH]               Initialize in project\nselvedge status                           Recent activity summary\nselvedge diff ENTITY [--limit N]          Change history for entity\nselvedge blame ENTITY                     Most recent change + context\nselvedge history [--since SINCE]          Browse all history\n              [--entity ENTITY]\n              [--project PROJECT]\n              [--changeset CS]\n              [--summarize]\n              [--limit N]\nselvedge changeset [CHANGESET_ID]         Show events in a changeset\n                  [--list]                or list all changesets\n                  [--project NAME]\n                  [--since SINCE]\nselvedge search QUERY [--limit N]         Full-text search\nselvedge prior-attempts ENTITY            Prior attempts + inferred outcome,\n                       [--description T]   with the tried → reverted →\n                       [--all]             re-opened trail + status line\n                       [--window 7d]       (--all widens recall)\n                       [--fuzzy TEXT]      add semantic matches (needs the\n                                           semantic extra; substring fallback)\nselvedge supersede ENTITY                 Re-open a reverted decision —\n                  --reasoning TEXT         append-only, links the prior\n                  [--constraint TEXT]      reverted event (or --supersedes ID)\n                  [--stale-when TEXT]\n                  [--supersedes ID]\nselvedge index [--model NAME]             Build/update the optional semantic\n              [--json]                     embeddings index (selvedge[semantic])\nselvedge stale [--entity ENTITY]          Decisions due for a revisit: past\n              [--project NAME]            revisit_after + still in use, or\n              [--agent NAME]              stale_when matched by a later change\n              [--json]                    (\"review suggested\")\nselvedge stats [--since SINCE]            Tool call coverage report (per-tool, per-agent)\nselvedge doctor [--json]                  Health check: DB path, schema, hook, MCP wiring\nselvedge install-hook [--path PATH]       Install git post-commit hook\n                     [--window MIN]       (default 60 minutes)\nselvedge backfill-commit --hash HASH      Backfill git_commit on recent events\n                        [--window MIN]    (default 60 minutes)\nselvedge import PATH                      Import migrations (SQL / Alembic) or\n              [--format auto|sql|         an Agent Trace file (agent-trace)\n                 alembic|agent-trace]\n              [--from-git]                or walk git history for reverts:\n              [--since REF|DATE]          revert-message commits + deletions\n              [--project NAME]            become change_type=\"revert\" events\n              [--dry-run]                 (idempotent on commit + entity)\nselvedge export [--format json|csv|       Export history (agent-trace =\n                 markdown|agent-trace]      Agent Trace v0.1.0 records;\n                                            markdown = reviewable digest)\n              [--since SINCE]\n              [--entity ENTITY]\n              [--ndjson]                  agent-trace: one record per line\n              [--collapse-by-session]     agent-trace: merge a session into one\n              [--output FILE]\nselvedge log ENTITY CHANGE_TYPE           Manually log a change\n             [--diff TEXT]                CHANGE_TYPE: add, remove, modify,\n             [--reasoning TEXT]           rename, retype, create, delete,\n             [--agent NAME]               index_add, index_remove, migrate,\n             [--commit HASH]              revert, supersede\n             [--project NAME]\n             [--changeset CS]\n             [--revisit-after WHEN]       ISO date or offset (e.g. 90d)\n             [--rename-from OLD]          OLD path when CHANGE_TYPE is 'rename'\n             [--constraint TEXT]          the principle behind the decision\n             [--stale-when TEXT]          what would invalidate it\n             [--supersedes ID]            with CHANGE_TYPE 'supersede'\nselvedge migrate-paths                    Re-canonicalize stored entity paths\n                      [--apply]           (dry-run by default; --apply writes)\n                      [--json]\n```\n\nAll read commands support `--json` for machine-readable output.\n\n**Relative time in `--since`:**\n- `15m` → last 15 minutes (`m` = minutes)\n- `24h` → last 24 hours\n- `7d` → last 7 days\n- `5mo` → last 5 months (`mo` or `mon` = months)\n- `1y` → last year\n\nUnparseable inputs (e.g. `--since yesterday`) exit with a clear error\nrather than silently returning empty results. ISO 8601 timestamps\nare also accepted and normalized to UTC.\n\n---\n\n## Configuration\n\n| Method | Format | Example |\n|--------|--------|---------|\n| Env var | `SELVEDGE_DB=/path/to/db` | Per-session override |\n| Project init | `selvedge init` | Creates `.selvedge/selvedge.db` in CWD |\n| Global fallback | `~/.selvedge/selvedge.db` | Used if no project DB found |\n| Hook watch globs | `.selvedge/config.toml` | `[hook]`<br>`watch_globs = [\"**/migrations/**\", \"db/**/*.sql\"]` — replaces the enforcement hook's default schema/migration globs |\n| Project settings | `.selvedge/config.toml` | See the key list below — retention, size bounds, redaction patterns |\n| Global settings | `~/.selvedge/config.toml` | Same keys; the project file wins where both set one |\n| Hook bypass | `SELVEDGE_HOOK_DISABLE=1` | Disables the PreToolUse enforcement hook for the shell |\n| Semantic extra | `pip install \"selvedge[semantic]\"` | Enables `selvedge index` + `prior-attempts --fuzzy` (local model2vec embeddings, ~30 MB; core never depends on it) |\n\n### `.selvedge/config.toml`\n\nEvery key is optional; a missing file means the defaults below. Precedence is\n**CLI flag → env var → project `.selvedge/config.toml` → global\n`~/.selvedge/config.toml` → default**. `SELVEDGE_DB` is the one exception: it\nalways wins for database resolution, because the config file is found *by*\nresolving that path. `selvedge doctor` prints the effective value and the step\nthat produced it for every setting.\n\n```toml\nretention_days_events     = 0       # 0 = never delete events (the default)\nretention_days_tool_calls = 90      # local telemetry retention\nbackup_keep_last          = 7\ndiff_bytes                = 65536   # truncate oversized diffs at log time\nreasoning_bytes           = 32768   # truncate oversized reasoning\ndb_size_warn_mb           = 500     # doctor warns above this\nstale_days                = 0       # 0 = off\ndigest_max_bytes          = 4096    # cap on the session-start digest\nredaction_patterns        = []      # extra secret shapes to warn about\n\n[hook]\nwatch_globs = [\"**/migrations/**\", \"db/**/*.sql\"]\n```\n\nEvery key also has an env override (`SELVEDGE_DIFF_BYTES`,\n`SELVEDGE_RETENTION_DAYS_EVENTS`, …).\n\n---\n\n## Reviewing captured intent in a pull request\n\n`.selvedge/selvedge.db` is a SQLite file, so the reasoning inside it doesn't\nshow up in a diff. Export a Markdown digest next to it and commit both:\n\n```bash\nselvedge export --format markdown -o .selvedge/DECISIONS.md\ngit add .selvedge/\n```\n\nThe digest is grouped by entity with **reverted decisions first**, and it is\ndeterministic — regenerating with no new events produces a zero-line diff, so\nit stays reviewable instead of becoming noise everyone learns to skip. Heading\nanchors derive from the entity path, so links into it keep working as it\ngrows. Regenerate it in the same commit as the code, or from a pre-commit\nhook.\n\n---\n\n## Coverage checking\n\nWondering how often your agent actually calls `log_change`? Two ways to check:\n\n```bash\n# Quick summary in the terminal\nselvedge stats\n\n# Cross-reference against git commits\npython scripts/coverage_check.py --since 30d\n```\n\nThe coverage script compares your git log against Selvedge events and shows\nwhich commits have associated change events. Low coverage usually means the\nsystem prompt needs strengthening — see `docs/fallbacks.md` for guidance.\n\n### In CI (GitHub Action)\n\nThe same check ships as the **Selvedge Coverage Check** composite Action, so\nyou can track agent coverage on every push — and optionally fail the build\nwhen it drops:\n\n```yaml\n# .github/workflows/selvedge-coverage.yml\nname: Selvedge coverage\non: [push, pull_request]\njobs:\n  coverage:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0            # full history so commits can be matched\n      - uses: masondelan/selvedge@v0.3.11   # pin to a release tag (or @main for latest)\n        with:\n          since: 30d\n          fail-under: \"0.5\"         # optional: fail below 50% coverage; omit to report only\n```\n\nIt writes a coverage summary to the job summary and exposes `coverage-ratio`,\n`covered`, and `total` as step outputs. The action cross-references your git\nhistory against the Selvedge event log, so the runner needs the project's\n`.selvedge/selvedge.db` (commit it, or restore it before this step) and full\ngit history (`fetch-depth: 0`). Inputs: `since`, `window`, `limit`,\n`fail-under`, `selvedge-version`, `python-version`, `working-directory`,\n`db-path`.\n\n---\n\n## Contributing\n\n```bash\ngit clone https://github.com/masondelan/selvedge\ncd selvedge\npip install -e \".[dev]\"\npytest\n```\n\nSee `CLAUDE.md` for architecture details and the phase roadmap.\n\n---\n\n## License\n\nMIT — see [LICENSE](LICENSE).\n",
  "bytes": 36240,
  "sha": "fbcec8dfd8ac1fb22599c20127e665abf98c0c9d001f198772a47c4798cd24f5",
  "repo_slug": "masondelan/selvedge",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_masondelan_selvedge_4ad7ec50/readme"
}