The full upstream README, mirrored here for reference. Install config, tool schemas, adoption signals, and an original overview live on the Selvedge listing page.
selvedge.sh · PyPI · GitHub
Long-term memory for AI-coded codebases — including what was already tried and rejected.
Line attribution tells you who wrote something. Selvedge tells your agent
what not to write next: the approaches this codebase already tried,
reverted, and why. It's a git blame for AI agents, for the why rather
than which model touched which line — captured live, by the agent, as the
change happens, so nothing downstream has to guess at it.
Selvedge is a local MCP server. AI coding agents (Claude Code, Cursor,
Copilot) call it as they work to log structured change events with
reasoning. Your data stays in a SQLite file under .selvedge/ next to
your code.
Local-first by default, team-server by choice, zero-LLM always.
Six months ago, your AI agent added a column called user_tier_v2. You don't
know why. git blame points to a commit from claude-code with a generated
message that says "Update schema." The session that made the change is long
gone — and so is the prompt that produced it.
With Selvedge, you run this instead:
That reasoning was captured by the agent in the moment — written into Selvedge from the same context that produced the change. Not inferred from the diff afterward by a second LLM. Not a hand-typed commit message.
Selvedge has two audiences. Same tool, same pip install, same SQLite
file under .selvedge/. Different scale of pain.
Teams running long-term, AI-coded codebases.
When the project is big enough that you (or someone else) will touch it
again in six months, twelve months, three years — but most of it was written
by an agent whose context evaporated the day each PR shipped. git blame
tells you what changed. Selvedge tells you why — even after the agent
session, the prompt template, the developer who asked for it, and the model
version are all long gone. This is the original use case: production
codebases, schema decisions, migrations, dependency changes that need an
audit trail that survives turnover.
Solo developers using Claude Code on everyday projects.
Side projects, weekend builds, the small internal tool you keep poking at.
You don't need enterprise governance — you just need to remember why you (or
your agent) did the thing you did yesterday, last week, last sprint. Run
selvedge init once. Add four lines to your CLAUDE.md. From then on,
selvedge blame is muscle memory — a way to talk to your past self when
your past self was an LLM.
If you've ever come back to your own AI-built project and thought "what was this for again?", Selvedge is the missing piece.
Human-written code leaks intent everywhere — commit messages, PR descriptions, inline comments, the Slack thread that preceded it. AI-written code doesn't. The agent has perfect clarity about why it made each decision, but that context lives in the prompt and evaporates when the conversation ends.
Six months later, your team is debugging a schema decision with no trail.
git blame tells you what changed and when. It can't tell you why.
Selvedge captures the why — live, by the agent itself, as the change is made. The diff is git's job. The why is Selvedge's.
Abandoned alternatives are first-class, and the log can prove itself.
Rejections and reverts are now stated outcomes, not inferences.
change_type="reject" records "we considered this and decided against it"
without writing the change — the counterpart to revert for paths never
taken. prior_attempts reads both as a new confidence: "exact" tier; the
old proximity heuristic drops to tiebreaker. And the expires_when column
that shipped dormant in v0.3.8 gets its evaluator: a closed, machine-checkable
grammar — library:NAME>=VERSION, entity:PATH:changes, date:ISO,
manual:LABEL — validated at write time, evaluated locally by
selvedge stale with no network and no LLM. A rejection stored with the
condition that would invalidate it is a decision that knows when to die.
The event log is now tamper-evident. Every logged event gets a SHA-256
chain record in a sidecar table, same transaction, over every field except the
late-bound git_commit (git already witnesses that one). Two new
selvedge verify checks: chain_intact fails hard when a chained row was
edited, deleted, or reordered out-of-band — the check names the exact sequence
number — and chain_coverage warns (never fails) about rows that predate the
chain. Legitimate operations append boundary records instead of breaking the
chain, so migrate-paths and a destructive-gated prune verify clean while a
silent sqlite3 edit does not. selvedge verify --json publishes the
attestation manifest. Honest scope, stated in the module itself: this detects
casual and accidental modification and produces an independently verifiable
export; it is not proof against a motivated local attacker.
Also: the PreCompact reminder now distinguishes "edited with no log" from
"log exists but was truncated," and both hook surfaces have their determinism
pinned byte-for-byte in tests; capture-time nudges suggest recording the
invalidating condition when a reject/revert lands without one;
selvedge supersede gains -d/--diff, --revisit-after, and
--expires-when (#31); and an id-less supersede no longer re-opens every
earlier revert on the path (#30). Tests 984 → 1114.
The memory comes to the agent, and the store gets its dials. Two themes, shipped together because the config half is what the rest needed to read settings from.
Delivery. Selvedge already blocked re-edits of reverted entities. What was missing was delivery when there is nothing to veto. Two new hooks:
Both are quiet when they have nothing to say, size-capped, read-only, and templated. Neither can block anything — PreCompact deliberately declines the veto the hook API offers it. This is the answer to a measured failure mode: "Delivery, Not Storage" (arXiv:2607.20972) recorded a pull-model memory tool going unused entirely (zero voluntary memory operations across 114 turns against a pre-seeded store) while deterministic injection landed every time.
selvedge export --format markdown renders the store as a reviewable
digest to commit next to it, so captured intent shows up in a pull request
instead of hiding inside a binary. Deterministic — regenerating with no new
events is a zero-line diff.
Config. .selvedge/config.toml is now first-class, with a canonical
precedence chain that selvedge doctor prints per setting. It brings:
selvedge prune --include-events — the first path that can delete
captured reasoning, so it needs both a confirmation and
SELVEDGE_DESTRUCTIVE=1. Neither alone is enough, because --yes in a cron
entry defeats a prompt and a shell profile defeats an env var. Events
retention defaults to never.diff_bytes, reasoning_bytes) that truncate loudly
— a marker in the text, a warning at write time, a count in selvedge stats.log_change, extendable via
redaction_patterns, plus a doctor row that scans what's already stored.
Warn, never reject.Also: five review issues closed. The enforcement hook's allow path is
40% faster (33.6 ms → 20.1 ms per gated call) and SELVEDGE_HOOK_DISABLE=1
finally short-circuits before the imports it was documented to skip;
log_change no longer discards revisit_after / constraint / stale_when
on renames and supersedes; the CLI's --json and the MCP tools now return
identical structures; and the Docker image no longer ships the maintainer's
own database. Tests 826 → 984.
AI agents call Selvedge as they work. Selvedge captures the why into a durable, queryable store and emits it back out — as Agent Trace records for cross-tool readers, as observability metadata that links into Sentry/Datadog stack traces, and as compliance artifacts for SOC 2 and EU AI Act audits.
Selvedge does not replace git (line-level what/when), PR review
tools (review-time quality), agent observability (LLM call traces),
or general-purpose code-host AI features. It sits between them — the
provenance-as-first-class-citizen layer that everything else
references.
There's a fast-growing "git blame for AI agents" category. Here's where Selvedge fits — and where it deliberately doesn't.
| Rejected paths | Reasoning source | Granularity | Mechanism | Grouping | Storage | |
|---|---|---|---|---|---|---|
| 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 |
| 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/ |
| AgentDiff (sunilmallya) | 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 |
| AgentDiff (codeprakhar25) | None | ed25519-signed cross-agent provenance | Line | Per-agent editor hooks + git hooks (sign at commit) | None | Signed traces in git refs |
| Origin | 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 |
| Git AI | None | Attribution metadata | Line | Agent-invoked checkpoint → Git notes at commit | None | Git notes |
| BlamePrompt | None | Prompt receipts — prompt, cost, tools; no stated rationale | Line | Agent-lifecycle hooks + post-commit hook | None | Git notes |
Why "rejected paths" matter — the one that isn't copyable. The expensive
failure isn't forgetting why a column exists. It's an agent confidently
re-implementing something the team already killed for a good reason, six
months after everyone who knew that left the context window. None of the
line-attribution tools above surface rejected paths at all, and it isn't a
feature gap they can close in a release — a line-oriented store has no notion
of an entity that persisted across a try → revert → retry cycle. See
docs/demos/prior-attempts.md.
Why determinism matters. Selvedge's reasoning is the agent's own intent, written from the same context window that produced the change. There is no model anywhere in the storage or retrieval path, so the same query returns the same answer today and in two years, across model versions. Tools that infer reasoning post-hoc are running a second LLM that never saw the original prompt: what it produces is paraphrase, and re-running it can produce different categories for the same change. As a Hacker News commenter put it about a competing approach, "grep won't find your commit because you rejected 'oauth-library'… unless there is deterministic enforcement" (0x457).
Determinism alone is no longer a separator — OpenLore is deterministic-native too, and says so. The compound that separates is append-only testimony: reasoning the agent wrote itself, kept in a store where a rejection is a first-class record rather than an inactive status to be swept up.
Why "entity-level" matters. Most tools attribute lines. Selvedge
attributes things you actually search for: users.email,
env/STRIPE_SECRET_KEY, api/v1/checkout, deps/stripe. The first
question after git blame is usually "what's the history of this column",
not "what's the history of lines 40–48 of users.py".
Why "captured live" matters. Not a differentiator on its own — every tool
here claims some flavour of it — but it's the mechanism that makes the
reasoning trustworthy. Writing at the moment of the change, from the context
that produced it, is the reason there's no second model in the path to
hallucinate an explanation. An empty reasoning field is itself an honest
signal: the agent didn't have one.
Comparison current as of 2026-08-05; OpenLore at v2.1.8 / 265★, verified against its source. Corrections welcome as an issue.
Why "changesets" matter. A Stripe billing rollout touches the users
table, two new env vars, three new API routes, one dependency, and four
functions across the codebase. Tag every event with changeset:add-stripe-billing
and you can pull the entire scope back later — even if the original PR was
broken into eight smaller ones over a month.
Selvedge ↔ Agent Trace. Agent Trace is an
open AI code-attribution wire format published by Cursor (RFC, Jan 2026). Its
original GitHub home went 404 in August 2026 and the multi-vendor momentum
behind it has faded, but the spec and schema still resolve at agent-trace.dev,
frozen at v0.1.0. Since v0.3.9, selvedge export --format agent-trace
emits Agent Trace v0.1.0 records and selvedge import --format agent-trace
reads them back — a portable, documented interchange format for file/line AI
attribution, with reasoning and entity-level provenance carried in each
record's dev.selvedge metadata. The mapping is in
docs/agent-trace-interop.md; Selvedge vendors
the schema and has no runtime dependency on the upstream project.
Two commands, inside Claude Code. No prior pip install — the plugin
bootstraps the server itself via uvx (or pipx):
That's the whole agent-facing surface in one step:
log_change, prior_attempts, blame,
diff, history, changeset, search, stale_decisions);prior_attempts has been checked this session, with the prior
reasoning in the block message;/selvedge:status, /selvedge:blame <entity>,
/selvedge:history, /selvedge:prior-attempts <entity>.The store (.selvedge/selvedge.db) creates itself on the first logged change.
Two optional extras stay CLI-side: the post-commit hook that stamps each event
with its commit hash (selvedge install-hook), and — if you want the
selvedge command on your own shell PATH — pip install selvedge, which the
launcher then prefers over uvx for an exact pinned version.
Plugin or
selvedge setupfor Claude Code? Pick one. Both wire the MCP server; running both registers it twice. The plugin is the lighter path and the one that updates itself. If you're on the plugin and only want the post-commit commit-hash stamping, runselvedge install-hookon its own.
selvedge setupCursor, Copilot, Windsurf, Codex CLI, Gemini CLI, and the rest:
That's it. selvedge setup is an interactive wizard: it detects which AI
tools you have (Claude Code, Cursor, Copilot), writes the MCP entry into
each one's config, drops the canonical agent-instructions block into your
project's prompt file (CLAUDE.md / .cursorrules /
copilot-instructions.md), installs the PreToolUse enforcement hook into
.claude/settings.json (Claude Code only — blocks schema/migration edits
until prior_attempts has been checked; --skip-enforcement-hook to opt
out), runs selvedge init, and installs the post-commit hook. Every
modified file gets a .bak written next to it before any change reaches
disk. Re-running is a no-op.
For CI bootstrap or devcontainer.json postCreateCommand:
Verify the wiring — open a second terminal in the same project:
Make any change in your AI tool — add a column, rename a function, add an
env var. selvedge watch should print the new event within a second of
the agent calling log_change. If nothing arrives, run selvedge doctor
for a single-command health check that tells you which step is silently
broken.
Query your history:
If you don't want to run the wizard, the four manual steps it automates:
1. Initialize in your project
2. Register the MCP server
Selvedge is a standard stdio MCP server, so it works with any MCP client — Claude Code, Cursor, Windsurf, Codex CLI, Gemini CLI, and more. See Works with any MCP client for the exact config per client. For Claude Code:
3. Tell your agent to use it
Point --install at whichever prompt file your client reads — the block
itself is identical across clients:
| Client | Prompt file |
|---|---|
| Claude Code | CLAUDE.md |
Codex CLI (and other AGENTS.md-aware tools) | AGENTS.md |
| Cursor | .cursor/rules/selvedge.md (or legacy .cursorrules) |
| Gemini CLI | GEMINI.md |
This installs the canonical agent-instructions block, sentinel-bracketed
(<!-- selvedge:start --> / <!-- selvedge:end -->) so future
--install calls update the bracketed region without disturbing
anything else in the file. Or pipe it:
Prefer to copy-paste? The same block is one click away on the website: selvedge.sh/prompt-block — with a copy button and notes on what your agent does with it.
4. Install the post-commit hook
That's the same four steps the wizard runs.
Selvedge is a standard stdio MCP server — its launch command is
selvedge-server, put on your PATH by pip install selvedge. Any
MCP-capable client can run it. Pick yours:
Or commit a project-level .mcp.json so your whole team gets it:
.cursor/mcp.json (project) or ~/.cursor/mcp.json (global):
Cursor's newer schema also accepts an explicit "type": "stdio"; the
command-only form works too (Cursor infers stdio from command).
Docs: https://cursor.com/docs/mcp
~/.codeium/windsurf/mcp_config.json:
Windsurf hot-reloads the file — no restart needed. The in-app Plugins → View raw config button opens the exact file Cascade reads. Docs: https://docs.windsurf.com/windsurf/cascade/mcp
~/.codex/config.toml:
Or run codex mcp add selvedge -- selvedge-server.
Docs: https://developers.openai.com/codex/config-reference
~/.gemini/settings.json (or .gemini/settings.json per project):
Or run gemini mcp add -s user selvedge selvedge-server.
Docs: https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md
Most clients share the same JSON shape — point yours at:
If selvedge-server isn't found, use its absolute path (which selvedge-server).
Selvedge runs as an MCP server. AI agents in tools like Claude Code call Selvedge's tools as they work — logging structured change events to a local SQLite database.
Each event records:
The diff is git's job. The why is Selvedge's.
This repo dogfoods Selvedge: its .selvedge/selvedge.db is committed, so a
fresh clone ships with Selvedge's own why-history. Clone it and ask why any
part of Selvedge changed:
Every event was logged by the agents that built Selvedge — the same
log_change calls this README asks you to make in your own project.
Prefix queries work everywhere: users returns users, users.email,
users.created_at, and any other entity under the users. namespace.
When connected as an MCP server, Selvedge exposes:
| Tool | Description |
|---|---|
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 |
diff | History for an entity or entity prefix, each row annotated with superseded_by |
blame | Most recent change + context for an exact entity, plus the derived decision status (active / reverted / reopened) |
history | Filtered history across all entities |
changeset | All events grouped under a named feature/task slug |
search | Full-text search across all events |
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) |
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") |
All read commands support --json for machine-readable output.
Relative time in --since:
15m → last 15 minutes (m = minutes)24h → last 24 hours7d → last 7 days5mo → last 5 months (mo or mon = months)1y → last yearUnparseable inputs (e.g. --since yesterday) exit with a clear error
rather than silently returning empty results. ISO 8601 timestamps
are also accepted and normalized to UTC.
| Method | Format | Example |
|---|---|---|
| Env var | SELVEDGE_DB=/path/to/db | Per-session override |
| Project init | selvedge init | Creates .selvedge/selvedge.db in CWD |
| Global fallback | ~/.selvedge/selvedge.db | Used if no project DB found |
| Hook watch globs | .selvedge/config.toml | [hook]watch_globs = ["**/migrations/**", "db/**/*.sql"] — replaces the enforcement hook's default schema/migration globs |
| Project settings | .selvedge/config.toml | See the key list below — retention, size bounds, redaction patterns |
| Global settings | ~/.selvedge/config.toml | Same keys; the project file wins where both set one |
| Hook bypass | SELVEDGE_HOOK_DISABLE=1 | Disables the PreToolUse enforcement hook for the shell |
| Semantic extra | pip install "selvedge[semantic]" | Enables selvedge index + prior-attempts --fuzzy (local model2vec embeddings, ~30 MB; core never depends on it) |
.selvedge/config.tomlEvery key is optional; a missing file means the defaults below. Precedence is
CLI flag → env var → project .selvedge/config.toml → global
~/.selvedge/config.toml → default. SELVEDGE_DB is the one exception: it
always wins for database resolution, because the config file is found by
resolving that path. selvedge doctor prints the effective value and the step
that produced it for every setting.
Every key also has an env override (SELVEDGE_DIFF_BYTES,
SELVEDGE_RETENTION_DAYS_EVENTS, …).
.selvedge/selvedge.db is a SQLite file, so the reasoning inside it doesn't
show up in a diff. Export a Markdown digest next to it and commit both:
The digest is grouped by entity with reverted decisions first, and it is deterministic — regenerating with no new events produces a zero-line diff, so it stays reviewable instead of becoming noise everyone learns to skip. Heading anchors derive from the entity path, so links into it keep working as it grows. Regenerate it in the same commit as the code, or from a pre-commit hook.
Wondering how often your agent actually calls log_change? Two ways to check:
The coverage script compares your git log against Selvedge events and shows
which commits have associated change events. Low coverage usually means the
system prompt needs strengthening — see docs/fallbacks.md for guidance.
The same check ships as the Selvedge Coverage Check composite Action, so you can track agent coverage on every push — and optionally fail the build when it drops:
It writes a coverage summary to the job summary and exposes coverage-ratio,
covered, and total as step outputs. The action cross-references your git
history against the Selvedge event log, so the runner needs the project's
.selvedge/selvedge.db (commit it, or restore it before this step) and full
git history (fetch-depth: 0). Inputs: since, window, limit,
fail-under, selvedge-version, python-version, working-directory,
db-path.
See CLAUDE.md for architecture details and the phase roadmap.
MIT — see LICENSE.