Skip to main content
Glama
README.md
# DiffMind

> **Your AI writes the code. DiffMind makes sure it explains why.**

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
[![MCP](https://img.shields.io/badge/protocol-MCP-blue)](https://modelcontextprotocol.io)
[![Claude Code](https://img.shields.io/badge/works%20with-Claude%20Code-blueviolet)](https://claude.ai/code)

[English](./README.md) · [简体中文](./README.zh.md)

**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.

---

## A complete login walkthrough

**You:** "Add email/password login with session-based authentication"

**Claude (via DiffMind):**
1. Calls `start_session("实现用户登录功能:邮箱+密码,带会话保持")`
2. Writes code across three files...
3. 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 `list_changes()` and then `recall_change(id)` → recalls the 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.

---

## Keeps your context clean

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)

---

## Token economics

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.

---

## Why existing tools fall short

| | 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.

---

## Why DiffMind?

### The Problem: Vibe Coding Amnesia

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.

### The Solution: Structured Decision Documentation

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.

### An Evolving CLI That Learns You

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*.

---

## How it works

```
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.

---

## Quick start

From the root of the Git repository where you use Claude Code:

```bash
npx -y --package diffmind diffmind init
npx -y --package diffmind diffmind doctor
```

`init` safely merges the Claude Code hooks, writes the project-scoped `.mcp.json`,
creates `.diffmind/`, and installs the DiffMind instructions into `CLAUDE.md`.
Existing JSON files are backed up once as `*.bak`, and rerunning the command is safe.

Restart Claude Code in the repository, then make a code change. Rerun `doctor`
at any time to verify MCP, hooks, storage, and agent instructions.

Optional Git commit-message integration:

```bash
npx -y --package diffmind diffmind install-git-hook
```

### Commit the useful decision records

```bash
echo "/.diffmind/sessions/" >> .gitignore   # optional: exclude raw session files
# explanations/ and digests/ are worth committing — that's the point
git add .diffmind/
```

---

## Usage Examples

### Example 1: First-time setup walkthrough

```bash
cd /path/to/your-project
npx -y --package diffmind diffmind init
npx -y --package diffmind diffmind doctor
# Restart Claude Code in this repository
```

### Example 2: A typical session walkthrough

**You:** "Add JWT refresh token support to the authentication system"

**Claude (via DiffMind):**
1. Calls `start_session("Add JWT refresh token support")`
2. Calls `get_conventions()` to read your project rules
3. Writes code...
4. 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.json` created
- 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.md` generated with Chinese explanation
- Call chain Mermaid diagram showing AuthGuard → TokenService → RefreshAPI

### Example 3: Git commit with auto-generated message

```bash
$ 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
```

### Example 4: Querying past decisions

```bash
# Via MCP tools (in Claude Code)
recall_change("x-20260730-abc123")
list_changes(limit=10, scale="architectural")

# Via CLI
diffmind --help
```

### Example 5: User profile evolution

After 10 sessions:

```bash
$ 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
```

### Example 6: Project overview

```bash
# 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
```

---

## Real-world workflow

### Morning: Start new feature
1. Open Claude Code
2. "Add email verification to signup flow"
3. DiffMind auto-starts session
4. Claude reads conventions, writes code, explains changes
5. Quality gate blocks: "Rationale contains filler phrase: 'better security'"
6. 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."
7. Explanation saved

### Afternoon: Review what was done
1. Check `.diffmind/digests/s-20260730-morning.md`
2. See: why email verification, what alternatives (SMS, phone), trade-offs
3. Understand the decisions without re-reading code

### Evening: Commit work
1. `git commit`
2. Commit message auto-populated with DiffMind digest
3. User profile evolves in background
4. Overview docs updated

### Next week: New developer joins
1. They read `.diffmind/overview/README.md`
2. Understand project architecture in 5 minutes
3. Check `.diffmind/overview/decisions/` for past architectural choices
4. Start contributing with context

---

## MCP tools

| 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 |

---

## Quality gate

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 `structural` or `architectural` change 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.

---

## Git integration

DiffMind automatically enhances your commit messages with session context:

```bash
diffmind install-git-hook
```

Now 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.

---

## See it in action

Want the full picture before installing? [**A worked walkthrough of implementing login**](./docs/mock-example-login.md)
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.

---

## Storage layout

```
.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.

---

## Roadmap

- [x] Phase 1 — MCP server, 9 tools, quality gate, session model
- [x] Phase 1.5 — `diffmind` CLI, Claude Code hook auto-trigger, terminal explanation picker
- [x] Phase 2 — Call chain diff visualization (Mermaid, changed nodes in red)
- [x] Phase 2.5 — Git commit message injection (`prepare-commit-msg`)
- [ ] Phase 3 — Web UI for browsing sessions and explanation history

---

## Contributing

Issues and PRs welcome. This project follows its own conventions —
run `start_convention_interview()` in DiffMind before contributing code.

## License

[MIT](./LICENSE)

TDQS

A3.9/5.0

Scored across 10 tools

Disambiguation4/5

Tools are mostly distinct: conventions, sessions, changes, and notifications are separate concerns. However, mark_gap_filled and test_notify do not clearly fit the established workflow, creating minor ambiguity about their role.

Naming Consistency4/5

Most tools follow a verb_noun snake_case pattern (e.g., save_conventions, explain_change). Exceptions like mark_gap_filled and test_notify deviate slightly but remain readable and consistent in style.

Tool Count4/5

At 10 tools, the server is well-scoped for its purpose, but test_notify feels like an auxiliary utility that doesn't belong to the core domain, making the count slightly higher than necessary.

Completeness3/5

The core change and convention workflows are covered, but the knowledge gap feature only has a 'mark filled' action with no way to create or list gaps, and there is no update/delete for changes or conventions, leaving some lifecycle gaps.

Maintenance

ActivitySlowing
ResponsivenessResponsive