grokmap 0.2.1__tar.gz → 0.3.1__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.
- {grokmap-0.2.1 → grokmap-0.3.1}/PKG-INFO +52 -3
- {grokmap-0.2.1 → grokmap-0.3.1}/README.md +47 -1
- grokmap-0.3.1/packages/grokmap-mcp/README.md +17 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/pyproject.toml +5 -3
- {grokmap-0.2.1 → grokmap-0.3.1}/skills/grokmap/SKILL.md +2 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/__init__.py +1 -1
- grokmap-0.3.1/src/grokmap/agent_tools.py +248 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/cli.py +17 -0
- grokmap-0.3.1/src/grokmap/mcp_server.py +232 -0
- grokmap-0.3.1/tests/test_agent_tools.py +123 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/.gitignore +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/LICENSE +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/action.yml +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/__main__.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/badge.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/config.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/detect.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/gitutil.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/ledger.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/prdiff.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/quiz.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/report.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/report_template.html +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/scan.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/score.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/src/grokmap/trend.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/tests/conftest.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/tests/test_cli.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/tests/test_detect_config.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/tests/test_scan_score.py +0 -0
- {grokmap-0.2.1 → grokmap-0.3.1}/tests/test_trend_diff.py +0 -0
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: grokmap
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.1
|
|
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">
|
|
@@ -29,11 +32,14 @@ Description-Content-Type: text/markdown
|
|
|
29
32
|
|
|
30
33
|
[](https://github.com/Aadithya-kl/grokmap/actions/workflows/ci.yml)
|
|
31
34
|
[](https://pypi.org/project/grokmap/)
|
|
35
|
+
[](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Aadithya-kl/grokmap)
|
|
36
|
+
[](https://glama.ai/mcp/servers/Aadithya-kl/grokmap)
|
|
37
|
+
[](https://scorecard.dev/viewer/?uri=github.com/Aadithya-kl/grokmap)
|
|
32
38
|

|
|
33
39
|

|
|
34
40
|

|
|
35
41
|
|
|
36
|
-
**[▶ 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) · [CI and PR comments](#in-ci)
|
|
42
|
+
**[▶ 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)
|
|
37
43
|
|
|
38
44
|
<picture>
|
|
39
45
|
<source media="(prefers-color-scheme: dark)" srcset="docs/report-dark.png">
|
|
@@ -130,6 +136,48 @@ or copy [`skills/grokmap/`](skills/grokmap/SKILL.md) into your agent's skills fo
|
|
|
130
136
|
|
|
131
137
|
Then just say **"quiz me on the payments module"**, or let the agent offer after it finishes a change.
|
|
132
138
|
|
|
139
|
+
<a id="mcp-server"></a>
|
|
140
|
+
### MCP server: let your agent check before it edits
|
|
141
|
+
|
|
142
|
+
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.
|
|
143
|
+
|
|
144
|
+
```json
|
|
145
|
+
{
|
|
146
|
+
"mcpServers": {
|
|
147
|
+
"grokmap": { "command": "uvx", "args": ["grokmap-mcp"] }
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
[](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)
|
|
153
|
+
[](https://cursor.com/en/install-mcp?name=grokmap&config=eyJjb21tYW5kIjogInV2eCIsICJhcmdzIjogWyJncm9rbWFwLW1jcCJdfQ==)
|
|
154
|
+
|
|
155
|
+
That block works in Claude Desktop, Cursor (`.cursor/mcp.json`), Windsurf and most other clients. Elsewhere:
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
claude mcp add grokmap -- uvx grokmap-mcp # Claude Code (the plugin above already includes it)
|
|
159
|
+
codex mcp add grokmap -- uvx grokmap-mcp # Codex CLI
|
|
160
|
+
code --add-mcp '{"name":"grokmap","command":"uvx","args":["grokmap-mcp"]}' # VS Code
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Already installed grokmap? `pip install "grokmap[mcp]"` and use `grokmap mcp` as the command instead.
|
|
164
|
+
|
|
165
|
+
Prefer Docker? `docker build -t grokmap-mcp .` in this repo, then use `docker run -i --rm -v "$PWD:/repo" grokmap-mcp` as the command.
|
|
166
|
+
|
|
167
|
+
| Tool | What the agent gets |
|
|
168
|
+
|---|---|
|
|
169
|
+
| `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). |
|
|
170
|
+
| `repo_status` | Debt, AI share and the riskiest files. |
|
|
171
|
+
| `who_understands` | Who has shown they understand a file or folder, so it knows whom to ask. |
|
|
172
|
+
| `quiz_brief` | The exact lines you haven't shown you understand, plus grading rules. |
|
|
173
|
+
| `record_understanding` | Records a quiz, explanation, review or pairing result in the shared ledger. The only tool that writes. |
|
|
174
|
+
| `pr_comprehension` | The AI-written lines a branch adds and how many are understood. |
|
|
175
|
+
| `ai_trend` | How much of the code added each week or month each agent wrote. |
|
|
176
|
+
|
|
177
|
+
[](https://glama.ai/mcp/servers/Aadithya-kl/grokmap)
|
|
178
|
+
|
|
179
|
+
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`.
|
|
180
|
+
|
|
133
181
|
## Quick start
|
|
134
182
|
|
|
135
183
|
```bash
|
|
@@ -155,6 +203,7 @@ Commit `.grokmap/ledger.jsonl` so your whole team shares one map. It's one JSON
|
|
|
155
203
|
| `grokmap check [--max-debt 40] [--critical]` | Exits 1 above the limit. For CI. |
|
|
156
204
|
| `grokmap badge` | An SVG badge for your README:  |
|
|
157
205
|
| `grokmap init` | Adds config, ledger and `.gitattributes`. |
|
|
206
|
+
| `grokmap mcp` | Runs the MCP server over stdio (needs `grokmap[mcp]`). |
|
|
158
207
|
|
|
159
208
|
## In CI
|
|
160
209
|
|
|
@@ -6,11 +6,14 @@
|
|
|
6
6
|
|
|
7
7
|
[](https://github.com/Aadithya-kl/grokmap/actions/workflows/ci.yml)
|
|
8
8
|
[](https://pypi.org/project/grokmap/)
|
|
9
|
+
[](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.Aadithya-kl/grokmap)
|
|
10
|
+
[](https://glama.ai/mcp/servers/Aadithya-kl/grokmap)
|
|
11
|
+
[](https://scorecard.dev/viewer/?uri=github.com/Aadithya-kl/grokmap)
|
|
9
12
|

|
|
10
13
|

|
|
11
14
|

|
|
12
15
|
|
|
13
|
-
**[▶ 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) · [CI and PR comments](#in-ci)
|
|
16
|
+
**[▶ 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)
|
|
14
17
|
|
|
15
18
|
<picture>
|
|
16
19
|
<source media="(prefers-color-scheme: dark)" srcset="docs/report-dark.png">
|
|
@@ -107,6 +110,48 @@ or copy [`skills/grokmap/`](skills/grokmap/SKILL.md) into your agent's skills fo
|
|
|
107
110
|
|
|
108
111
|
Then just say **"quiz me on the payments module"**, or let the agent offer after it finishes a change.
|
|
109
112
|
|
|
113
|
+
<a id="mcp-server"></a>
|
|
114
|
+
### MCP server: let your agent check before it edits
|
|
115
|
+
|
|
116
|
+
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.
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
{
|
|
120
|
+
"mcpServers": {
|
|
121
|
+
"grokmap": { "command": "uvx", "args": ["grokmap-mcp"] }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
[](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)
|
|
127
|
+
[](https://cursor.com/en/install-mcp?name=grokmap&config=eyJjb21tYW5kIjogInV2eCIsICJhcmdzIjogWyJncm9rbWFwLW1jcCJdfQ==)
|
|
128
|
+
|
|
129
|
+
That block works in Claude Desktop, Cursor (`.cursor/mcp.json`), Windsurf and most other clients. Elsewhere:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
claude mcp add grokmap -- uvx grokmap-mcp # Claude Code (the plugin above already includes it)
|
|
133
|
+
codex mcp add grokmap -- uvx grokmap-mcp # Codex CLI
|
|
134
|
+
code --add-mcp '{"name":"grokmap","command":"uvx","args":["grokmap-mcp"]}' # VS Code
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Already installed grokmap? `pip install "grokmap[mcp]"` and use `grokmap mcp` as the command instead.
|
|
138
|
+
|
|
139
|
+
Prefer Docker? `docker build -t grokmap-mcp .` in this repo, then use `docker run -i --rm -v "$PWD:/repo" grokmap-mcp` as the command.
|
|
140
|
+
|
|
141
|
+
| Tool | What the agent gets |
|
|
142
|
+
|---|---|
|
|
143
|
+
| `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). |
|
|
144
|
+
| `repo_status` | Debt, AI share and the riskiest files. |
|
|
145
|
+
| `who_understands` | Who has shown they understand a file or folder, so it knows whom to ask. |
|
|
146
|
+
| `quiz_brief` | The exact lines you haven't shown you understand, plus grading rules. |
|
|
147
|
+
| `record_understanding` | Records a quiz, explanation, review or pairing result in the shared ledger. The only tool that writes. |
|
|
148
|
+
| `pr_comprehension` | The AI-written lines a branch adds and how many are understood. |
|
|
149
|
+
| `ai_trend` | How much of the code added each week or month each agent wrote. |
|
|
150
|
+
|
|
151
|
+
[](https://glama.ai/mcp/servers/Aadithya-kl/grokmap)
|
|
152
|
+
|
|
153
|
+
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`.
|
|
154
|
+
|
|
110
155
|
## Quick start
|
|
111
156
|
|
|
112
157
|
```bash
|
|
@@ -132,6 +177,7 @@ Commit `.grokmap/ledger.jsonl` so your whole team shares one map. It's one JSON
|
|
|
132
177
|
| `grokmap check [--max-debt 40] [--critical]` | Exits 1 above the limit. For CI. |
|
|
133
178
|
| `grokmap badge` | An SVG badge for your README:  |
|
|
134
179
|
| `grokmap init` | Adds config, ledger and `.gitattributes`. |
|
|
180
|
+
| `grokmap mcp` | Runs the MCP server over stdio (needs `grokmap[mcp]`). |
|
|
135
181
|
|
|
136
182
|
## In CI
|
|
137
183
|
|
|
@@ -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.
|
|
7
|
+
version = "0.3.1"
|
|
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
|
-
|
|
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 |
|
|
@@ -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
|
|
@@ -0,0 +1,232 @@
|
|
|
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
|
+
"""Rate how risky it is to change specific files or folders, based on how much of their AI-written code anyone
|
|
76
|
+
on the team has shown they understand.
|
|
77
|
+
|
|
78
|
+
When to use: before editing existing code in a non-trivial way. Follow the returned advice: at high or very high,
|
|
79
|
+
keep the diff small, explain the change, and offer a quiz afterwards. For the whole repository use repo_status;
|
|
80
|
+
to find a reviewer use who_understands.
|
|
81
|
+
|
|
82
|
+
Returns {"repo", "results": [...]}, one entry per path with: risk (none, low, medium, high, very high),
|
|
83
|
+
lines, ai, understood, skimmed, fading, unread, debt_pct, ai_pct, agents (lines per AI agent), understood_by
|
|
84
|
+
(person -> lines), critical_path, advice, and most_unread_files. A path that does not exist has found=false.
|
|
85
|
+
Lines count as AI-written when the commit that last changed them carries an AI agent's marker
|
|
86
|
+
(e.g. a Co-Authored-By: Claude trailer)."""
|
|
87
|
+
return agent_tools.comprehension_risk(paths, repo)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@server.tool(annotations=READ)
|
|
91
|
+
@friendly
|
|
92
|
+
def repo_status(
|
|
93
|
+
top: Annotated[int, Field(description="How many of the riskiest files to list.", ge=1, le=50)] = 10,
|
|
94
|
+
repo: RepoArg = None,
|
|
95
|
+
) -> dict:
|
|
96
|
+
"""Summarize comprehension debt for the whole repository: how much code is AI-written, how much of that anyone
|
|
97
|
+
understands, and which files are riskiest.
|
|
98
|
+
|
|
99
|
+
When to use: the user asks how much of the code is AI-written, where the risk is, or for an overview. For
|
|
100
|
+
specific files you are about to change, use comprehension_risk instead; for change over time, use ai_trend.
|
|
101
|
+
|
|
102
|
+
Returns {"repo", "head", "risk", "total", "critical_paths", "riskiest_files"}. total and critical_paths hold
|
|
103
|
+
lines, human, ai, understood, skimmed, fading, unread, debt_pct, ai_pct, agents and understood_by.
|
|
104
|
+
riskiest_files lists up to `top` files with lines, ai_lines, unread, debt_pct and critical. Debt counts unread
|
|
105
|
+
AI-written lines in full and skimmed or fading ones (understood over 180 days ago) as half."""
|
|
106
|
+
return agent_tools.repo_status(repo, top)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@server.tool(annotations=READ)
|
|
110
|
+
@friendly
|
|
111
|
+
def who_understands(
|
|
112
|
+
path: Annotated[str, Field(description="File or folder, relative to the repo root.")],
|
|
113
|
+
repo: RepoArg = None,
|
|
114
|
+
) -> dict:
|
|
115
|
+
"""List the people who have shown they understand the AI-written code at a path, and who committed to it lately.
|
|
116
|
+
|
|
117
|
+
When to use: the user asks who knows this code, who should review a change, or whom to ask. For a risk rating
|
|
118
|
+
use comprehension_risk.
|
|
119
|
+
|
|
120
|
+
Returns {"path", "understood_by" (person -> lines they passed a quiz, explanation or review on), "ai_lines",
|
|
121
|
+
"unread" (AI-written lines nobody has checked), "recent_committers": [{"name", "commits"}], "note"}.
|
|
122
|
+
Committing code is not counted as understanding it: only recorded quizzes, explanations and reviews are."""
|
|
123
|
+
return agent_tools.who_understands(path, repo)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@server.tool(annotations=READ)
|
|
127
|
+
@friendly
|
|
128
|
+
def quiz_brief(
|
|
129
|
+
paths: Annotated[
|
|
130
|
+
list[str] | None,
|
|
131
|
+
Field(description="Files or folders to quiz on. Leave empty with uncommitted=true for the change just made."),
|
|
132
|
+
] = None,
|
|
133
|
+
uncommitted: Annotated[bool, Field(description="Quiz on uncommitted changes and new files (what you just wrote).")] = False,
|
|
134
|
+
diff_base: Annotated[
|
|
135
|
+
str | None, Field(description="Quiz on everything changed since this git ref, e.g. 'main' for a branch.")
|
|
136
|
+
] = None,
|
|
137
|
+
who: Annotated[str | None, Field(description="Person being quizzed. Defaults to git user.email.")] = None,
|
|
138
|
+
max_lines: Annotated[int, Field(description="Cap on lines in the brief, to keep the quiz short.", ge=20, le=1000)] = 200,
|
|
139
|
+
repo: RepoArg = None,
|
|
140
|
+
) -> dict:
|
|
141
|
+
"""Build a quiz brief: the exact AI-written lines a person has not yet shown they understand, with rules for
|
|
142
|
+
quizzing them.
|
|
143
|
+
|
|
144
|
+
When to use: the user asks to be quizzed, or agrees to a quiz after you finished a change (uncommitted=true for
|
|
145
|
+
that change, diff_base='main' for a whole branch, paths for specific code). Ask 2 to 6 questions one at a time,
|
|
146
|
+
grade each 0, 0.5 or 1, then call record_understanding with record_with.paths and the mean grade.
|
|
147
|
+
|
|
148
|
+
Returns {"who", "nothing_to_quiz", "line_count", "truncated", "brief_markdown" (the code and quiz rules),
|
|
149
|
+
"record_with": {"tool", "paths", "method", "score"}}. If nothing_to_quiz is true, tell the person there is
|
|
150
|
+
nothing new for them to check. Read-only: nothing is recorded until you call record_understanding."""
|
|
151
|
+
return agent_tools.quiz_brief(paths, uncommitted, diff_base, who, max_lines, repo)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@server.tool(annotations=WRITE)
|
|
155
|
+
@friendly
|
|
156
|
+
def record_understanding(
|
|
157
|
+
paths: Annotated[list[str], Field(description="Paths exactly as quiz_brief returned them, e.g. 'src/a.py:10-40,55-60'.")],
|
|
158
|
+
score: Annotated[float, Field(description="Mean of the grades, 0 to 1.", ge=0, le=1)],
|
|
159
|
+
method: Annotated[
|
|
160
|
+
Literal["quiz", "explain", "review", "pair"],
|
|
161
|
+
Field(description="quiz: answered questions. explain: explained the change back. review: only skimmed (counts as half)."),
|
|
162
|
+
] = "quiz",
|
|
163
|
+
who: Annotated[
|
|
164
|
+
str | None,
|
|
165
|
+
Field(description="Person who answered. Defaults to git user.email. Only set it when the user says who is answering."),
|
|
166
|
+
] = None,
|
|
167
|
+
note: Annotated[str, Field(description="Optional short note stored with the record.")] = "",
|
|
168
|
+
repo: RepoArg = None,
|
|
169
|
+
) -> dict:
|
|
170
|
+
"""Record in the shared ledger (.grokmap/ledger.jsonl) that a person showed they understand these lines.
|
|
171
|
+
|
|
172
|
+
When to use: only after the person actually answered a quiz from quiz_brief, explained the change back to you,
|
|
173
|
+
reviewed it, or paired on it, with the score they earned. Never record understanding because you or they wrote
|
|
174
|
+
the code, and never round scores up. This is the only tool that writes: it appends to the ledger and changes
|
|
175
|
+
nothing else. Lines edited later count as not understood again.
|
|
176
|
+
|
|
177
|
+
Returns {"recorded", "who", "score", "counts_as" (understood, or skimmed for low scores and reviews),
|
|
178
|
+
"files", "lines", "ledger" (its path), "reminder"}."""
|
|
179
|
+
return agent_tools.record_understanding(paths, score, method, who, note, repo)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@server.tool(annotations=READ)
|
|
183
|
+
@friendly
|
|
184
|
+
def pr_comprehension(
|
|
185
|
+
base: Annotated[str, Field(description="Branch to compare with, e.g. 'origin/main' or 'main'.")] = "origin/main",
|
|
186
|
+
repo: RepoArg = None,
|
|
187
|
+
) -> dict:
|
|
188
|
+
"""Summarize a branch or pull request: the AI-written lines it adds compared with base and how many of them
|
|
189
|
+
anyone understands.
|
|
190
|
+
|
|
191
|
+
When to use: before opening or merging a pull request, or when asked how much of a branch is AI-written. For
|
|
192
|
+
the whole repository use repo_status. The base ref must exist locally (run git fetch if it is missing).
|
|
193
|
+
|
|
194
|
+
Returns {"base", "merge_base", "commits", "ai", "human", "understood", "unread", "tools" (AI lines per agent),
|
|
195
|
+
"files": [{"path", "ai", "human", "understood", "unread", "partial"}], "markdown" (a ready-to-post PR comment)}."""
|
|
196
|
+
return agent_tools.pr_comprehension(base, repo)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@server.tool(annotations=READ)
|
|
200
|
+
@friendly
|
|
201
|
+
def ai_trend(
|
|
202
|
+
by: Annotated[Literal["auto", "week", "month"], Field(description="Bucket size.")] = "auto",
|
|
203
|
+
since: Annotated[str | None, Field(description="Only commits after this date, e.g. '2026-01-01' or '6 months ago'.")] = None,
|
|
204
|
+
repo: RepoArg = None,
|
|
205
|
+
) -> dict:
|
|
206
|
+
"""Show how much of the code added over time was written by each AI agent versus people, per week or month.
|
|
207
|
+
|
|
208
|
+
When to use: the user asks how AI use has changed, which agents write the most code, or since when. For
|
|
209
|
+
today's totals use repo_status. Counts lines added in commits (from git log), attributed to an AI agent when
|
|
210
|
+
the commit carries its marker, e.g. a Co-Authored-By: Claude trailer or a Copilot bot author.
|
|
211
|
+
|
|
212
|
+
Returns {"by", "summary": {"human", "ai", "ai_pct", "tools" (lines per agent)},
|
|
213
|
+
"periods": [{"start", "human", "tools"}]}, oldest period first."""
|
|
214
|
+
return agent_tools.ai_trend(by, since, repo)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@server.prompt(title="Quiz me on what you just wrote")
|
|
218
|
+
def quiz_me() -> str:
|
|
219
|
+
"""Start a short grokmap quiz on the uncommitted changes."""
|
|
220
|
+
return (
|
|
221
|
+
"Call grokmap's quiz_brief tool with uncommitted=true. Then quiz me on that code exactly as the brief says: "
|
|
222
|
+
"one question at a time, wait for my answer, grade it honestly, explain the right answer briefly. At the end, "
|
|
223
|
+
"call record_understanding with the paths from the brief and my average score, and tell me my score."
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def main() -> None:
|
|
228
|
+
server.run("stdio")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
if __name__ == "__main__":
|
|
232
|
+
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)
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|