grokmap 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {grokmap-0.2.0 → grokmap-0.3.0}/PKG-INFO +58 -5
  2. {grokmap-0.2.0 → grokmap-0.3.0}/README.md +53 -3
  3. grokmap-0.3.0/packages/grokmap-mcp/README.md +17 -0
  4. {grokmap-0.2.0 → grokmap-0.3.0}/pyproject.toml +5 -3
  5. {grokmap-0.2.0 → grokmap-0.3.0}/skills/grokmap/SKILL.md +2 -0
  6. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/__init__.py +1 -1
  7. grokmap-0.3.0/src/grokmap/agent_tools.py +248 -0
  8. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/cli.py +17 -0
  9. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/detect.py +8 -1
  10. grokmap-0.3.0/src/grokmap/mcp_server.py +180 -0
  11. grokmap-0.3.0/tests/test_agent_tools.py +123 -0
  12. {grokmap-0.2.0 → grokmap-0.3.0}/tests/test_detect_config.py +11 -0
  13. {grokmap-0.2.0 → grokmap-0.3.0}/.gitignore +0 -0
  14. {grokmap-0.2.0 → grokmap-0.3.0}/LICENSE +0 -0
  15. {grokmap-0.2.0 → grokmap-0.3.0}/action.yml +0 -0
  16. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/__main__.py +0 -0
  17. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/badge.py +0 -0
  18. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/config.py +0 -0
  19. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/gitutil.py +0 -0
  20. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/ledger.py +0 -0
  21. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/prdiff.py +0 -0
  22. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/quiz.py +0 -0
  23. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/report.py +0 -0
  24. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/report_template.html +0 -0
  25. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/scan.py +0 -0
  26. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/score.py +0 -0
  27. {grokmap-0.2.0 → grokmap-0.3.0}/src/grokmap/trend.py +0 -0
  28. {grokmap-0.2.0 → grokmap-0.3.0}/tests/conftest.py +0 -0
  29. {grokmap-0.2.0 → grokmap-0.3.0}/tests/test_cli.py +0 -0
  30. {grokmap-0.2.0 → grokmap-0.3.0}/tests/test_scan_score.py +0 -0
  31. {grokmap-0.2.0 → grokmap-0.3.0}/tests/test_trend_diff.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: grokmap
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Measure comprehension debt: the AI-written code in your repo that nobody understands.
5
5
  Project-URL: Homepage, https://github.com/Aadithya-kl/grokmap
6
6
  Project-URL: Issues, https://github.com/Aadithya-kl/grokmap/issues
7
7
  Author: K. L. Aadithya
8
8
  License-Expression: MIT
9
9
  License-File: LICENSE
10
- Keywords: agent-skills,ai,claude-code,code-review,codex,comprehension-debt,copilot,git
10
+ Keywords: agent-skills,ai,claude-code,code-review,codex,comprehension-debt,copilot,git,mcp,mcp-server
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Environment :: Console
13
13
  Classifier: Intended Audience :: Developers
@@ -17,8 +17,11 @@ Classifier: Topic :: Software Development :: Quality Assurance
17
17
  Classifier: Topic :: Software Development :: Version Control :: Git
18
18
  Requires-Python: >=3.11
19
19
  Provides-Extra: dev
20
+ Requires-Dist: mcp<3,>=2.3; extra == 'dev'
20
21
  Requires-Dist: pytest>=8; extra == 'dev'
21
22
  Requires-Dist: ruff>=0.6; extra == 'dev'
23
+ Provides-Extra: mcp
24
+ Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
22
25
  Description-Content-Type: text/markdown
23
26
 
24
27
  <div align="center">
@@ -28,11 +31,13 @@ Description-Content-Type: text/markdown
28
31
  **Find the AI-written code nobody on your team understands, and pay it down one short quiz at a time.**
29
32
 
30
33
  [![ci](https://github.com/Aadithya-kl/grokmap/actions/workflows/ci.yml/badge.svg)](https://github.com/Aadithya-kl/grokmap/actions/workflows/ci.yml)
34
+ [![PyPI](https://img.shields.io/pypi/v/grokmap)](https://pypi.org/project/grokmap/)
35
+ [![MCP Registry](https://img.shields.io/badge/MCP_Registry-io.github.Aadithya--kl%2Fgrokmap-6e56cf)](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Aadithya-kl/grokmap)
31
36
  ![python](https://img.shields.io/badge/python-3.11%2B-blue)
32
37
  ![dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)
33
38
  ![license](https://img.shields.io/badge/license-MIT-lightgrey)
34
39
 
35
- **[▶ Open the live demo](https://aadithya-kl.github.io/grokmap/)** · [Install](#install) · [Agent skill](#add-the-skill-to-your-coding-agent) · [CI and PR comments](#in-ci)
40
+ **[▶ Live demo](https://aadithya-kl.github.io/grokmap/demo/)** · [Website](https://aadithya-kl.github.io/grokmap/) · [Study: how much of open source is AI-written?](https://aadithya-kl.github.io/grokmap/study/) · [Install](#install) · [Agent skill](#add-the-skill-to-your-coding-agent) · [MCP server](#mcp-server) · [CI and PR comments](#in-ci)
36
41
 
37
42
  <picture>
38
43
  <source media="(prefers-color-scheme: dark)" srcset="docs/report-dark.png">
@@ -71,6 +76,12 @@ src/shopcart/api/auth.py 23 23 0
71
76
  Pay it down: ask your coding agent to run `grokmap quiz <file>` and quiz you.
72
77
  ```
73
78
 
79
+ ## How much of your code is AI-written?
80
+
81
+ `grokmap status` answers that in seconds, and `grokmap trend` shows how it changed month by month. We ran it on 18 well-known open-source projects. In the [MCP reference servers](https://github.com/modelcontextprotocol/servers), 94% of commits from August to October 2026 were co-authored by Claude; in VS Code, 74% were co-authored by Copilot. Read the [full study](https://aadithya-kl.github.io/grokmap/study/), including its limitations.
82
+
83
+ New to the idea? [What is comprehension debt, and how do you measure it?](https://aadithya-kl.github.io/grokmap/comprehension-debt/)
84
+
74
85
  ## How you pay it down: your agent quizzes you
75
86
 
76
87
  grokmap ships an **agent skill**. After your coding agent writes something substantial, it offers a two-minute quiz on exactly the lines you haven't shown you understand, grades you honestly, and records the result:
@@ -96,10 +107,10 @@ Understanding is tracked **per line**. If the agent later rewrites a line you we
96
107
  ## Install
97
108
 
98
109
  ```bash
99
- pipx install git+https://github.com/Aadithya-kl/grokmap
110
+ pipx install grokmap # or: pip install grokmap
100
111
  ```
101
112
 
102
- Or try it without installing: `uvx --from git+https://github.com/Aadithya-kl/grokmap grokmap status`
113
+ Or try it without installing: `uvx grokmap status`
103
114
 
104
115
  Python 3.11+ and git. No other dependencies, no network calls, nothing leaves your machine.
105
116
 
@@ -123,6 +134,46 @@ or copy [`skills/grokmap/`](skills/grokmap/SKILL.md) into your agent's skills fo
123
134
 
124
135
  Then just say **"quiz me on the payments module"**, or let the agent offer after it finishes a change.
125
136
 
137
+ <a id="mcp-server"></a>
138
+ ### MCP server: let your agent check before it edits
139
+
140
+ The skill teaches the agent to quiz you. The MCP server goes further: before the agent changes code, it can ask **"does anyone on this team actually understand this?"** and be more careful when the answer is no.
141
+
142
+ ```json
143
+ {
144
+ "mcpServers": {
145
+ "grokmap": { "command": "uvx", "args": ["grokmap-mcp"] }
146
+ }
147
+ }
148
+ ```
149
+
150
+ [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_grokmap-0098FF?logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=grokmap&config=%7B%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22grokmap-mcp%22%5D%7D)
151
+ [![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en/install-mcp?name=grokmap&config=eyJjb21tYW5kIjogInV2eCIsICJhcmdzIjogWyJncm9rbWFwLW1jcCJdfQ==)
152
+
153
+ That block works in Claude Desktop, Cursor (`.cursor/mcp.json`), Windsurf and most other clients. Elsewhere:
154
+
155
+ ```bash
156
+ claude mcp add grokmap -- uvx grokmap-mcp # Claude Code (the plugin above already includes it)
157
+ codex mcp add grokmap -- uvx grokmap-mcp # Codex CLI
158
+ code --add-mcp '{"name":"grokmap","command":"uvx","args":["grokmap-mcp"]}' # VS Code
159
+ ```
160
+
161
+ Already installed grokmap? `pip install "grokmap[mcp]"` and use `grokmap mcp` as the command instead.
162
+
163
+ Prefer Docker? `docker build -t grokmap-mcp .` in this repo, then use `docker run -i --rm -v "$PWD:/repo" grokmap-mcp` as the command.
164
+
165
+ | Tool | What the agent gets |
166
+ |---|---|
167
+ | `comprehension_risk` | For the files it's about to change: a risk level from *none* to *very high*, who understands them, and how to act (explain the change, keep the diff small, offer a quiz). |
168
+ | `repo_status` | Debt, AI share and the riskiest files. |
169
+ | `who_understands` | Who has shown they understand a file or folder, so it knows whom to ask. |
170
+ | `quiz_brief` | The exact lines you haven't shown you understand, plus grading rules. |
171
+ | `record_understanding` | Records a quiz, explanation, review or pairing result in the shared ledger. The only tool that writes. |
172
+ | `pr_comprehension` | The AI-written lines a branch adds and how many are understood. |
173
+ | `ai_trend` | How much of the code added each week or month each agent wrote. |
174
+
175
+ Plus a `quiz_me` prompt. Everything runs locally on your git history: no network calls, no API keys. It's listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Aadithya-kl/grokmap) as `io.github.Aadithya-kl/grokmap`.
176
+
126
177
  ## Quick start
127
178
 
128
179
  ```bash
@@ -148,6 +199,7 @@ Commit `.grokmap/ledger.jsonl` so your whole team shares one map. It's one JSON
148
199
  | `grokmap check [--max-debt 40] [--critical]` | Exits 1 above the limit. For CI. |
149
200
  | `grokmap badge` | An SVG badge for your README: ![comprehension debt badge](docs/badge-example.svg) |
150
201
  | `grokmap init` | Adds config, ledger and `.gitattributes`. |
202
+ | `grokmap mcp` | Runs the MCP server over stdio (needs `grokmap[mcp]`). |
151
203
 
152
204
  ## In CI
153
205
 
@@ -197,6 +249,7 @@ It also writes the repo summary to the job page, uploads the heatmap as an artif
197
249
  | Cursor | `cursoragent@cursor.com` author or co-author |
198
250
  | OpenAI Codex | `chatgpt-codex` / `codex[bot]`, Codex co-author |
199
251
  | Aider | `aider:` message prefix, `(aider)` author suffix |
252
+ | Charm Crush | `crush@charm.land` co-author |
200
253
  | Devin, Gemini / Jules, Amazon Q, Windsurf | their bot authors or co-author trailers |
201
254
  | Your own | any regex in `[grokmap.ai_patterns]`, or specific commits in `[grokmap.ai_commits]` |
202
255
 
@@ -5,11 +5,13 @@
5
5
  **Find the AI-written code nobody on your team understands, and pay it down one short quiz at a time.**
6
6
 
7
7
  [![ci](https://github.com/Aadithya-kl/grokmap/actions/workflows/ci.yml/badge.svg)](https://github.com/Aadithya-kl/grokmap/actions/workflows/ci.yml)
8
+ [![PyPI](https://img.shields.io/pypi/v/grokmap)](https://pypi.org/project/grokmap/)
9
+ [![MCP Registry](https://img.shields.io/badge/MCP_Registry-io.github.Aadithya--kl%2Fgrokmap-6e56cf)](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Aadithya-kl/grokmap)
8
10
  ![python](https://img.shields.io/badge/python-3.11%2B-blue)
9
11
  ![dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)
10
12
  ![license](https://img.shields.io/badge/license-MIT-lightgrey)
11
13
 
12
- **[▶ Open the live demo](https://aadithya-kl.github.io/grokmap/)** · [Install](#install) · [Agent skill](#add-the-skill-to-your-coding-agent) · [CI and PR comments](#in-ci)
14
+ **[▶ Live demo](https://aadithya-kl.github.io/grokmap/demo/)** · [Website](https://aadithya-kl.github.io/grokmap/) · [Study: how much of open source is AI-written?](https://aadithya-kl.github.io/grokmap/study/) · [Install](#install) · [Agent skill](#add-the-skill-to-your-coding-agent) · [MCP server](#mcp-server) · [CI and PR comments](#in-ci)
13
15
 
14
16
  <picture>
15
17
  <source media="(prefers-color-scheme: dark)" srcset="docs/report-dark.png">
@@ -48,6 +50,12 @@ src/shopcart/api/auth.py 23 23 0
48
50
  Pay it down: ask your coding agent to run `grokmap quiz <file>` and quiz you.
49
51
  ```
50
52
 
53
+ ## How much of your code is AI-written?
54
+
55
+ `grokmap status` answers that in seconds, and `grokmap trend` shows how it changed month by month. We ran it on 18 well-known open-source projects. In the [MCP reference servers](https://github.com/modelcontextprotocol/servers), 94% of commits from August to October 2026 were co-authored by Claude; in VS Code, 74% were co-authored by Copilot. Read the [full study](https://aadithya-kl.github.io/grokmap/study/), including its limitations.
56
+
57
+ New to the idea? [What is comprehension debt, and how do you measure it?](https://aadithya-kl.github.io/grokmap/comprehension-debt/)
58
+
51
59
  ## How you pay it down: your agent quizzes you
52
60
 
53
61
  grokmap ships an **agent skill**. After your coding agent writes something substantial, it offers a two-minute quiz on exactly the lines you haven't shown you understand, grades you honestly, and records the result:
@@ -73,10 +81,10 @@ Understanding is tracked **per line**. If the agent later rewrites a line you we
73
81
  ## Install
74
82
 
75
83
  ```bash
76
- pipx install git+https://github.com/Aadithya-kl/grokmap
84
+ pipx install grokmap # or: pip install grokmap
77
85
  ```
78
86
 
79
- Or try it without installing: `uvx --from git+https://github.com/Aadithya-kl/grokmap grokmap status`
87
+ Or try it without installing: `uvx grokmap status`
80
88
 
81
89
  Python 3.11+ and git. No other dependencies, no network calls, nothing leaves your machine.
82
90
 
@@ -100,6 +108,46 @@ or copy [`skills/grokmap/`](skills/grokmap/SKILL.md) into your agent's skills fo
100
108
 
101
109
  Then just say **"quiz me on the payments module"**, or let the agent offer after it finishes a change.
102
110
 
111
+ <a id="mcp-server"></a>
112
+ ### MCP server: let your agent check before it edits
113
+
114
+ The skill teaches the agent to quiz you. The MCP server goes further: before the agent changes code, it can ask **"does anyone on this team actually understand this?"** and be more careful when the answer is no.
115
+
116
+ ```json
117
+ {
118
+ "mcpServers": {
119
+ "grokmap": { "command": "uvx", "args": ["grokmap-mcp"] }
120
+ }
121
+ }
122
+ ```
123
+
124
+ [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_grokmap-0098FF?logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=grokmap&config=%7B%22command%22%3A%22uvx%22%2C%22args%22%3A%5B%22grokmap-mcp%22%5D%7D)
125
+ [![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en/install-mcp?name=grokmap&config=eyJjb21tYW5kIjogInV2eCIsICJhcmdzIjogWyJncm9rbWFwLW1jcCJdfQ==)
126
+
127
+ That block works in Claude Desktop, Cursor (`.cursor/mcp.json`), Windsurf and most other clients. Elsewhere:
128
+
129
+ ```bash
130
+ claude mcp add grokmap -- uvx grokmap-mcp # Claude Code (the plugin above already includes it)
131
+ codex mcp add grokmap -- uvx grokmap-mcp # Codex CLI
132
+ code --add-mcp '{"name":"grokmap","command":"uvx","args":["grokmap-mcp"]}' # VS Code
133
+ ```
134
+
135
+ Already installed grokmap? `pip install "grokmap[mcp]"` and use `grokmap mcp` as the command instead.
136
+
137
+ Prefer Docker? `docker build -t grokmap-mcp .` in this repo, then use `docker run -i --rm -v "$PWD:/repo" grokmap-mcp` as the command.
138
+
139
+ | Tool | What the agent gets |
140
+ |---|---|
141
+ | `comprehension_risk` | For the files it's about to change: a risk level from *none* to *very high*, who understands them, and how to act (explain the change, keep the diff small, offer a quiz). |
142
+ | `repo_status` | Debt, AI share and the riskiest files. |
143
+ | `who_understands` | Who has shown they understand a file or folder, so it knows whom to ask. |
144
+ | `quiz_brief` | The exact lines you haven't shown you understand, plus grading rules. |
145
+ | `record_understanding` | Records a quiz, explanation, review or pairing result in the shared ledger. The only tool that writes. |
146
+ | `pr_comprehension` | The AI-written lines a branch adds and how many are understood. |
147
+ | `ai_trend` | How much of the code added each week or month each agent wrote. |
148
+
149
+ Plus a `quiz_me` prompt. Everything runs locally on your git history: no network calls, no API keys. It's listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Aadithya-kl/grokmap) as `io.github.Aadithya-kl/grokmap`.
150
+
103
151
  ## Quick start
104
152
 
105
153
  ```bash
@@ -125,6 +173,7 @@ Commit `.grokmap/ledger.jsonl` so your whole team shares one map. It's one JSON
125
173
  | `grokmap check [--max-debt 40] [--critical]` | Exits 1 above the limit. For CI. |
126
174
  | `grokmap badge` | An SVG badge for your README: ![comprehension debt badge](docs/badge-example.svg) |
127
175
  | `grokmap init` | Adds config, ledger and `.gitattributes`. |
176
+ | `grokmap mcp` | Runs the MCP server over stdio (needs `grokmap[mcp]`). |
128
177
 
129
178
  ## In CI
130
179
 
@@ -174,6 +223,7 @@ It also writes the repo summary to the job page, uploads the heatmap as an artif
174
223
  | Cursor | `cursoragent@cursor.com` author or co-author |
175
224
  | OpenAI Codex | `chatgpt-codex` / `codex[bot]`, Codex co-author |
176
225
  | Aider | `aider:` message prefix, `(aider)` author suffix |
226
+ | Charm Crush | `crush@charm.land` co-author |
177
227
  | Devin, Gemini / Jules, Amazon Q, Windsurf | their bot authors or co-author trailers |
178
228
  | Your own | any regex in `[grokmap.ai_patterns]`, or specific commits in `[grokmap.ai_commits]` |
179
229
 
@@ -0,0 +1,17 @@
1
+ # grokmap-mcp
2
+
3
+ <!-- mcp-name: io.github.Aadithya-kl/grokmap -->
4
+
5
+ The MCP server for [grokmap](https://github.com/Aadithya-kl/grokmap): it lets coding agents (Claude Code, Codex, Cursor, Gemini CLI, VS Code…) see which AI-written code **nobody on your team has shown they understand**, adjust how carefully they change it, and quiz you on it.
6
+
7
+ ```json
8
+ {
9
+ "mcpServers": {
10
+ "grokmap": { "command": "uvx", "args": ["grokmap-mcp"] }
11
+ }
12
+ }
13
+ ```
14
+
15
+ Tools: `comprehension_risk`, `repo_status`, `who_understands`, `quiz_brief`, `record_understanding`, `pr_comprehension`, `ai_trend`, plus a `quiz_me` prompt. Everything runs locally on git history; no network calls, no API keys.
16
+
17
+ This package only installs `grokmap[mcp]` and the `grokmap-mcp` command. Docs, the CLI and the GitHub Action are in the [main repository](https://github.com/Aadithya-kl/grokmap).
@@ -4,14 +4,14 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "grokmap"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Measure comprehension debt: the AI-written code in your repo that nobody understands."
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  license-files = ["LICENSE"]
12
12
  requires-python = ">=3.11"
13
13
  authors = [{ name = "K. L. Aadithya" }]
14
- keywords = ["ai", "claude-code", "codex", "copilot", "code-review", "comprehension-debt", "git", "agent-skills"]
14
+ keywords = ["mcp", "mcp-server", "ai", "claude-code", "codex", "copilot", "code-review", "comprehension-debt", "git", "agent-skills"]
15
15
  classifiers = [
16
16
  "Development Status :: 4 - Beta",
17
17
  "Environment :: Console",
@@ -29,9 +29,11 @@ Issues = "https://github.com/Aadithya-kl/grokmap/issues"
29
29
 
30
30
  [project.scripts]
31
31
  grokmap = "grokmap.cli:main"
32
+ grokmap-mcp = "grokmap.mcp_server:main"
32
33
 
33
34
  [project.optional-dependencies]
34
- dev = ["pytest>=8", "ruff>=0.6"]
35
+ mcp = ["mcp>=2.3,<3"]
36
+ dev = ["pytest>=8", "ruff>=0.6", "mcp>=2.3,<3"]
35
37
 
36
38
  [tool.hatch.build.targets.wheel]
37
39
  packages = ["src/grokmap"]
@@ -17,6 +17,8 @@ grokmap --version || pipx install grokmap || pip install --user grokmap
17
17
 
18
18
  If none of those work, `uvx grokmap <command>` runs it without installing. In a repo that has never used grokmap, run `grokmap init` (it adds `.grokmap.toml`, the ledger and a merge rule) and tell the user what it created.
19
19
 
20
+ If the grokmap MCP tools are connected (`comprehension_risk`, `quiz_brief`, `record_understanding`…), use them instead of the CLI: they return the same data as structured results. Before you change a file, `comprehension_risk` tells you how carefully to tread: at *high* or *very high*, keep the diff small, explain what you changed and why, and offer a quiz afterwards.
21
+
20
22
  ## When to use it
21
23
 
22
24
  | The user… | Do this |
@@ -1,3 +1,3 @@
1
1
  """grokmap: measure comprehension debt — the AI-written code nobody on the team understands."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.3.0"
@@ -0,0 +1,248 @@
1
+ """The logic behind grokmap's MCP tools, as plain functions that return JSON-ready dicts.
2
+
3
+ Kept free of any MCP dependency so it can be tested directly and reused by other integrations.
4
+ Every function takes `repo`, a path anywhere inside a git repository (default: current directory).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+
12
+ from grokmap import gitutil, prdiff, trend
13
+ from grokmap.config import Config, load_config
14
+ from grokmap.ledger import METHODS, load_ledger
15
+ from grokmap.quiz import build_targets, format_ranges, mark, render_markdown, truncate
16
+ from grokmap.scan import scan_repo
17
+ from grokmap.score import Stats, evaluate
18
+
19
+ RISK_LEVELS = ("none", "low", "medium", "high", "very high")
20
+
21
+ ADVICE = {
22
+ "none": "Written by people (or no AI-agent commits detected). Edit normally.",
23
+ "low": "Most AI-written code here has been understood by someone. Edit normally, and mention what you changed.",
24
+ "medium": "Some AI-written code here has not been checked by anyone. Keep changes focused and explain them clearly.",
25
+ "high": (
26
+ "Much of this is AI-written code nobody on the team has shown they understand. Prefer small, reviewable "
27
+ "changes, explain the existing behavior before changing it, and offer the user a short grokmap quiz afterwards."
28
+ ),
29
+ "very high": (
30
+ "Almost nobody understands this AI-written code. Before changing it, summarize how it works for the user and "
31
+ "confirm the plan. Avoid broad refactors. Afterwards, offer a short grokmap quiz so the change does not add more debt."
32
+ ),
33
+ }
34
+
35
+
36
+ def _root(repo: str | None) -> tuple[Path, Config]:
37
+ root = gitutil.repo_root(Path(repo or ".").resolve())
38
+ return root, load_config(root)
39
+
40
+
41
+ def _norm(path: str, root: Path) -> str:
42
+ p = path.replace("\\", "/").strip()
43
+ full = Path(p)
44
+ if full.is_absolute():
45
+ try:
46
+ p = full.resolve().relative_to(root).as_posix()
47
+ except ValueError:
48
+ pass
49
+ return p.removeprefix("./").rstrip("/")
50
+
51
+
52
+ def risk_level(st: Stats, critical: bool = False) -> str:
53
+ if st.ai == 0:
54
+ return "none"
55
+ pct = st.debt_pct
56
+ level = 1 if pct < 10 else 2 if pct < 35 else 3 if pct < 60 else 4
57
+ if critical and level >= 2:
58
+ level = min(level + 1, 4)
59
+ return RISK_LEVELS[level]
60
+
61
+
62
+ def _stats_dict(st: Stats) -> dict:
63
+ d = st.to_dict()
64
+ d["understood_by"] = d.pop("people")
65
+ d["agents"] = d.pop("tools")
66
+ return d
67
+
68
+
69
+ def repo_status(repo: str | None = None, top: int = 10) -> dict:
70
+ """Whole-repository summary: debt, AI share, who understands what, riskiest files."""
71
+ root, cfg = _root(repo)
72
+ scan = scan_repo(root, cfg)
73
+ res = evaluate(scan, load_ledger(root), cfg)
74
+ risky = sorted(((p, s) for p, s in res.files.items() if s.debt > 0), key=lambda x: -x[1].debt)[:top]
75
+ return {
76
+ "repo": root.name,
77
+ "head": (scan.head or "")[:12],
78
+ "total": _stats_dict(res.total),
79
+ "risk": risk_level(res.total),
80
+ "critical_paths": _stats_dict(res.critical) if res.critical_files else None,
81
+ "riskiest_files": [
82
+ {
83
+ "path": p,
84
+ "lines": s.lines,
85
+ "ai_lines": s.ai,
86
+ "unread": s.unread,
87
+ "debt_pct": round(s.debt_pct, 1),
88
+ "critical": p in res.critical_files,
89
+ }
90
+ for p, s in risky
91
+ ],
92
+ }
93
+
94
+
95
+ def comprehension_risk(paths: list[str], repo: str | None = None) -> dict:
96
+ """Per-path risk before an edit: how much is AI-written, how much nobody has checked, and what to do about it."""
97
+ root, cfg = _root(repo)
98
+ tracked = [tf.path for tf in gitutil.tracked_files(root)]
99
+ wanted: dict[str, list[str]] = {}
100
+ for raw in paths:
101
+ p = _norm(raw, root)
102
+ if p in ("", "."):
103
+ wanted[raw] = [t for t in tracked if cfg.is_included(t)]
104
+ else:
105
+ wanted[raw] = [t for t in tracked if (t == p or t.startswith(p + "/")) and cfg.is_included(t)]
106
+ every = {f for files in wanted.values() for f in files}
107
+ scan = scan_repo(root, cfg, only=every)
108
+ res = evaluate(scan, load_ledger(root), cfg)
109
+
110
+ results = []
111
+ for raw, files in wanted.items():
112
+ if not files:
113
+ results.append({"path": raw, "found": False, "note": "Not a tracked file or folder (new files have no history yet)."})
114
+ continue
115
+ agg = Stats()
116
+ crit = False
117
+ for f in files:
118
+ if f in res.files:
119
+ agg.add(res.files[f])
120
+ crit = crit or f in res.critical_files
121
+ level = risk_level(agg, crit)
122
+ entry = {
123
+ "path": raw,
124
+ "found": True,
125
+ "files": len(files),
126
+ "risk": level,
127
+ "critical_path": crit,
128
+ **{
129
+ k: v
130
+ for k, v in _stats_dict(agg).items()
131
+ if k
132
+ in ("lines", "ai", "understood", "skimmed", "fading", "unread", "debt_pct", "ai_pct", "agents", "understood_by")
133
+ },
134
+ "advice": ADVICE[level],
135
+ }
136
+ if len(files) > 1:
137
+ worst = sorted((f for f in files if f in res.files and res.files[f].unread), key=lambda f: -res.files[f].unread)[:5]
138
+ entry["most_unread_files"] = [{"path": f, "unread": res.files[f].unread} for f in worst]
139
+ results.append(entry)
140
+ return {"repo": root.name, "results": results}
141
+
142
+
143
+ def who_understands(path: str, repo: str | None = None) -> dict:
144
+ """Who has shown they understand the AI-written code at a path, plus who has been changing it lately."""
145
+ root, cfg = _root(repo)
146
+ p = _norm(path, root)
147
+ risk = comprehension_risk([p], str(root))["results"][0]
148
+ recent = gitutil.run_git(["log", "-n", "200", "--format=%an <%ae>", "--", p or "."], root, check=False).splitlines()
149
+ authors: dict[str, int] = {}
150
+ for a in recent:
151
+ authors[a] = authors.get(a, 0) + 1
152
+ top_authors = sorted(authors.items(), key=lambda kv: -kv[1])[:5]
153
+ return {
154
+ "path": p or ".",
155
+ "understood_by": risk.get("understood_by", {}),
156
+ "ai_lines": risk.get("ai", 0),
157
+ "unread": risk.get("unread", 0),
158
+ "recent_committers": [{"name": a, "commits": n} for a, n in top_authors],
159
+ "note": (
160
+ "understood_by counts AI-written lines each person passed a grokmap quiz on. "
161
+ "recent_committers is plain git history: committing code is not evidence of understanding it, "
162
+ "especially when an agent wrote the change."
163
+ ),
164
+ }
165
+
166
+
167
+ def quiz_brief(
168
+ paths: list[str] | None = None,
169
+ uncommitted: bool = False,
170
+ diff_base: str | None = None,
171
+ who: str | None = None,
172
+ max_lines: int = 200,
173
+ repo: str | None = None,
174
+ ) -> dict:
175
+ """The lines a person has not yet shown they understand, plus the rules for running the quiz."""
176
+ root, cfg = _root(repo)
177
+ who = who or gitutil.current_user(root)
178
+ diff_mode = bool(uncommitted or diff_base)
179
+ scan = None if diff_mode else scan_repo(root, cfg)
180
+ norm_paths = [_norm(p, root) for p in (paths or [])]
181
+ targets = build_targets(root, cfg, who, scan, norm_paths, diff_base, False, diff_mode)
182
+ targets, cut = truncate(targets, max_lines)
183
+ specs = [f"{t.path}:{format_ranges(t.ranges)}" for t in targets]
184
+ return {
185
+ "who": who,
186
+ "nothing_to_quiz": not targets,
187
+ "truncated": cut,
188
+ "line_count": sum(len(t.lines) for t in targets),
189
+ "record_with": {"tool": "record_understanding", "paths": specs, "method": "quiz", "score": "<mean of grades, 0..1>"},
190
+ "brief_markdown": render_markdown(targets, who, cut),
191
+ }
192
+
193
+
194
+ def record_understanding(
195
+ paths: list[str],
196
+ score: float,
197
+ method: str = "quiz",
198
+ who: str | None = None,
199
+ note: str = "",
200
+ repo: str | None = None,
201
+ ) -> dict:
202
+ """Record that a person showed they understand files or line ranges (path or path:10-40,55-60)."""
203
+ if method not in METHODS:
204
+ raise ValueError(f"method must be one of {', '.join(METHODS)}")
205
+ root, cfg = _root(repo)
206
+ who = who or gitutil.current_user(root)
207
+ specs = []
208
+ for raw in paths:
209
+ if ":" in raw and raw.rsplit(":", 1)[1].replace("-", "").replace(",", "").isdigit():
210
+ p, r = raw.rsplit(":", 1)
211
+ specs.append(f"{_norm(p, root)}:{r}")
212
+ else:
213
+ specs.append(_norm(raw, root))
214
+ recs = mark(root, cfg, specs, score, method, who, None, note)
215
+ state = "skimmed" if (method == "review" or (recs and recs[0].score < cfg.pass_score)) else "understood"
216
+ return {
217
+ "recorded": len(recs),
218
+ "who": who,
219
+ "score": round(recs[0].score, 3) if recs else None,
220
+ "counts_as": state if recs else None,
221
+ "lines": sum(len(r.hashes) for r in recs),
222
+ "files": [r.path for r in recs],
223
+ "ledger": ".grokmap/ledger.jsonl",
224
+ "reminder": "Ask the user to commit .grokmap/ledger.jsonl with their change so the team shares it.",
225
+ }
226
+
227
+
228
+ def pr_comprehension(base: str = "origin/main", repo: str | None = None) -> dict:
229
+ """AI-written lines the current branch adds compared with `base`, and how many anyone understands."""
230
+ root, cfg = _root(repo)
231
+ try:
232
+ delta = prdiff.compute(root, cfg, base)
233
+ except gitutil.GitError as exc:
234
+ raise ValueError(f"cannot compare with '{base}': fetch it first (git fetch origin) or pass another base") from exc
235
+ data = prdiff.to_json(delta)
236
+ data["markdown"] = prdiff.render_markdown(delta)
237
+ return data
238
+
239
+
240
+ def ai_trend(by: str = "auto", since: str | None = None, repo: str | None = None) -> dict:
241
+ """AI-written vs human-written lines added per week or month, by agent."""
242
+ root, cfg = _root(repo)
243
+ b, buckets = trend.collect(root, cfg, by, since)
244
+ return trend.to_json(b, buckets)
245
+
246
+
247
+ def dumps(obj: dict) -> str:
248
+ return json.dumps(obj, indent=2, ensure_ascii=False)
@@ -296,6 +296,20 @@ def cmd_init(args) -> int:
296
296
  return 0
297
297
 
298
298
 
299
+ def cmd_mcp(args) -> int:
300
+ try:
301
+ from grokmap.mcp_server import main as serve
302
+ except ImportError as exc:
303
+ print(f"grokmap mcp: {exc}", file=sys.stderr)
304
+ return 2
305
+ import os
306
+
307
+ if args.repo and args.repo != ".":
308
+ os.chdir(args.repo)
309
+ serve()
310
+ return 0
311
+
312
+
299
313
  def build_parser() -> argparse.ArgumentParser:
300
314
  p = argparse.ArgumentParser(
301
315
  prog="grokmap",
@@ -370,6 +384,9 @@ def build_parser() -> argparse.ArgumentParser:
370
384
  s.add_argument("path")
371
385
  s.set_defaults(func=cmd_who)
372
386
 
387
+ s = sub.add_parser("mcp", help='run the MCP server over stdio for coding agents (needs: pip install "grokmap[mcp]")')
388
+ s.set_defaults(func=cmd_mcp)
389
+
373
390
  s = sub.add_parser("init", help="add config, ledger and .gitattributes to this repo")
374
391
  s.set_defaults(func=cmd_init)
375
392
  return p
@@ -18,16 +18,22 @@ BUILTIN_SIGNATURES: list[tuple[str, str, str]] = [
18
18
  ("claude", "message", r"^co-authored-by:.*\b(claude|anthropic)\b"),
19
19
  ("claude", "message", r"generated with \[?claude code"),
20
20
  ("claude", "message", r"^claude-session:"),
21
+ ("claude", "message", r"^assisted-by:.*\bclaude\b"),
21
22
  ("claude", "author", r"\bclaude\[bot\]|noreply@anthropic\.com"),
22
23
  # GitHub Copilot (agent mode, coding agent, co-author trailer)
23
24
  ("copilot", "message", r"^co-authored-by:.*\b(copilot|github copilot)\b"),
24
25
  ("copilot", "author", r"copilot-swe-agent|^copilot\b|copilot@github\.com|\bcopilot\[bot\]"),
26
+ ("copilot", "message", r"^\(written by copilot\)|^assisted-by:.*\bcopilot\b"),
25
27
  # Cursor
26
28
  ("cursor", "message", r"^co-authored-by:.*\bcursor(agent)?\b"),
27
29
  ("cursor", "author", r"cursoragent@cursor\.com|\bcursor agent\b"),
28
30
  # OpenAI Codex / ChatGPT
29
31
  ("codex", "message", r"^co-authored-by:.*\b(codex|chatgpt|openai)\b"),
30
32
  ("codex", "author", r"\bchatgpt-codex|codex\[bot\]"),
33
+ ("codex", "message", r"^assisted-by:.*\b(codex|gpt-\d)"),
34
+ # Charm Crush
35
+ ("crush", "message", r"^co-authored-by:.*<crush@charm\.land>"),
36
+ ("crush", "author", r"crush@charm\.land"),
31
37
  # Aider
32
38
  ("aider", "message", r"^aider:"),
33
39
  ("aider", "message", r"^co-authored-by:.*\baider\b"),
@@ -43,7 +49,8 @@ BUILTIN_SIGNATURES: list[tuple[str, str, str]] = [
43
49
  # Windsurf / Codeium
44
50
  ("windsurf", "message", r"^co-authored-by:.*\b(windsurf|codeium|cascade)\b"),
45
51
  # Generic marker many teams adopt
46
- ("ai", "message", r"^(ai-assisted|ai-generated|assisted-by):"),
52
+ ("ai", "message", r"^(ai-assisted|ai-generated):"),
53
+ ("ai", "message", r"^assisted-by:.*\b(ai|llm|gpt|gemini|agent|model)\b"),
47
54
  ]
48
55
 
49
56
 
@@ -0,0 +1,180 @@
1
+ """grokmap as an MCP server: coding agents can see which code nobody understands, and pay it down.
2
+
3
+ Run with `grokmap mcp` (stdio). Needs the optional dependency: pip install "grokmap[mcp]".
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import functools
9
+ from typing import Annotated, Literal
10
+
11
+ from grokmap import __version__, agent_tools, gitutil
12
+
13
+ try:
14
+ import mcp_types
15
+ from mcp.server.mcpserver import MCPServer
16
+ from mcp.server.mcpserver.exceptions import ToolError
17
+ from pydantic import Field
18
+ except ImportError as exc: # pragma: no cover - exercised by the CLI message test
19
+ raise ImportError('grokmap\'s MCP server needs the "mcp" package: pip install "grokmap[mcp]"') from exc
20
+
21
+ INSTRUCTIONS = """\
22
+ grokmap tracks comprehension debt: code written by AI coding agents that no person on the team has shown they understand.
23
+
24
+ How to use these tools well:
25
+ - Before you change existing code in a non-trivial way, call comprehension_risk on the files or folders involved. \
26
+ Follow its "advice": the higher the risk, the smaller and better-explained your change should be.
27
+ - When the user asks who knows a part of the code or who should review it, call who_understands.
28
+ - After you finish a substantial change the user will commit, offer once (one line, never forced) to quiz them. \
29
+ If they agree: call quiz_brief with uncommitted=true, ask the questions one at a time as the brief describes, grade honestly, \
30
+ then call record_understanding with the paths the brief gives you.
31
+ - Never call record_understanding without real answers from the person, never round scores up, and never record \
32
+ understanding for code because you wrote it. The ledger is about people.
33
+ - For a branch or pull request, pr_comprehension summarizes the AI-written lines it adds and how many anyone understands.
34
+ All tools are local: they read git history and the repository's .grokmap/ledger.jsonl, and make no network calls.
35
+ """
36
+
37
+ READ = mcp_types.ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
38
+ WRITE = mcp_types.ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False)
39
+
40
+
41
+ def friendly(fn):
42
+ """Turn expected failures (bad path, unknown branch, not a repo) into a clear message for the agent."""
43
+
44
+ @functools.wraps(fn)
45
+ def wrapper(*args, **kwargs):
46
+ try:
47
+ return fn(*args, **kwargs)
48
+ except (ValueError, FileNotFoundError, gitutil.GitError) as exc:
49
+ raise ToolError(str(exc)) from None
50
+
51
+ return wrapper
52
+
53
+
54
+ RepoArg = Annotated[str | None, Field(description="Path inside the git repository. Defaults to the server's working directory.")]
55
+
56
+ server = MCPServer(
57
+ "grokmap",
58
+ title="grokmap: comprehension debt",
59
+ description="See which AI-written code nobody on the team understands, and pay it down with quizzes.",
60
+ instructions=INSTRUCTIONS,
61
+ website_url="https://aadithya-kl.github.io/grokmap/",
62
+ version=__version__,
63
+ )
64
+
65
+
66
+ @server.tool(annotations=READ)
67
+ @friendly
68
+ def comprehension_risk(
69
+ paths: Annotated[
70
+ list[str],
71
+ Field(description="Files or folders you are about to change, relative to the repo root. '.' means the whole repo."),
72
+ ],
73
+ repo: RepoArg = None,
74
+ ) -> dict:
75
+ """Call this BEFORE changing existing code. For each path: how much is AI-written, how much nobody has checked,
76
+ who understands it, a risk level (none, low, medium, high, very high) and advice on how carefully to proceed."""
77
+ return agent_tools.comprehension_risk(paths, repo)
78
+
79
+
80
+ @server.tool(annotations=READ)
81
+ @friendly
82
+ def repo_status(
83
+ top: Annotated[int, Field(description="How many of the riskiest files to list.", ge=1, le=50)] = 10,
84
+ repo: RepoArg = None,
85
+ ) -> dict:
86
+ """Whole-repository summary: comprehension debt %, share of AI-written lines by agent, who understands what,
87
+ and the riskiest files. Use when the user asks how much of the code is AI-written or where the risk is."""
88
+ return agent_tools.repo_status(repo, top)
89
+
90
+
91
+ @server.tool(annotations=READ)
92
+ @friendly
93
+ def who_understands(
94
+ path: Annotated[str, Field(description="File or folder, relative to the repo root.")],
95
+ repo: RepoArg = None,
96
+ ) -> dict:
97
+ """Who has shown they understand the AI-written code at a path (from passed quizzes), plus who has been committing
98
+ to it lately. Use it to suggest reviewers or the right person to ask."""
99
+ return agent_tools.who_understands(path, repo)
100
+
101
+
102
+ @server.tool(annotations=READ)
103
+ @friendly
104
+ def quiz_brief(
105
+ paths: Annotated[
106
+ list[str] | None,
107
+ Field(description="Files or folders to quiz on. Leave empty with uncommitted=true for the change just made."),
108
+ ] = None,
109
+ uncommitted: Annotated[bool, Field(description="Quiz on uncommitted changes and new files (what you just wrote).")] = False,
110
+ diff_base: Annotated[
111
+ str | None, Field(description="Quiz on everything changed since this git ref, e.g. 'main' for a branch.")
112
+ ] = None,
113
+ who: Annotated[str | None, Field(description="Person being quizzed. Defaults to git user.email.")] = None,
114
+ max_lines: Annotated[int, Field(description="Cap on lines in the brief, to keep the quiz short.", ge=20, le=1000)] = 200,
115
+ repo: RepoArg = None,
116
+ ) -> dict:
117
+ """Get the exact lines the person has not yet shown they understand, with rules for running a short quiz:
118
+ ask 2 to 6 questions one at a time, grade 0 / 0.5 / 1, then call record_understanding with the given paths."""
119
+ return agent_tools.quiz_brief(paths, uncommitted, diff_base, who, max_lines, repo)
120
+
121
+
122
+ @server.tool(annotations=WRITE)
123
+ @friendly
124
+ def record_understanding(
125
+ paths: Annotated[list[str], Field(description="Paths exactly as quiz_brief returned them, e.g. 'src/a.py:10-40,55-60'.")],
126
+ score: Annotated[float, Field(description="Mean of the grades, 0 to 1.", ge=0, le=1)],
127
+ method: Annotated[
128
+ Literal["quiz", "explain", "review", "pair"],
129
+ Field(description="quiz: answered questions. explain: explained the change back. review: only skimmed (counts as half)."),
130
+ ] = "quiz",
131
+ who: Annotated[
132
+ str | None,
133
+ Field(description="Person who answered. Defaults to git user.email. Only set it when the user says who is answering."),
134
+ ] = None,
135
+ note: Annotated[str, Field(description="Optional short note stored with the record.")] = "",
136
+ repo: RepoArg = None,
137
+ ) -> dict:
138
+ """Record that a person showed they understand these lines. Only call this with a score the person earned by
139
+ answering. Lines changed later automatically count as not understood again."""
140
+ return agent_tools.record_understanding(paths, score, method, who, note, repo)
141
+
142
+
143
+ @server.tool(annotations=READ)
144
+ @friendly
145
+ def pr_comprehension(
146
+ base: Annotated[str, Field(description="Branch to compare with, e.g. 'origin/main' or 'main'.")] = "origin/main",
147
+ repo: RepoArg = None,
148
+ ) -> dict:
149
+ """For the current branch: how many AI-written lines it adds compared with base, which files, and how many anyone
150
+ understands. Includes a ready-to-post markdown summary."""
151
+ return agent_tools.pr_comprehension(base, repo)
152
+
153
+
154
+ @server.tool(annotations=READ)
155
+ @friendly
156
+ def ai_trend(
157
+ by: Annotated[Literal["auto", "week", "month"], Field(description="Bucket size.")] = "auto",
158
+ since: Annotated[str | None, Field(description="Only commits after this date, e.g. '2026-01-01' or '6 months ago'.")] = None,
159
+ repo: RepoArg = None,
160
+ ) -> dict:
161
+ """How much of the code added over time was written by each AI agent versus people."""
162
+ return agent_tools.ai_trend(by, since, repo)
163
+
164
+
165
+ @server.prompt(title="Quiz me on what you just wrote")
166
+ def quiz_me() -> str:
167
+ """Start a short grokmap quiz on the uncommitted changes."""
168
+ return (
169
+ "Call grokmap's quiz_brief tool with uncommitted=true. Then quiz me on that code exactly as the brief says: "
170
+ "one question at a time, wait for my answer, grade it honestly, explain the right answer briefly. At the end, "
171
+ "call record_understanding with the paths from the brief and my average score, and tell me my score."
172
+ )
173
+
174
+
175
+ def main() -> None:
176
+ server.run("stdio")
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
@@ -0,0 +1,123 @@
1
+ import asyncio
2
+ import json
3
+
4
+ import pytest
5
+ from conftest import CLAUDE_TRAILER
6
+
7
+ from grokmap import agent_tools
8
+
9
+
10
+ def test_comprehension_risk_levels_and_advice(mixed_repo):
11
+ root = str(mixed_repo.root)
12
+ out = agent_tools.comprehension_risk(["src/human.py", "src/ai.py", "src", "missing.py"], root)
13
+ by = {r["path"]: r for r in out["results"]}
14
+ assert by["src/human.py"]["risk"] == "none" and by["src/human.py"]["ai"] == 0
15
+ assert by["src/ai.py"]["risk"] == "very high" and by["src/ai.py"]["unread"] == 7
16
+ assert "summarize how it works" in by["src/ai.py"]["advice"]
17
+ assert by["src"]["files"] == 3 and by["src"]["most_unread_files"][0]["path"] == "src/ai.py"
18
+ assert by["missing.py"]["found"] is False
19
+
20
+
21
+ def test_risk_drops_after_quiz_and_rises_for_critical(mixed_repo):
22
+ root = str(mixed_repo.root)
23
+ brief = agent_tools.quiz_brief(["src/ai.py"], repo=root)
24
+ assert not brief["nothing_to_quiz"] and brief["record_with"]["paths"][0].startswith("src/ai.py:")
25
+ assert "## Code to quiz on" in brief["brief_markdown"]
26
+ rec = agent_tools.record_understanding(brief["record_with"]["paths"], 0.9, repo=root)
27
+ assert rec["counts_as"] == "understood" and rec["files"] == ["src/ai.py"]
28
+ after = agent_tools.comprehension_risk(["src/ai.py"], root)["results"][0]
29
+ assert after["risk"] == "low" and after["understood_by"] == {"dev@example.com": 7}
30
+ assert agent_tools.quiz_brief(["src/ai.py"], repo=root)["nothing_to_quiz"]
31
+
32
+ (mixed_repo.root / ".grokmap.toml").write_text('[grokmap]\ncritical = ["src/bot.py"]\n')
33
+ agent_tools.record_understanding(["src/bot.py:1-4"], 1.0, repo=root) # 4 of 5 lines understood -> 20% debt
34
+ bot = agent_tools.comprehension_risk(["src/bot.py"], root)["results"][0]
35
+ assert bot["critical_path"] and bot["risk"] == "high" # medium, bumped one level for a critical path
36
+
37
+
38
+ def test_record_review_counts_as_skimmed_and_rejects_bad_method(mixed_repo):
39
+ root = str(mixed_repo.root)
40
+ assert agent_tools.record_understanding(["src/bot.py"], 1.0, method="review", repo=root)["counts_as"] == "skimmed"
41
+ with pytest.raises(ValueError):
42
+ agent_tools.record_understanding(["src/bot.py"], 1.0, method="vibes", repo=root)
43
+
44
+
45
+ def test_absolute_paths_are_accepted(mixed_repo):
46
+ full = str(mixed_repo.root / "src" / "ai.py")
47
+ out = agent_tools.comprehension_risk([full], str(mixed_repo.root))
48
+ assert out["results"][0]["found"] and out["results"][0]["ai"] == 7
49
+
50
+
51
+ def test_who_understands_and_status_and_trend(mixed_repo):
52
+ root = str(mixed_repo.root)
53
+ who = agent_tools.who_understands("src/bot.py", root)
54
+ assert who["understood_by"] == {} and who["recent_committers"][0]["name"].startswith("Copilot")
55
+ status = agent_tools.repo_status(root, top=2)
56
+ assert status["total"]["ai"] == 12 and len(status["riskiest_files"]) == 2
57
+ assert agent_tools.ai_trend("month", repo=root)["summary"]["tools"] == {"claude": 11, "copilot": 5}
58
+
59
+
60
+ def test_pr_comprehension_and_bad_base(mixed_repo):
61
+ repo = mixed_repo
62
+ repo.git("checkout", "-q", "-b", "feature")
63
+ repo.write("src/new.py", "def f():\n return 1\n")
64
+ repo.commit("feat" + CLAUDE_TRAILER)
65
+ out = agent_tools.pr_comprehension("main", str(repo.root))
66
+ assert out["ai"] == 2 and out["markdown"].startswith("<!-- grokmap:pr-summary -->")
67
+ with pytest.raises(ValueError, match="cannot compare"):
68
+ agent_tools.pr_comprehension("does-not-exist", str(repo.root))
69
+
70
+
71
+ def test_mcp_server_lists_and_calls_tools(mixed_repo):
72
+ pytest.importorskip("mcp")
73
+ from grokmap.mcp_server import server
74
+
75
+ async def run():
76
+ tools = {t.name: t for t in await server.list_tools()}
77
+ assert set(tools) == {
78
+ "comprehension_risk",
79
+ "repo_status",
80
+ "who_understands",
81
+ "quiz_brief",
82
+ "record_understanding",
83
+ "pr_comprehension",
84
+ "ai_trend",
85
+ }
86
+ assert tools["comprehension_risk"].annotations.read_only_hint is True
87
+ assert tools["record_understanding"].annotations.read_only_hint is False
88
+ res = await server.call_tool("comprehension_risk", {"paths": ["src/ai.py"], "repo": str(mixed_repo.root)})
89
+ data = json.loads(res.content[0].text)
90
+ assert data["results"][0]["risk"] == "very high"
91
+ from mcp.server.mcpserver.exceptions import ToolError
92
+
93
+ # a clear message, not a crash (over stdio the client receives it as an error result)
94
+ with pytest.raises(ToolError, match="cannot compare with 'nope'"):
95
+ await server.call_tool("pr_comprehension", {"base": "nope", "repo": str(mixed_repo.root)})
96
+ prompts = await server.list_prompts()
97
+ assert [p.name for p in prompts] == ["quiz_me"]
98
+
99
+ asyncio.run(run())
100
+
101
+
102
+ def test_all_version_numbers_agree():
103
+ import re
104
+ import tomllib
105
+ from pathlib import Path
106
+
107
+ import grokmap
108
+
109
+ root = Path(__file__).resolve().parent.parent
110
+ server = json.loads((root / "server.json").read_text())
111
+ mcp_pkg = tomllib.loads((root / "packages/grokmap-mcp/pyproject.toml").read_text())["project"]
112
+ versions = {
113
+ tomllib.loads((root / "pyproject.toml").read_text())["project"]["version"],
114
+ mcp_pkg["version"],
115
+ server["version"],
116
+ server["packages"][0]["version"],
117
+ json.loads((root / ".claude-plugin/plugin.json").read_text())["version"],
118
+ grokmap.__version__,
119
+ }
120
+ assert len(versions) == 1, versions
121
+ assert mcp_pkg["dependencies"] == [f"grokmap[mcp]=={grokmap.__version__}"]
122
+ readme = (root / "packages/grokmap-mcp/README.md").read_text()
123
+ assert re.search(rf"mcp-name: {re.escape(server['name'])}\s", readme)
@@ -25,6 +25,15 @@ def info(message="fix", name="Dev", email="dev@example.com", sha="a" * 40):
25
25
  ("fix\n\nCo-authored-by: Gemini <gemini@google.com>", "Dev", "d@x.io", "gemini"),
26
26
  ("fix\n\nCo-authored-by: Codex <codex@openai.com>", "Dev", "d@x.io", "codex"),
27
27
  ("fix\n\nAI-Assisted: yes", "Dev", "d@x.io", "ai"),
28
+ ("fix\n\nAssisted-by: Claude Fable 5", "Dev", "d@x.io", "claude"),
29
+ ("fix\n\nCo-Authored-By: Charm Crush <crush@charm.land>", "Dev", "d@x.io", "crush"),
30
+ ("fix\n\n(Written by Copilot)", "Dev", "d@x.io", "copilot"),
31
+ (
32
+ "fix\n\nCo-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>",
33
+ "Dev",
34
+ "d@x.io",
35
+ "copilot",
36
+ ),
28
37
  ],
29
38
  )
30
39
  def test_builtin_signatures(message, name, email, tool):
@@ -39,6 +48,8 @@ def test_builtin_signatures(message, name, email, tool):
39
48
  ("normal commit\n\nCo-authored-by: Jane Doe <jane@example.com>", "Dev", "d@x.io"),
40
49
  ("fix", "Sam", "sam@openai.com"), # people who work at AI labs are not bots
41
50
  ("fix", "Sam", "sam@anthropic.com"),
51
+ ("I have a crush on this API", "Dev", "d@x.io"),
52
+ ("normal\n\nAssisted-by: Jane Doe <jane@example.com>", "Dev", "d@x.io"),
42
53
  ],
43
54
  )
44
55
  def test_human_commits_stay_human(message, name, email):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes