diff --git a/.github/social-preview-template.txt b/.github/social-preview-template.txt index a4e437c..cb8f07a 100644 --- a/.github/social-preview-template.txt +++ b/.github/social-preview-template.txt @@ -7,7 +7,7 @@ ┃ ┃ ┃ ┃ ┃ ┌─────────────────────────────────────────┐ ┃ -┃ │ Devscope: B · Low risk · Easy │ ┃ +┃ │ Local Git context for coding agents │ ┃ ┃ │ onboarding · 0.06s ⚡ │ ┃ ┃ └─────────────────────────────────────────┘ ┃ ┃ ┃ @@ -40,7 +40,7 @@ TEXT LAYOUT: 3. Sample Output Box - Position: Center-bottom (480px from top) - - Content: "Devscope: B · Low risk · Easy onboarding · 0.06s ⚡" + - Content: "Local Git history · private · read-only · fast" - Font: Monospace, ~38px - Color: #79c0ff (light blue) - Background: Semi-transparent box (#1a1f3a with 60% opacity) diff --git a/CHANGELOG.md b/CHANGELOG.md index f66addf..d8ec2e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.4.0 — 2026-12-05 + +- Added five local, read-only MCP tools for agent access to fix history, ownership, + co-change facts, import blast radius and changed-file context. +- Added portable Claude Code, Cursor and Codex MCP configuration plus an opt-in, + fail-open working-tree hook. +- Removed predictive risk ranking and the legacy `file_risk` MCP tool after the + preregistered P3b evaluation found no improvement over ranking by file size. +- Published the complete negative result, paired per-unit data and methodology. +- Requires Python 3.11 or newer and tests Python 3.13 in CI. + ## 0.3.0 — 2026-12-04 - Guided `devscope demo` with labelled synthetic data, no Git or repository required. diff --git a/README.md b/README.md index 3aa6597..6764c5a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Devscope -**Review the right files first—with evidence.** +**Give coding agents local Git-history context.** A local CLI and GitHub Action that help you focus a code review, understand an unfamiliar repository, and share readable reports with your team. @@ -9,8 +9,22 @@ unfamiliar repository, and share readable reports with your team. [![PyPI](https://img.shields.io/pypi/v/devscope.svg)](https://pypi.org/project/devscope/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/EhsanAzish80/Devscope/blob/main/LICENSE) +## The result, honestly + +We tried to beat “review the biggest file first” with Git history across 44 +repositories. We could not. In the preregistered final test, Devscope v2 differed +from size-only file-level Recall@3 by **+0.003** on held-out repositories, with a +95% confidence interval of **-0.037 to +0.051**. Co-change history also did not +predict fewer later fixes when the usual partner was included. + +Devscope therefore makes **no predictive risk claim**. Version 0.4.0 is a free, +open-source way to give coding agents inspectable facts: traced fix history, +recent owners, files that often changed together and import blast radius. +[Read the result](docs/negative-result.md) or inspect the +[methodology and raw paired data](docs/methodology.md). + ```bash -pipx install devscope==0.3.0 +pipx install devscope==0.4.0 devscope demo ``` @@ -18,15 +32,13 @@ The demo needs no repository or Git. Its sample paths, history and coverage are clearly labelled synthetic. Python 3.11+ is required; Git is needed for real PR reviews. Already installed? Run `pipx upgrade devscope`. -![Terminal demo: prioritized files, evidence and next commands](https://raw.githubusercontent.com/EhsanAzish80/Devscope/main/docs/assets/terminal-demo.jpg) - ## Choose your starting point | I want to… | Start here | What you get | | --- | --- | --- | | Understand a repository | [Explore a repository](#explore-a-repository) | Modules, entry-point candidates, test locations and declared commands | -| Focus a code review | [Review a PR](#review-a-pr) | Changed files ranked with size, history, co-change and optional coverage evidence | -| Give an AI coding agent local history | [Connect an MCP client](#connect-an-mcp-client) | Six read-only tools for changes, co-change, fix facts, owners and blast radius | +| Focus a code review | [Review a PR](#review-a-pr) | Changed files with configured findings and optional coverage evidence | +| Give an AI coding agent local history | [Connect an MCP client](#connect-an-mcp-client) | Five read-only tools for changes, co-change facts, fix history, owners and blast radius | | Share results with reviewers | [Add to GitHub Actions](#add-to-github-actions) | An updated PR comment and downloadable HTML/JSON/Markdown reports | ## Explore a repository @@ -63,9 +75,7 @@ devscope demo --format html --output demo.html Open the HTML file in your browser. It includes search, evidence and complete report data, with no external scripts or fonts. -![Offline HTML report generated by devscope demo; all data is synthetic](https://raw.githubusercontent.com/EhsanAzish80/Devscope/main/docs/assets/html-report.jpg) - -[Download the standalone sample HTML](https://github.com/EhsanAzish80/Devscope/releases/download/v0.3.0/devscope-demo.html) +[Download the standalone sample HTML](https://github.com/EhsanAzish80/Devscope/releases/download/v0.4.0/devscope-demo.html) · [View its structured data](https://github.com/EhsanAzish80/Devscope/blob/main/docs/assets/demo.json) ## Connect an MCP client @@ -79,21 +89,23 @@ devscope mcp install --client claude-code --path . ``` The installer preserves existing configuration and refuses to replace an existing -`devscope` entry. The server exposes six read-only tools: `review_changes`, -`cochange`, `file_risk`, `fix_history`, `owners` and `blast_radius`. It reads local +`devscope` entry. The server exposes five read-only tools: `review_changes`, +`cochange`, `fix_history`, `owners` and `blast_radius`. It reads local Git history without running repository code or using the network. A cold history index builds in the background; retry the tool when it returns `index_building`. -The `file_risk` compatibility name currently returns fix SHAs, churn and owners, -not a risk score. Codex reads `.codex/config.toml` only after the project is trusted. +Co-change output is historical context, not a warning or prediction. Codex reads +`.codex/config.toml` only after the project is trusted. For a lightweight pre-commit or agent hook, check all working-tree files without blocking by default: ```bash devscope check . --working-tree --format claude-stop -devscope check . --working-tree --format claude-stop --strict # opt-in blocking mode ``` +The hook is opt-in, advisory and fail-open. Its neutral message says that two files +often changed together and asks the agent to check whether that history is relevant. + ## Add to GitHub Actions Save this as `.github/workflows/devscope.yml`. This starts with **advisory** review; @@ -113,10 +125,10 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 - - uses: EhsanAzish80/devscope-action@v1.3.0 + - uses: EhsanAzish80/devscope-action@v1.4.0 with: review: 'true' - devscope-version: '0.3.0' + devscope-version: '0.4.0' ``` The Action updates one bot comment and uploads HTML, JSON and Markdown artifacts. @@ -146,7 +158,7 @@ comment is skipped. For summary-only reporting, use the [read-only CLI workflow] [All commands](https://github.com/EhsanAzish80/Devscope/blob/main/docs/commands.md) · [Changelog](https://github.com/EhsanAzish80/Devscope/blob/main/CHANGELOG.md) Without pipx, use a virtual environment: `python3 -m venv .venv`, activate it, then -`python -m pip install devscope==0.3.0`. On macOS/Linux activation is +`python -m pip install devscope==0.4.0`. On macOS/Linux activation is `source .venv/bin/activate`; on Windows PowerShell use `.venv\Scripts\Activate.ps1`. For development: `uv sync --all-extras`, `uv run pytest`, `uv run ruff check src/devscope tests` diff --git a/docs/assets/demo.html b/docs/assets/demo.html index 1afcf88..6f8e1aa 100644 --- a/docs/assets/demo.html +++ b/docs/assets/demo.html @@ -1,8 +1,8 @@ Devscope · Demo · PR review -
DEVSCOPE / SYNTHETIC DEMO

Demo · PR review

2 new warnings · 2 changed source files


billing/service.py

635 lines · 12 target-history commits

auth/session.py

148 lines · 3 target-history commits

Supplied patch coverage

93.4% of mapped added executable lines · 12 zero-hit · 0 unmapped added lines

History-aware hotspots

Ranked by lines × observed commits; review heuristics, not defect predictions.

All configured findings

StatusFileRuleEvidence
newbilling/service.pylarge-file635 lines exceeds the configured 500-line review threshold
newbilling/service.pyuncovered-added-lines12 added executable lines have zero hits in the supplied report

Interpretation

Complete report data, including coverage and revision provenance
{
-  "schema_version": "1.0",
+
DEVSCOPE / SYNTHETIC DEMO

Demo · PR review

2 new warnings · 2 changed source files


billing/service.py

  • new · large-file: 635 lines exceeds the configured 500-line review threshold
  • new · uncovered-added-lines: 12 added executable lines have zero hits in the supplied report

auth/session.py

    Supplied patch coverage

    93.4% of mapped added executable lines · 12 zero-hit · 0 unmapped added lines

    All configured findings

    StatusFileRuleEvidence
    newbilling/service.pylarge-file635 lines exceeds the configured 500-line review threshold
    newbilling/service.pyuncovered-added-lines12 added executable lines have zero hits in the supplied report

    Interpretation

    • File size and churn are review heuristics, not defect predictions.
    • Coverage percentages apply only to mapped added executable lines in a supplied report.
    • Begin with advisory reports; enable blocking gates only after choosing your policy.
    • Demo: all paths, commits, history and coverage are synthetic. No repository was scanned and no tests were executed.
    Complete report data, including coverage and revision provenance
    {
    +  "schema_version": 3,
       "kind": "review",
       "demo": true,
       "target_commit": "1111111111111111111111111111111111111111",
    @@ -171,4 +171,4 @@
         "Begin with advisory reports; enable blocking gates only after choosing your policy."
       ]
     }
    - \ No newline at end of file + diff --git a/docs/assets/demo.json b/docs/assets/demo.json index eda5857..ccf4cb0 100644 --- a/docs/assets/demo.json +++ b/docs/assets/demo.json @@ -1,52 +1,41 @@ { - "schema_version": "1.0", - "kind": "review", - "demo": true, - "target_commit": "1111111111111111111111111111111111111111", "base_commit": "1111111111111111111111111111111111111111", - "head_commit": "2222222222222222222222222222222222222222", - "history": { - "commits_analyzed": 40, - "limit": 200, - "revision": "1111111111111111111111111111111111111111" - }, - "packages": [], - "package_summary": [], "changed_source_files": 2, "checklist": [ { - "path": "billing/service.py", - "line": 453, - "lines": 635, - "recent_commits": 12, - "related_files": [ - { - "path": "billing/models.py", - "cochanges": 6 - } - ], + "coverage": { + "covered": 171, + "uncovered": [ + 453, + 454, + 455, + 456, + 457, + 458, + 459, + 460, + 461, + 462, + 463, + 464 + ], + "unmapped_added_lines": 0 + }, "findings": [ { - "id": "demo-large-file", - "rule": "large-file", - "path": "billing/service.py", - "line": 1, - "severity": "warning", - "status": "new", - "message": "635 lines exceeds the configured 500-line review threshold", "evidence": { "lines": 635, "threshold": 500 - } - }, - { - "id": "demo-uncovered-lines", - "rule": "uncovered-added-lines", + }, + "id": "demo-large-file", + "line": 1, + "message": "635 lines exceeds the configured 500-line review threshold", "path": "billing/service.py", - "line": 453, + "rule": "large-file", "severity": "warning", - "status": "new", - "message": "12 added executable lines have zero hits in the supplied report", + "status": "new" + }, + { "evidence": { "uncovered_lines": [ 453, @@ -62,76 +51,63 @@ 463, 464 ] - } + }, + "id": "demo-uncovered-lines", + "line": 453, + "message": "12 added executable lines have zero hits in the supplied report", + "path": "billing/service.py", + "rule": "uncovered-added-lines", + "severity": "warning", + "status": "new" } ], - "coverage": { - "covered": 171, - "uncovered": [ - 453, - 454, - 455, - 456, - 457, - 458, - 459, - 460, - 461, - 462, - 463, - 464 - ], - "unmapped_added_lines": 0 - }, - "priority": 218 + "line": 453, + "lines": 635, + "path": "billing/service.py", + "priority": 218, + "recent_commits": 12, + "related_files": [ + { + "cochanges": 6, + "path": "billing/models.py" + } + ] }, { - "path": "auth/session.py", + "coverage": null, + "findings": [], "line": 24, "lines": 148, + "path": "auth/session.py", + "priority": 4, "recent_commits": 3, - "related_files": [], - "findings": [], - "coverage": null, - "priority": 4 - } - ], - "history_hotspots": [ - { - "path": "billing/service.py", - "lines": 635, - "recent_commits": 12, - "activity_weight": 7620 - }, - { - "path": "billing/models.py", - "lines": 210, - "recent_commits": 6, - "activity_weight": 1260 + "related_files": [] } ], + "coverage": { + "available": true, + "commit": "2222222222222222222222222222222222222222", + "covered": 171, + "percent": 93.4, + "uncovered": 12, + "unmapped_added_lines": 0 + }, + "demo": true, "findings": [ { - "id": "demo-large-file", - "rule": "large-file", - "path": "billing/service.py", - "line": 1, - "severity": "warning", - "status": "new", - "message": "635 lines exceeds the configured 500-line review threshold", "evidence": { "lines": 635, "threshold": 500 - } - }, - { - "id": "demo-uncovered-lines", - "rule": "uncovered-added-lines", + }, + "id": "demo-large-file", + "line": 1, + "message": "635 lines exceeds the configured 500-line review threshold", "path": "billing/service.py", - "line": 453, + "rule": "large-file", "severity": "warning", - "status": "new", - "message": "12 added executable lines have zero hits in the supplied report", + "status": "new" + }, + { "evidence": { "uncovered_lines": [ 453, @@ -147,24 +123,48 @@ 463, 464 ] - } + }, + "id": "demo-uncovered-lines", + "line": 453, + "message": "12 added executable lines have zero hits in the supplied report", + "path": "billing/service.py", + "rule": "uncovered-added-lines", + "severity": "warning", + "status": "new" } ], - "new_warnings": 2, - "coverage": { - "available": true, - "commit": "2222222222222222222222222222222222222222", - "covered": 171, - "uncovered": 12, - "unmapped_added_lines": 0, - "percent": 93.4 + "head_commit": "2222222222222222222222222222222222222222", + "history": { + "commits_analyzed": 40, + "limit": 200, + "revision": "1111111111111111111111111111111111111111" }, - "warnings": [ - "Demo: all paths, commits, history and coverage are synthetic. No repository was scanned and no tests were executed." + "history_hotspots": [ + { + "activity_weight": 7620, + "lines": 635, + "path": "billing/service.py", + "recent_commits": 12 + }, + { + "activity_weight": 1260, + "lines": 210, + "path": "billing/models.py", + "recent_commits": 6 + } ], + "kind": "review", + "new_warnings": 2, "notes": [ "File size and churn are review heuristics, not defect predictions.", "Coverage percentages apply only to mapped added executable lines in a supplied report.", "Begin with advisory reports; enable blocking gates only after choosing your policy." + ], + "package_summary": [], + "packages": [], + "schema_version": 3, + "target_commit": "1111111111111111111111111111111111111111", + "warnings": [ + "Demo: all paths, commits, history and coverage are synthetic. No repository was scanned and no tests were executed." ] } diff --git a/docs/assets/demo.md b/docs/assets/demo.md index 63fba5c..1c8720a 100644 --- a/docs/assets/demo.md +++ b/docs/assets/demo.md @@ -8,29 +8,16 @@ Merge base `1111111111111111111111111111111111111111` → head `2222222222222222 ### 1. ` billing/service.py ` -635 lines · touched in 12 analyzed target-history commits - - **new / large-file**: 635 lines exceeds the configured 500-line review threshold - **new / uncovered-added-lines**: 12 added executable lines have zero hits in the supplied report -- Check interactions with ` billing/models.py ` (6 observed co-changes). ### 2. ` auth/session.py ` -148 lines · touched in 3 analyzed target-history commits - -- Inspect the changed behavior and its tests; no configured warning was triggered. ### Supplied patch coverage 93.4% of mapped added executable lines covered; 12 zero-hit lines; 0 added lines absent from the report (may include non-executable lines). -### History-aware hotspots - -Ranked by file lines × observed target-history commits (an attention heuristic). - -- ` billing/service.py `: 635 lines × 12 commits -- ` billing/models.py `: 210 lines × 6 commits - ### Package summary Whole repository selected. diff --git a/docs/guide.md b/docs/guide.md index 1b9b752..6688421 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -8,7 +8,7 @@ in a virtual environment (macOS/Linux): ```bash python3 -m venv .venv source .venv/bin/activate -python -m pip install 'devscope==0.3.0' +python -m pip install 'devscope==0.4.0' devscope scan . git fetch origin main devscope compare . --base origin/main @@ -24,7 +24,7 @@ PR changes. Dirty and untracked files are excluded; commit changes before compar Positive deltas mean larger counts, not improvements. Review areas are file-size heuristics, and their disappearance does not establish that a defect was fixed. Git activity is excluded from both snapshots; symlinks and submodules are omitted. -Published 0.2.0 also omits archive export-ignored files. The 0.3.0 source reads +Published 0.2.0 also omits archive export-ignored files. The 0.4.0 source reads tracked regular files directly, including files marked export-ignore. Full history and both refs must be available. The command is advisory and does not impose regression gates. @@ -49,7 +49,7 @@ jobs: with: python-version: '3.12' # Pin the published comparison engine. - - run: python -m pip install 'devscope==0.3.0' + - run: python -m pip install 'devscope==0.4.0' - name: Compare committed snapshots env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -65,7 +65,7 @@ for its pinned installation, required history, and optional comment permission. ## Review guidance -These commands are included in CLI 0.3.0. Start with advisory reports, then +These commands are included in CLI 0.4.0. Start with advisory reports, then choose a policy before enabling blocking gates. ```bash diff --git a/docs/negative-result.md b/docs/negative-result.md new file mode 100644 index 0000000..af80d1f --- /dev/null +++ b/docs/negative-result.md @@ -0,0 +1,60 @@ +# We tried to beat “review the biggest file first.” We couldn't. + +Devscope began with a plausible idea: repository history might identify the files +in a pull request that deserve attention better than diff size alone. Files with +recent fixes, heavy churn, unfamiliar authorship or missing co-change partners seem +like they should be riskier. + +We built the history index, point-in-time feature layer and replay harness needed to +test that idea without reading the future. Then we preregistered one final retest so +we could not keep changing the experiment until it passed. + +## The test + +The final P3b run replayed 24 months of first-parent history across a pinned corpus. +It labelled a changed file when a later fix, landing within 12 months, blamed that +file. Each repository contributed at most 40 sampled units, preventing next.js from +dominating the result. Ten repositories were held out entirely from model fitting. + +The primary comparison was paired: Devscope v2 and size-only ranked the exact same +files in the exact same units. The gate required the 95% repository-stratified +bootstrap interval for v2 minus size-only Recall@3 to be wholly above zero. + +## What happened + +The gate failed. + +- Across 165 held-out units in seven repositories, the preregistered repo-balanced + difference was **+0.0032**, with a 95% CI of **-0.0370 to +0.0512**. +- Across all 1,060 paired units in 44 repositories, v2 won 50, tied 936 and lost 74. +- Mean Recall@3 was about **0.668 for v2** and **0.679 for size-only**. +- next.js had 811 eligible units but contributed only 40, so the cap did its job. + +We also tested the behavior behind the co-change suggestion. When a commit omitted +a high-confidence partner, a fix touched that partner within 30 days in **25.6%** of +cases. When the commit included the partner, the rate was **31.8%**. The omitted to +included ratio was **0.80** (95% CI **0.65 to 0.97**). Larger, more active changes +probably confound this comparison, but that same confounding rules out a causal +claim that omitting the partner creates bugs. + +## What we changed + +We accepted the result. Devscope 0.4.0 removes predictive ranking and the `file_risk` +tool. Co-change is presented only as a historical fact: two files often changed +together, so an agent may check whether that context is relevant. The Stop hook is +opt-in, advisory and fail-open. + +The useful part remains: a local, open-source MCP server that gives coding agents +traced fix history, recent ownership, co-change facts and import blast radius without +running repository code or sending source to a service. + +That is a smaller claim than the one we started with. It is also the one the evidence +supports. + +## Reproduce it + +The frozen protocol, both runner commits, confidence intervals and interpretation are +in [methodology.md](methodology.md). The paired unit data and summary are in +[`docs/bench/`](bench/). The initial reporting run used `626f63f`; a co-change ratio +aggregation bug was corrected alone in `62967cf`, after which the full replay was +restarted from empty shards. The raw rankings and partner events were identical. diff --git a/examples/pr-comparison.yml b/examples/pr-comparison.yml index b663d84..9d8e9d6 100644 --- a/examples/pr-comparison.yml +++ b/examples/pr-comparison.yml @@ -14,7 +14,7 @@ jobs: with: python-version: '3.12' # Pin the published comparison engine. - - run: python -m pip install 'devscope==0.3.0' + - run: python -m pip install 'devscope==0.4.0' - name: Compare committed snapshots env: BASE_SHA: ${{ github.event.pull_request.base.sha }} diff --git a/pyproject.toml b/pyproject.toml index d256750..a3cae2b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "devscope" -version = "0.3.0" +version = "0.4.0" description = "Local PR review guidance, repository onboarding, coverage evidence and offline reports" readme = "README.md" requires-python = ">=3.11" diff --git a/src/devscope/__init__.py b/src/devscope/__init__.py index 733da3c..d21e4fe 100644 --- a/src/devscope/__init__.py +++ b/src/devscope/__init__.py @@ -1,3 +1,3 @@ """devscope - A zero-config code analysis CLI tool.""" -__version__ = "0.3.0" +__version__ = "0.4.0" diff --git a/src/devscope/cli.py b/src/devscope/cli.py index d74e2e3..e08dfda 100644 --- a/src/devscope/cli.py +++ b/src/devscope/cli.py @@ -1213,9 +1213,9 @@ def mcp_install(client: str, command: str, path: Path) -> None: @click.argument("path", type=click.Path(file_okay=False, path_type=Path), default=".") @click.option("--working-tree", is_flag=True, help="Check staged, unstaged, and untracked files") @click.option("--format", "output_format", type=str, default="claude-stop") -@click.option("--strict", is_flag=True, help="Fail when a high-confidence partner is missing") +@click.option("--strict", is_flag=True, hidden=True) def check_command(path: Path, working_tree: bool, output_format: str, strict: bool) -> None: - """Check working-tree files for omitted high-confidence co-change partners.""" + """Show neutral co-change context for working-tree files.""" del working_tree # Kept as a backwards-compatible, optional spelling of the default. try: hook_input = _read_hook_input() @@ -1230,7 +1230,7 @@ def check_command(path: Path, working_tree: bool, output_format: str, strict: bo if not findings: return messages = [ - f"{finding['partner']} usually changes with {finding['path']} and was not touched" + f"{finding['partner']} often changed with {finding['path']}; check whether it is relevant" for finding in findings ] if strict and not stop_hook_active: diff --git a/src/devscope/demo.py b/src/devscope/demo.py index 615902d..861cae9 100644 --- a/src/devscope/demo.py +++ b/src/devscope/demo.py @@ -29,7 +29,7 @@ def demo_report() -> dict[str, Any]: "evidence": {"uncovered_lines": list(range(453, 465))}, } return { - "schema_version": 2, + "schema_version": 3, "kind": "review", "demo": True, "target_commit": "1" * 40, @@ -38,32 +38,12 @@ def demo_report() -> dict[str, Any]: "history": {"commits_analyzed": 40, "limit": 200, "revision": "1" * 40}, "packages": [], "package_summary": [], - "model": {"fitted": False}, "changed_source_files": 2, "checklist": [ { "path": "billing/service.py", "line": 453, "lines": 635, - "risk": 0.81, - "rank": 1, - "calibration": "global", - "evidence": [ - { - "kind": "defect_history", - "weight": 0.34, - "text": "7 bug fixes traced to this file in 12 months", - "refs": ["a1b2c3d"], - }, - { - "kind": "missing_cochange", - "weight": 0.21, - "text": "billing/models.py changed with this file in 6 commits; not in this diff", - "refs": ["billing/models.py"], - }, - ], - "mitigating": [], - "context": {"ai_authored_lines": 112, "owners": ["@alice"]}, "recent_commits": 12, "related_files": [{"path": "billing/models.py", "cochanges": 6}], "findings": [size, missed], @@ -78,12 +58,6 @@ def demo_report() -> dict[str, Any]: "path": "auth/session.py", "line": 24, "lines": 148, - "risk": 0.12, - "rank": 2, - "calibration": "global", - "evidence": [], - "mitigating": [], - "context": {}, "recent_commits": 3, "related_files": [], "findings": [], @@ -148,7 +122,7 @@ def render_demo(console: "Console", report: dict[str, Any]) -> None: ) ) console.print( - "[bold]Review the right files first" + "[bold]Review changed files with inspectable evidence" + ("—" if unicode_ok else " - ") + "with evidence.[/bold]\n" ) @@ -169,7 +143,7 @@ def render_demo(console: "Console", report: dict[str, Any]) -> None: " Check interactions", f"{related['path']}{separator}{related['cochanges']} observed co-changes", ) - table.add_row(second["path"], f"Risk {second['risk']:.2f}") + table.add_row(second["path"], f"{second['lines']} lines{separator}no supplied coverage") console.print(table) console.print( f"\n[bold]Sample patch coverage:[/bold] {report['coverage']['percent']}% of mapped added executable lines" diff --git a/src/devscope/mcp/install.py b/src/devscope/mcp/install.py index 8c69073..d60e82d 100644 --- a/src/devscope/mcp/install.py +++ b/src/devscope/mcp/install.py @@ -24,8 +24,6 @@ def install_client(root: Path, client: str, command: str = "devscope") -> tuple[ servers["devscope"] = {"command": command, "args": args} target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8") - if client == "cursor": - _write_cursor_rule(root) return target, json.dumps(servers["devscope"], sort_keys=True) target = root / ".codex/config.toml" @@ -41,16 +39,3 @@ def install_client(root: Path, client: str, command: str = "devscope") -> tuple[ separator = "" if not existing or existing.endswith("\n\n") else "\n" target.write_text(existing + separator + block, encoding="utf-8") return target, block.strip() - - -def _write_cursor_rule(root: Path) -> None: - target = root / ".cursor/rules/devscope.mdc" - if target.exists(): - return - target.parent.mkdir(parents=True, exist_ok=True) - target.write_text( - "---\ndescription: Check local Git-history risk before finishing changes\nalwaysApply: true\n---\n" - "Call `review_changes` before finishing a change. Before editing an unfamiliar file, " - "call `cochange` and include established partner files when appropriate.\n", - encoding="utf-8", - ) diff --git a/src/devscope/mcp/server.py b/src/devscope/mcp/server.py index 3a38e3b..cea1ee7 100644 --- a/src/devscope/mcp/server.py +++ b/src/devscope/mcp/server.py @@ -12,7 +12,7 @@ def build_server(root: Path) -> MCPServer[Any]: - """Create the six-tool server for one local repository.""" + """Create the five-tool server for one local repository.""" tools = DevscopeTools(root) server: MCPServer[Any] = MCPServer( "devscope", @@ -22,19 +22,14 @@ def build_server(root: Path) -> MCPServer[Any]: @server.tool(name="review_changes", structured_output=True) def review_changes(base: str | None = None, working_tree: bool = False) -> dict[str, Any]: - """Call before committing or opening a PR to list changes and missing partners.""" + """Call before committing or opening a PR to list changes and co-change context.""" return tools.review_changes(base, working_tree) @server.tool(name="cochange", structured_output=True) def cochange(path: str, min_support: int = 3) -> dict[str, Any]: - """Call before editing a file to find files that usually change with it.""" + """Call before editing a file to see files that often changed with it.""" return tools.cochange(path, min_support) - @server.tool(name="file_risk", structured_output=True) - def file_risk(path: str) -> dict[str, Any]: - """Call to inspect fix SHAs, recent churn, and owners without a risk score.""" - return tools.file_risk(path) - @server.tool(name="fix_history", structured_output=True) def fix_history(path: str, limit: int = 10) -> dict[str, Any]: """Call when investigating why a file looks unusual to inspect traced past fixes.""" diff --git a/src/devscope/mcp/tools.py b/src/devscope/mcp/tools.py index 298816a..0d78cc7 100644 --- a/src/devscope/mcp/tools.py +++ b/src/devscope/mcp/tools.py @@ -12,7 +12,7 @@ from devscope.index.incremental import RepositoryIndexer from devscope.index.store import IndexStore from devscope.risk.evidence import owners -from devscope.risk.features import churn_90d, cochange_partners, importer_paths, recent_fix_count +from devscope.risk.features import cochange_partners, importer_paths class FreshIndex: @@ -59,7 +59,7 @@ def _cold_build(self, indexer: RepositoryIndexer) -> None: class DevscopeTools: - """The six P4 tools bound to one repository root.""" + """The five local-history tools bound to one repository root.""" def __init__(self, root: Path) -> None: self.root = GitReader(root).root @@ -92,8 +92,8 @@ def review_changes(self, base: str | None = None, working_tree: bool = False) -> ) missing = self.missing_partners(changed) return { - "summary": f"Found {len(missing)} missing partners across {len(changed)} changed files.", - "missing_partners": missing, + "summary": f"Found {len(missing)} historical co-change relationships to consider across {len(changed)} changed files.", + "cochange_context": missing, "files": sorted(changed), "base": base_sha, "head": head_sha, @@ -122,34 +122,6 @@ def cochange(self, path: str, min_support: int = 3) -> dict[str, Any]: ], } - def file_risk(self, path: str) -> dict[str, Any]: - ready = self._ensure_base() - if ready["status"] != "ready": - return ready - with IndexStore(ready["path"]) as store: - as_of = self._as_of(store.connection, ready["head"]) - fix_count = recent_fix_count(store.connection, path, as_of=as_of) - churn = churn_90d(store.connection, path, as_of=as_of) - people = owners(store.connection, path, as_of=as_of) - fixes = [ - str(row[0]) - for row in store.connection.execute( - "SELECT DISTINCT b.fix_sha FROM bug_intro b " - "JOIN commits c ON c.sha = b.fix_sha " - "WHERE b.path = ? AND c.landed_at < ? " - "ORDER BY c.landed_at DESC LIMIT 10", - (path, as_of), - ) - ] - return { - "summary": f"History facts for {path}: {fix_count} recent fixes and ~{round(churn)} changed lines.", - "path": path, - "recent_fix_count": fix_count, - "fix_shas": fixes, - "churn_90d": round(churn, 1), - "owners": people, - } - def fix_history(self, path: str, limit: int = 10) -> dict[str, Any]: ready = self._ensure_base() if ready["status"] != "ready": @@ -207,9 +179,9 @@ def _review_worktree(self) -> dict[str, Any]: changed = self.working_tree_paths() findings = self.missing_partners(changed) return { - "summary": f"Checked {len(changed)} working-tree files; found {len(findings)} missing partners.", + "summary": f"Checked {len(changed)} working-tree files; found {len(findings)} historical co-change relationships to consider.", "working_tree": True, - "missing_partners": findings, + "cochange_context": findings, } def working_tree_paths(self) -> set[str]: diff --git a/src/devscope/reports.py b/src/devscope/reports.py index a7b7b19..8836195 100644 --- a/src/devscope/reports.py +++ b/src/devscope/reports.py @@ -66,10 +66,6 @@ def report_markdown(report: dict[str, Any], repo_url: str | None = None) -> str: "", f"Merge base `{report['base_commit']}` → head `{report['head_commit']}`", "", - "**uncalibrated weights**" - if not report.get("model", {}).get("fitted", False) - else "**fitted weights**", - "", f"**{report['new_warnings']} new warnings** · {report['changed_source_files']} changed source files · {report['history']['commits_analyzed']} target-history commits analyzed", "", ] @@ -81,18 +77,12 @@ def report_markdown(report: dict[str, Any], repo_url: str | None = None) -> str: lines += [ f"### {index}. {label}", "", - f"Risk **{item['risk']:.2f}** · {item['calibration']} calibration", - "", ] if item["findings"]: lines += [ f"- **{finding['status']} / {finding['rule']}**: {text(finding['message'])}" for finding in item["findings"] ] - lines += [ - f"- **{text(evidence['kind'])} ({evidence['weight']:+.3f})**: {text(evidence['text'])}" - for evidence in item["evidence"] - ] lines.append("") if not report["checklist"]: lines += ["No changed source files in the selected scope.", ""] @@ -133,12 +123,7 @@ def report_html(report: dict[str, Any], repo_url: str | None = None) -> str: title = "Demo · " + title cards = [] if report["kind"] == "review": - weight_status = ( - "fitted weights" - if report.get("model", {}).get("fitted", False) - else "uncalibrated weights" - ) - subtitle = f"{report['new_warnings']} new warnings · {report['changed_source_files']} changed source files · {weight_status}" + subtitle = f"{report['new_warnings']} new warnings · {report['changed_source_files']} changed source files" for item in report["checklist"]: link = source_link(repo_url, report["head_commit"], item["path"], item["line"]) label = text(item["path"]) @@ -148,21 +133,8 @@ def report_html(report: dict[str, Any], repo_url: str | None = None) -> str: f"
  • {text(finding['status'])} · {text(finding['rule'])}: {text(finding['message'])}
  • " for finding in item["findings"] ) - details += "".join( - f"
  • {text(evidence['kind'])} ({evidence['weight']:+.3f}): {text(evidence['text'])}
  • " - for evidence in item["evidence"] - ) - mitigating = "".join( - f"
  • {text(factor['kind'])} ({factor['weight']:+.3f}): {text(factor['text'])}
  • " - for factor in item.get("mitigating", []) - ) - if mitigating: - details += ( - "
  • Mitigating factors" - f"
      {mitigating}
  • " - ) cards.append( - f'

    {label}

    Risk {item["risk"]:.2f} · {text(item["calibration"])} calibration

      {details}
    ' + f'

    {label}

      {details}
    ' ) coverage = report["coverage"] if coverage["available"]: diff --git a/src/devscope/review.py b/src/devscope/review.py index 1348996..5d2e27d 100644 --- a/src/devscope/review.py +++ b/src/devscope/review.py @@ -5,7 +5,6 @@ import json import os import re -import sqlite3 import tempfile from collections import Counter from dataclasses import replace @@ -16,12 +15,7 @@ from devscope.comparison import _git, extract_snapshot from devscope.config import ReviewConfig, load_config from devscope.coverage import read_coverage -from devscope.graph import graph_available from devscope.index.git_reader import GitReader -from devscope.index.incremental import RepositoryIndexer -from devscope.risk.evidence import build_evidence -from devscope.risk.features import pr_features -from devscope.risk.model import RiskModel def source_files( @@ -325,83 +319,24 @@ def resolve(ref: str) -> str: if item["id"] in old and item["rule"] != "uncovered-added-lines" else "new" ) - stats = changed_stats(repo, branch_point, head_sha) - ai_lines = ai_provenance(repo, branch_point, head_sha) - author_email = _git(repo, "show", "-s", "--format=%aE", head_sha).decode().strip() - indexed = RepositoryIndexer(repo, ref=target).build() - ranked: list[tuple[str, Any, Any]] = [] - changed_set = set(changed) - with sqlite3.connect(indexed.path) as database: - landed = database.execute( - "SELECT landed_at FROM commits WHERE sha = ?", (target,) - ).fetchone() - if landed is None: - raise ValueError("Target revision is outside the indexed history window") - as_of = int(landed[0]) + 1 - model = RiskModel() - for path in changed: - if path not in head_files: - continue - additions, deletions = stats.get(path, (0, 0)) - coverage_item = coverage_files.get(path) - uncovered_count: int | None = ( - len(coverage_item["uncovered"]) if coverage_item is not None else None - ) - features = pr_features( - database, - path, - author_email, - changed_set, - additions, - deletions, - as_of=as_of, - uncovered=uncovered_count, - graph_enabled=graph_available(), - ) - ranked.append((path, features, model.score(features))) - ranked.sort(key=lambda item: (-item[2].risk, item[0])) - risk_files = [ - build_evidence( - database, - path, - features, - scored, - changed_set, - as_of=as_of, - rank=rank, - ai_authored_lines=ai_lines.get(path, 0), - additions=stats.get(path, (0, 0))[0], - deletions=stats.get(path, (0, 0))[1], - ) - for rank, (path, features, scored) in enumerate(ranked, 1) - ] - checklist: list[dict[str, Any]] = [] - risk_by_path = {item["path"]: item for item in risk_files} for path in changed: if path not in head_files: continue issues = [item for item in findings if item["path"] == path] - risk_item = risk_by_path[path] checklist.append( { "path": path, "line": min(changed_lines(repo, branch_point, head_sha, path) or [1]), "lines": head_files[path], - "risk": risk_item["risk"], - "rank": risk_item["rank"], - "calibration": risk_item["calibration"], - "evidence": risk_item["evidence"], - "mitigating": risk_item["mitigating"], - "context": risk_item["context"], "recent_commits": 0, "related_files": [], "findings": issues, "coverage": coverage_files.get(path), - "priority": risk_item["risk"], + "priority": sum(item["status"] == "new" for item in issues), } ) - checklist.sort(key=lambda item: (item["rank"], item["path"])) + checklist.sort(key=lambda item: (-item["priority"], item["path"])) package_summary = [ { "package": package, @@ -417,7 +352,7 @@ def resolve(ref: str) -> str: for package in config.packages ] return { - "schema_version": 2, + "schema_version": 3, "kind": "review", "target_commit": target, "base_commit": branch_point, @@ -429,8 +364,6 @@ def resolve(ref: str) -> str: }, "packages": config.packages, "package_summary": package_summary, - "risk_files": risk_files, - "model": {"fitted": model.fitted}, "changed_source_files": len(checklist), "checklist": checklist[: config.checklist_limit], "findings": findings, @@ -438,7 +371,7 @@ def resolve(ref: str) -> str: "coverage": coverage, "warnings": warnings, "notes": [ - "Risk v2 uses the repository's point-in-time history before the target revision.", + "Checklist order reflects configured findings, not predicted defect risk.", "Policy and default baseline come from the target commit; renames are treated as remove/add.", "Co-change evidence ignores commits touching more than 30 files.", "Snapshots omit symlinks and submodules; tracked files remain visible despite ignore/archive attributes.", diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 922b20f..0932e89 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -60,7 +60,6 @@ async def exercise() -> None: assert {tool.name for tool in listed.tools} == { "review_changes", "cochange", - "file_risk", "fix_history", "owners", "blast_radius", @@ -69,7 +68,6 @@ async def exercise() -> None: calls = ( ("review_changes", {"base": base}), ("cochange", {"path": "service.py"}), - ("file_risk", {"path": "service.py"}), ("fix_history", {"path": "service.py"}), ("owners", {"path": "service.py"}), ("blast_radius", {"path": "service.py"}), @@ -81,15 +79,10 @@ async def exercise() -> None: assert list(payload)[0] == "summary" assert len(json.dumps(payload)) < 8_000 - facts = (await client.call_tool("file_risk", {"path": "service.py"})).structured_content - assert "risk" not in facts - assert "risk_score" not in facts - assert "risk" not in json.dumps(facts) - review = (await client.call_tool("review_changes", {})).structured_content assert "rank" not in json.dumps(review) assert "risk" not in json.dumps(review) - assert list(review)[1] == "missing_partners" + assert list(review)[1] == "cochange_context" asyncio.run(exercise()) @@ -140,6 +133,7 @@ def test_installers_merge_and_never_overwrite(tmp_path: Path, client: str) -> No assert added with pytest.raises(ValueError, match="already exists"): install_client(tmp_path, client) + assert not (tmp_path / ".cursor/rules/devscope.mdc").exists() @pytest.mark.parametrize("client", ["claude-code", "cursor", "codex"]) @@ -173,10 +167,10 @@ def test_worktree_check_uses_claude_stop_contract( assert advisory.exit_code == 0 output = json.loads(advisory.output) assert output["hookSpecificOutput"]["hookEventName"] == "Stop" - assert "model.py usually changes with service.py" in output["hookSpecificOutput"]["additionalContext"] + assert "model.py often changed with service.py; check whether it is relevant" in output["hookSpecificOutput"]["additionalContext"] assert strict.exit_code == 2 assert strict.stdout == "" - assert "model.py usually changes with service.py" in strict.stderr + assert "model.py often changed with service.py; check whether it is relevant" in strict.stderr repeated = runner.invoke( cli, diff --git a/tests/test_review_tools.py b/tests/test_review_tools.py index 3003734..045bc7e 100644 --- a/tests/test_review_tools.py +++ b/tests/test_review_tools.py @@ -86,14 +86,13 @@ def test_review_features_exclude_the_prs_own_commits( (root / "app.py").write_text("pass\n" * 5) commit(root, "second PR commit") - report = review_repository(root, base) index = RepositoryIndexer(root, ref=base) + index.build() as_of = GitReader(root).commit_info(base).committed_at + 1 with sqlite3.connect(index.path) as database: assert author_prior_commits( database, "app.py", "feature@example.com", as_of=as_of ) == 0 - assert report["risk_files"][0]["path"] == "app.py" def test_history_and_cochanges_preserve_unusual_paths(repository: Path) -> None: @@ -293,7 +292,7 @@ def test_cobertura_sources_resolve_to_repository_paths(tmp_path: Path) -> None: def test_package_paths_normalize_and_legacy_hotspots_are_removed(repository: Path) -> None: assert read_config({"packages": ["./packages/api/"]}).packages == ["packages/api"] report = review_repository(repository, "HEAD") - assert report["schema_version"] == 2 + assert report["schema_version"] == 3 assert "history_hotspots" not in report assert "History-aware hotspots" not in report_markdown(report) assert "History-aware hotspots" not in report_html(report) diff --git a/tests/test_risk_v2.py b/tests/test_risk_v2.py index 6fce283..ec7e258 100644 --- a/tests/test_risk_v2.py +++ b/tests/test_risk_v2.py @@ -2,7 +2,6 @@ from __future__ import annotations -import json import os import sqlite3 import subprocess @@ -83,24 +82,15 @@ def scripted_repo(tmp_path: Path) -> Path: def test_golden_evidence_json_on_scripted_repo(tmp_path: Path, monkeypatch: Any) -> None: repo = scripted_repo(tmp_path) monkeypatch.setenv("DEVSCOPE_CACHE_DIR", str(tmp_path / "cache")) - monkeypatch.setattr("devscope.review.graph_available", lambda: False) report = review_repository(repo, "main") - actual = report["risk_files"] - expected = json.loads( - (Path(__file__).parent / "golden/risk_evidence_v2.json").read_text(encoding="utf-8") - ) - assert actual == expected - defect = next(item for item in actual[0]["evidence"] if item["kind"] == "defect_history") - assert len(defect["refs"][0]) == 7 - assert actual[0]["context"]["ai_authored_lines"] == 102 - assert all(item["weight"] > 0 for item in actual[0]["evidence"]) - assert all(item["weight"] < 0 for item in actual[0]["mitigating"]) + assert "risk_files" not in report + assert "model" not in report + assert [item["path"] for item in report["checklist"]] == ["billing/service.py"] markdown = report_markdown(report) html = report_html(report) - assert "Mitigating factors" not in markdown - assert "PR changes +102/−1 lines" in markdown - assert "Mitigating factors" in html - assert "recent changes weighted higher" in html + assert "Risk" not in markdown + assert "Risk" not in html + assert "predicted defect risk" in markdown def test_500_file_features_are_under_two_seconds(tmp_path: Path) -> None: diff --git a/uv.lock b/uv.lock index e101a56..a76e596 100644 --- a/uv.lock +++ b/uv.lock @@ -337,7 +337,7 @@ wheels = [ [[package]] name = "devscope" -version = "0.3.0" +version = "0.4.0" source = { editable = "." } dependencies = [ { name = "click" },