Your AI writes the code. DiffMind makes sure it explains why.
Vibe coding lets AI ship features fast. DiffMind makes sure you still own the project.
When you tell your AI agent "add user authentication", it writes the code and the feature works. Three weeks later you want to change the logout flow, but you don't know where sessions are stored, how token refresh works, or why it didn't use OAuth. You've become a stranger to your own codebase.
This is the hidden cost of vibe coding: you know what features exist, but not why they were designed this way, what trade-offs were made, or how to safely change them. You lose ownership. Maintenance becomes archaeology. Technical debt piles up because you're afraid to touch code you don't understand.
DiffMind closes this gap. It's an MCP server for Claude Code that forces AI agents to explain every decision — not just "what I did", but "why this approach", "what I rejected", and "what trade-offs I accepted". You get the speed of AI-assisted development with the deep understanding of hand-written code.
You: "Add email/password login with session-based authentication"
Claude (via DiffMind):
- Calls
start_session("实现用户登录功能:邮箱+密码,带会话保持") - Writes code across three files...
- Calls
explain_change():- Why: "Passwords are hashed with bcrypt (cost 12) rather than stored in plaintext, so a database leak doesn't hand over usable credentials. Auth state is kept in a server-side session keyed by an httpOnly cookie instead of a JWT: for an MVP with a single backend we don't need statelessness, and sessions let us revoke a login instantly."
- Rejected: JWT (stateless is a benefit we don't need yet), OAuth (overkill for MVP), SHA-256 with static salt (fast hashes are wrong tool for passwords)
- Trade-offs: "Sessions require server-side storage, so the backend is no longer stateless — horizontal scaling later needs Redis, not the in-memory store"
- Verification: "npm test -- auth/login → 4 passing; manual POST /login with seeded user returns 200 + Set-Cookie"
You: (end conversation)
DiffMind Stop hook displays:
● created ◐ modified ⊗ deleted ○ unchanged
○ Express [unchanged]
├─● loginHandler [created]
│ ├─● validateInput [created]
│ ├─● User.findByEmail [created]
│ ├─○ bcrypt.compare [unchanged]
│ └─● SessionService.create [created]
└─● sessionMiddleware [created]
Three weeks later:
You: "Why didn't we use JWT for auth?"
Claude: (calls search_changes("authentication") → recalls stored explanation)
"Sessions over JWT because for an MVP with a single backend we don't need statelessness, and sessions let us revoke a login instantly by deleting a row — JWT would require building token refresh/blacklist machinery. The trade-off: the backend now holds state, so horizontal scaling later needs Redis."
Result: You understand past decisions without archaeology.
DiffMind keeps documentation costs out of your main conversation. Your coding agent delegates explanation writing to a subagent: the subagent reads the diff, composes the full explanation, and calls explain_change itself, so the prose, diff reading, and quality-gate revisions never touch your context—you get back one line. Session digests display straight to your terminal via the Stop hook, which never enters model context at all.
What stays out of your context:
- Explanation prose (150-800 tokens each)
- Diff reading for explanations (varies)
- Quality-gate retry loops (unpredictable)
- Digest markdown (500-2,000 tokens)
What still costs context:
- Task delegation call + rationale seed (50-150 tokens)
- One-line result (10-20 tokens)
DiffMind saves tokens in realistic usage (4+ explanations per session, or any recall/onboarding). After 4-5 explanations or a single recall query, you're net positive on tokens; for onboarding to an unfamiliar codebase, the project overview saves 10k-30k tokens of cold exploration.
| Git commits | Chat history | Code review | DiffMind | |
|---|---|---|---|---|
| What changed | ✅ | partial | ✅ | ✅ |
| Why this approach | ❌ | buried | sometimes | ✅ enforced |
| Rejected alternatives | ❌ | lost | rarely | ✅ required |
| Trade-offs accepted | ❌ | ❌ | sometimes | ✅ required |
| Maintains ownership after AI coding | ❌ | ❌ | ❌ | ✅ |
| Quality enforced at write | ❌ | ❌ | human effort | ✅ blocked |
| Searchable + commitable | ✅ | ❌ | ❌ | ✅ |
Git history tells you what changed. Chat logs record a conversation that's forgotten next session. Code review catches problems after the fact, when changing course is expensive.
DiffMind is the only tool that captures the AI's reasoning before the code is saved — and rejects it if the reasoning is vague.
You tell Claude "add user authentication" and boom — feature done. Three weeks later you need to modify the logout flow, but:
- Where are sessions stored? (Redis? Memory? Database?)
- Why didn't we use OAuth? (Security? Complexity? Time?)
- How does token refresh work? (Auto? Manual? Interval?)
You've become a stranger to your own codebase. The AI knew the answers when it wrote the code. You never did.
DiffMind forces the AI to explain:
- Why this approach — rationale with substance, not filler
- What was rejected — alternatives considered and why they didn't fit
- What trade-offs — nothing is free, what did we sacrifice?
- How it was verified — testing, edge cases, confidence level
And it enforces quality:
- Blocks explanations with filler phrases ("better maintainability", "cleaner code")
- Detects when rationale just repeats the summary
- Requires alternatives for structural changes
- Demands verification for "verified" confidence claims
Result: You get AI speed + human understanding. Maintenance becomes informed decision-making, not archaeology.
Unlike static documentation tools, DiffMind builds a profile of what you don't know:
- Detects knowledge gaps from patterns: custom requirements with "step by step" / "eli5" / "basic explanation", or recalling the same topic 3+ times
- Tracks topics you repeatedly struggle with (not your strengths)
- Remembers your preferred explanation style
Result: Over time, explanations become increasingly tailored to fill your gaps, not generic ones.
Example: You struggle with Redis caching. DiffMind notices you've recalled "Redis" explanations 4 times. Next time a change involves caching, the explanation includes:
- "Redis is an in-memory data store (like a super-fast database in RAM)"
- Step-by-step: how the cache invalidation works
- Visual analogy: "Think of it like a notepad next to your desk vs. a filing cabinet"
The more you use it, the better it gets at explaining to you.
Developer starts a session → AI writes code → AI calls explain_change()
↓ ↓
goal recorded rationale + rejected alternatives + trade-offs
pass quality gate → saved to .diffmind/
↓
session closed → digest Markdown generated
call chain diff (Mermaid)
commit message drafted
Every explanation lives in .diffmind/ — plain JSON + Markdown, commitable alongside
your code, diffable in PRs, readable without any tooling.
npm install -g diffmindgit clone https://github.com/akay1121/DiffMind.git
cd DiffMind
npm install
npm run build
npm link # Makes `diffmind` command available globallycd your-project
# 1. Add MCP server to Claude Code settings
# Merge hooks/settings-fragment.json into .claude/settings.jsonEdit your project's .claude/settings.json:
{
"hooks": {
"PreToolUse": [{ "matcher": "Write|Edit", "hooks": [{ "type": "command", "command": "diffmind session auto-start" }] }],
"Stop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "diffmind session auto-close" }] }]
},
"mcpServers": {
"diffmind": {
"command": "npx",
"args": ["-y", "diffmind"],
"env": { "DIFFMIND_ROOT": "${workspaceFolder}" }
}
}
}# 2. Add CLAUDE.md template
cp /path/to/DiffMind/templates/CLAUDE.md ./CLAUDE.md
# 3. Install git hook (optional but recommended)
diffmind install-git-hook
# 4. Start using Claude Code — DiffMind is now active!echo "/.diffmind/sessions/" >> .gitignore # optional: exclude raw session files
# explanations/ and digests/ are worth committing — that's the point
git add .diffmind/# Clone and install
git clone https://github.com/akay1121/DiffMind.git
cd DiffMind
npm install
npm run build
# In your project
cd /path/to/your-project
# Merge settings
cat /path/to/DiffMind/hooks/settings-fragment.json >> .claude/settings.json
# Copy CLAUDE.md template
cp /path/to/DiffMind/templates/CLAUDE.md ./CLAUDE.md
# Start using
# Now when you use Claude Code in this project, DiffMind is activeYou: "Add JWT refresh token support to the authentication system"
Claude (via DiffMind):
- Calls
start_session("Add JWT refresh token support") - Calls
get_conventions()to read your project rules - Writes code...
- Calls
explain_change():- Intent: "Add JWT refresh logic to prevent session expiration"
- Rationale: "Users were getting logged out every 15min. JWT refresh extends sessions by issuing new tokens before expiry. Checked existing AuthGuard, added interceptor to catch 401 responses and trigger refresh flow automatically."
- Rejected: ["OAuth flow (overkill for internal app)", "Server-side sessions (stateful, breaks horizontal scaling)"]
- Trade-offs: ["Slightly more complex client logic vs. better UX", "Extra network request on refresh vs. seamless experience"]
- Verification: ["Tested with expired token → refresh triggers automatically", "Confirmed refresh endpoint returns new token with extended expiry"]
Result:
.diffmind/explanations/x-20260730-abc123.jsoncreated- Quality gate passed (no filler phrases, sufficient detail)
- Session logged
You: (end conversation)
DiffMind Stop hook triggers:
╔══════════════════════════════════════════════════════╗
║ Choose explanation types (↑↓ move, Space select, ║
║ Enter confirm): ║
║ ║
║ > [✓] Natural language (why/what/tradeoffs) ║
║ [ ] Architecture diagram ║
║ [✓] Call chain diff (mermaid) ║
║ [ ] Git commit message only ║
╚══════════════════════════════════════════════════════╝
╔══════════════════════════════════════════════════════╗
║ Custom explanation requirements (optional): ║
║ e.g., "explain in Chinese", "focus on performance" ║
╚══════════════════════════════════════════════════════╝
> explain in Chinese, focus on security implications
Result:
.diffmind/digests/s-20260730-xyz.mdgenerated with Chinese explanation- Call chain Mermaid diagram showing AuthGuard → TokenService → RefreshAPI
$ git add .
$ git commit
# prepare-commit-msg hook runs diffmind git-message
# Your commit message is pre-filled:Add JWT refresh token support
Session: s-20260730T143022-abc123
Closed: 2026-07-30T14:45:00Z
Changes (DiffMind):
- Add JWT refresh logic to prevent session expiration (structural)
Why: Users were getting logged out every 15min. JWT refresh extends sessions...
- Update AuthGuard to handle token refresh flow (local)
Why: Need to intercept 401 responses and trigger refresh before retrying...
Trade-offs:
- Slightly complex client logic vs. better UX
- Extra network request on refresh vs. seamless experience
Verification:
- Tested with expired token → refresh triggers automatically
- Confirmed refresh endpoint returns new token with extended expiry
Open threads: None
See: .diffmind/digests/s-20260730T143022-abc123.md
# Via MCP tools (in Claude Code)
recall_change("x-20260730-abc123")
search_changes("authentication")
list_changes(limit=10, scale="architectural")
# Via CLI
diffmind --helpAfter 10 sessions:
$ diffmind profile show
User Profile
────────────
Knowledge Level: intermediate
Preferred Language: zh (Chinese)
Preferred Explanation Types:
- natural_language: 8 times
- call_chain_diff: 6 times
- git_commit_message: 10 times
- architecture_diagram: 2 times
Focus Areas: security, performance, error-handling
Quality Metrics:
- Violation rate: 5% (healthy)
- Avg rationale length: 180 chars (good)
Last updated: 2026-07-30T16:00:00Z# Generate initial overview
$ diffmind overview init
Analyzing 47 explanations...
Generated:
- .diffmind/overview/README.md (project purpose, key modules)
- .diffmind/overview/architecture.md (call chains, trade-offs)
- .diffmind/overview/decisions/jwt-refresh.md
- .diffmind/overview/decisions/redis-cache.md
# Enable auto-updates
$ diffmind overview enable
# Now on every commit, the overview updates automatically- Open Claude Code
- "Add email verification to signup flow"
- DiffMind auto-starts session
- Claude reads conventions, writes code, explains changes
- Quality gate blocks: "Rationale contains filler phrase: 'better security'"
- Claude revises: "Email verification prevents bot signups and ensures valid contact info for password resets. Checked existing UserService, added SendGrid integration with 6-hour token expiry."
- Explanation saved
- Check
.diffmind/digests/s-20260730-morning.md - See: why email verification, what alternatives (SMS, phone), trade-offs
- Understand the decisions without re-reading code
git commit- Commit message auto-populated with DiffMind digest
- User profile evolves in background
- Overview docs updated
- They read
.diffmind/overview/README.md - Understand project architecture in 5 minutes
- Check
.diffmind/overview/decisions/for past architectural choices - Start contributing with context
| Tool | When to call |
|---|---|
start_session(goal) |
Before making any changes |
get_conventions() |
Before touching existing code |
explain_change(...) |
After every meaningful edit |
close_session(sessionId, summary) |
When done for this conversation |
recall_change(id) |
Look up a past explanation |
list_changes(...) |
Browse recent history |
start_convention_interview() |
First time on a new project |
save_conventions(...) |
Persist project conventions |
DiffMind blocks or warns when explanations are vague. You can't save:
- A rationale under the minimum length for the change scale
- A rationale that just repeats the summary (Jaccard similarity > 0.7)
- Filler phrases: "better maintainability", "cleaner code", "improved readability"
- A
structuralorarchitecturalchange with no rejected alternatives confidence: "verified"with no verification steps listed
Warnings (non-blocking) catch things like missing call chain on structural changes, suspiciously many files for a "local" scale, or opening the rationale with an action verb.
DiffMind automatically enhances your commit messages with session context:
diffmind install-git-hookNow when you commit after a DiffMind session, the commit message includes:
- Session summary
- Key explanations and their rationale
- Trade-offs and verification steps
- Link to the full digest
This makes git log a searchable knowledge base of why decisions were made
(git log --grep "DiffMind session"). The hook only touches ordinary commits —
it leaves merges, squashes, amends, and -m messages alone, and does nothing
when there's no closed session or DiffMind isn't installed.
Want the full picture before installing? A worked walkthrough of implementing login
takes a single request — "帮我完成登录功能" — through the whole DiffMind workflow: session
start, three explain_change calls with genuine trade-offs (bcrypt over plaintext, sessions
over JWT, a deliberately vague 401 to block email enumeration), the generated digest with its
Mermaid call chain diff, the terminal box, the drafted commit message, and — three weeks later —
recall_change handing the reasoning back just as the developer needs it to add OAuth.
.diffmind/
├── conventions.json project coding conventions
├── sessions/ one JSON per session (start → close)
├── explanations/ one JSON per explain_change call
└── digests/ Markdown digest per session, with Mermaid call chain diff
All files are plain text (JSON + Markdown) that you can Read directly or grep. digests/ is the main artifact for code review.
- Phase 1 — MCP server, 9 tools, quality gate, session model
- Phase 1.5 —
diffmindCLI, Claude Code hook auto-trigger, terminal explanation picker - Phase 2 — Call chain diff visualization (Mermaid, changed nodes in red)
- Phase 2.5 — Git commit message injection (
prepare-commit-msg) - Phase 3 — Web UI for browsing sessions and explanation history
Issues and PRs welcome. This project follows its own conventions —
run start_convention_interview() in DiffMind before contributing code.