Skip to content

feat: add deterministic repo-map scanner (#155 slice 2) - #229

Merged
sumithr merged 5 commits into
mainfrom
feat/issue-155-repo-map-scanner
May 29, 2026
Merged

sumithr merged 5 commits into
mainfrom
feat/issue-155-repo-map-scanner

Conversation

@sumithr

@sumithr sumithr commented May 28, 2026

Copy link
Copy Markdown
Owner

Stacked on #222 (slice 1). When that lands on main, this PR's base auto-rebases.

Second implementation slice under #154's QA-native repo-understanding epic. Adds the local walker that populates the .sumo-qa/repo-map.json artifact defined by slice 1.

Refs #155 · Closes when slice 1 (PR #222) is also merged.

What landed

sumo_qa.repo_map_scanner.scan_repo(root, *, generator_version) -> RepoMap

  • Prefers git ls-files (respects .gitignore, only tracked files); falls back to an rglob walk that skips .git, node_modules, __pycache__, .venv, dist, build, .tox, mutants, .sumo-qa when not in a git repo.
  • Cross-checks git rev-parse --show-toplevel against root so a parent process's GIT_DIR / GIT_WORK_TREE (notably pre-commit's stash on git push) can't leak an ancestor repo's tracked files into a sub-directory scan. Env vars are also scrubbed (_git_env() strips GIT_* before every git subprocess).
  • Classifies into the full first-slice vocabulary: source_file, test_file, manifest, ci_workflow, docs, config, fixture, migration_schema, infrastructure. Language detected from extension. Files outside the language map → unsupported_language warning; binary-extension files → skipped_file warning.
  • SHA-256 content fingerprints (slice 1 schema requires sha256:<64 hex>).
  • Edges of type likely_tests only, inferred by name convention: tests/test_X.py → */X.py. confidence is high for a unique source match, medium when multiple sources share the stem. imports, configured_by deferred — they need [Task]: Add repo-map query and diff-impact analysis tools #156's diff-impact context to be worth computing.
  • Commands extracted from pyproject.toml [project.scripts] and package.json scripts. package.json kinds (test/lint/format/build/other) guessed from script name; pyproject.toml defaults to other.
  • Deterministic by construction: nodes sorted by path; edges by (source, target); commands by (source, name). Only project.generated_at churns.

Evidence

Gate Result
uv run pytest -q 1113 passed, 1 xfailed, 100% coverage on src/sumo_qa
uv run mypy src/sumo_qa/repo_map_scanner.py Clean
uv run ruff check + ruff format --check Clean
End-to-end on this actual repo 240 nodes (8 CI workflows, 46 source, 101 tests, 48 docs, 29 configs, 5 fixtures, 1 infra, 2 manifests), 20 likely_tests edges (all high-confidence), 9 commands (pyproject + package.json), 12 warnings — 83KB JSON round-trips cleanly through slice 1's load_repo_map.

Deferred to follow-up slices

Notes

  • tomli>=2,<3; python_version < '3.11' added to runtime deps for the scanner's pyproject.toml parsing under the 3.10 floor; unconditional in dev deps so mypy's 3.10-pinned check resolves on every dev host.
  • .sumo-qa/repo-map.json added to .gitignore — local cache per slice 1's docs guidance.
  • Codex adversarial review is pending until usage limit resets — I'll re-run it before merge and surface any findings in a follow-up commit.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1110cf1936

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/sumo_qa/repo_map_scanner.py Resolved
Comment thread src/sumo_qa/repo_map_scanner.py Resolved
Base automatically changed from feat/issue-155-repo-map-schema to main May 28, 2026 23:52
sumithr and others added 3 commits May 29, 2026 01:56
Second implementation slice under the QA-native repo-understanding epic.
Adds the local walker that populates the .sumo-qa/repo-map.json artifact
defined by slice 1, so downstream consumers (#156 diff-impact, #157
report, #160 CLI) can build against real data instead of hand-rolled
fixtures.

`sumo_qa.repo_map_scanner.scan_repo(root, *, generator_version)` walks
a repo, classifies files into the first-slice node vocabulary,
SHA-256-fingerprints content, infers minimal `likely_tests` edges by
name convention, and extracts top-level commands from pyproject.toml
and package.json.

Highlights:

- Prefers `git ls-files` (respects .gitignore, only tracked); falls
  back to a manual rglob walk that skips known cache/vendored dirs
  (.git, node_modules, __pycache__, .venv, dist, build, .tox, mutants,
  .sumo-qa) when not inside a git repo.
- Deterministic by construction: nodes sorted by path, edges sorted by
  (source, target), commands sorted by (source, name), fingerprints
  content-hashed. Only project.generated_at varies between runs.
- Edge inference is intentionally narrow: only likely_tests, by name
  convention. imports / configured_by / command_runs are deferred —
  they need #156's diff-impact context to be worth computing.
- Command extraction reads pyproject.toml ([project.scripts]) and
  package.json (scripts). package.json kinds are guessed from script
  name (test/lint/format/build/other); pyproject scripts default to
  "other" until a smarter detector lands.
- Robust to malformed pyproject.toml / package.json (returns empty
  command list, not an exception), missing-on-read fingerprints
  (returns None), and binary extensions / unclassified extensions
  (surfaced as warnings, not silent drops).

49 new tests; full suite 1111 passed at 100% coverage. mypy + ruff
clean.

Adds `tomli>=2,<3` to runtime deps (conditional on python<3.11) for
pyproject.toml parsing under the 3.10 floor; unconditionally to dev
deps so mypy's 3.10-pinned check finds it on every dev host.

`.sumo-qa/repo-map.json` added to .gitignore — local cache by default
per slice 1's docs guidance.

Refs #154.
Real bug surfaced by pre-commit's pre-push hook: pre-commit's stash
mechanism sets GIT_DIR and GIT_WORK_TREE in the parent process env.
The scanner's `subprocess.run(["git", "ls-files"], cwd=tmp_path)` then
returned the OUTER repo's tracked files instead of tmp_path's actual
contents — manifesting as 7 scanner tests failing under `git push` but
passing under plain `uv run pytest`.

Two safety nets:

- `_git_env()` strips GIT_* from os.environ so an inherited GIT_DIR /
  GIT_WORK_TREE can't override `--git-dir` and `cwd`.
- Both `_list_files` and `_detect_git_commit` cross-check
  `git rev-parse --show-toplevel` against the resolved root before
  trusting the call. If git's discovery walks up and finds an ancestor
  repo, the toplevel won't match and we fall back to the manual walk
  (or, for the commit detector, return None).

Adds `git -C <root>` everywhere for belt-and-braces.

Two regression tests:
- scanning a subdirectory of a real git repo doesn't attribute the
  outer commit + tracked files to the inner dir;
- an inherited GIT_DIR / GIT_WORK_TREE from monkeypatched env doesn't
  leak through.

Suite stays at 1113 passed, 100% coverage on src/sumo_qa.
@sumithr
sumithr force-pushed the feat/issue-155-repo-map-scanner branch from 1110cf1 to ac24533 Compare May 29, 2026 00:06
t added 2 commits May 29, 2026 02:18
…e 2)

Surfaced when /finish-pr first drove #229's full CI matrix to green:
- py3.10 coverage dropped to 99% because the version-gated tomllib import's
  if-branch (import tomllib) had no pragma, so the untaken branch counted as
  missing. Pragma both branches — only one runs per interpreter, so the block
  is excluded on every version (the canonical.py pattern this was copied from
  lives outside the src cov gate, which masked the gap).
- Windows pytest failed test_fingerprint_is_canonical_sha256: _make_file wrote
  via text mode, so '\n' became '\r\n' on win32 and the raw-bytes sha256
  drifted. Write with newline='' so the on-disk bytes are deterministic.
- Strip .test/.spec suffix from JS/TS test stems before the test_/_test
  checks so foo.test.ts maps to its foo.ts source (the docs claimed .test/
  .spec were handled but no likely_tests edge was produced).
- Drop tracked-but-deleted files from git ls-files output (filter by
  on-disk existence) so the repo-map describes the current tree and doesn't
  emit nodes with fingerprint=None for paths that no longer exist.
@sumithr
sumithr merged commit 4415e73 into main May 29, 2026
30 checks passed
@sumithr
sumithr deleted the feat/issue-155-repo-map-scanner branch May 29, 2026 00:48
sumithr added a commit that referenced this pull request May 29, 2026
**Stacked on #229** (slice 2) which is stacked on **#222** (slice 1).
When upstream PRs land on main, this PR's base auto-rebases.

Third implementation slice under #154's QA-native repo-understanding
epic. Wraps the slice-2 deterministic scanner in a host-callable MCP
tool so any host (Claude Code, IntelliJ AI Assistant, VS Code + Copilot)
can map an arbitrary repo from the slash menu.

Refs #155.

## Tool signature

```python
sumo_qa_scan_repo(
    root: str,
    generator_version: str | None = None,
    write_to: str | None = None,
) -> RepoMapScanOutput | ErrorEnvelope
```

## Design choices

- **Compact-by-default response.** Returns per-type node counts,
per-type + per-confidence edge counts, command counts by kind, warning
counts by kind. **NO node/edge arrays** — a real scan of this repo
produces 242 nodes / 84KB of JSON; the host budget can't carry that on
every call. Callers who need the full artifact pass `write_to=<path>`
and read it from disk.
- `generator_version` defaults to the installed sumo-qa version via
`importlib.metadata.version("sumo-qa")` so freshness metadata accurately
identifies the producer.
- Read-only annotation, `openWorldHint=False` — reads the local
filesystem only, no network calls.
- Failures (missing directory, file-as-root, scanner exceptions) come
back through the standard `{"isError": True, "error": {...}}` envelope
with an actionable hint.

## Live demo (against this actual repo)

```
Server has 31 tools registered. New tool present:
  sumo_qa_scan_repo: YES

Compact summary returned to the host:
  node_count        : 242
  nodes_by_type     : {config: 29, docs: 48, source_file: 47, ci_workflow: 8,
                       infrastructure: 1, manifest: 2, test_file: 102, fixture: 5}
  edge_count        : 21  (all likely_tests, all high confidence)
  command_count     : 9   (extracted from pyproject.toml + package.json)
  warning_count     : 12  (11 unsupported_language + 1 skipped_file)
  artifact_path     : /tmp/sumo-qa-slice3-demo-repo-map.json
  artifact_bytes    : 84425
```

Full artifact round-trips cleanly through slice 1's `load_repo_map`.

## Evidence

| Gate | Result |
|---|---|
| `uv run pytest -q` | 1123 passed, 1 xfailed, 100% coverage on
`src/sumo_qa` |
| `uv run mypy src/sumo_qa/server.py src/sumo_qa/server_schemas.py` |
Clean |
| `uv run ruff check` + `ruff format --check` | Clean |
| MCP tool surface | 31 tools (was 30); `REQUIRED_TOOL_NAMES` bumped 16
→ 17 |
| `tests/fixtures/mcp_tools_list_snapshot.json` | Regenerated via
`scripts/regen_tools_list_snapshot.py` |

## What landed

- `src/sumo_qa/server_schemas.py` — new `RepoMapScanOutput` model (under
existing `_StrictBase`)
- `src/sumo_qa/server.py` — `@mcp.tool` registration,
`_package_version()` helper, `_build_scan_summary()` aggregator,
`_HINT_SCAN_REPO`
- `src/sumo_qa/installer.py` — `sumo_qa_scan_repo` added to
`REQUIRED_TOOL_NAMES`; doctor/verify handshake fails if a host install
drops it
- `tests/test_server_repo_map_tool.py` — 10 new tests (registration,
annotation shape, declarative description, compact summary, optional
write_to + slice-1 round-trip, default vs explicit generator_version,
both error-envelope arms)
- `tests/test_server.py`, `tests/test_installer_verify.py`,
`tests/test_skill_tool_crossref.py` — updated for the new tool name
- `tests/fixtures/mcp_tools_list_snapshot.json` — regenerated

## Notes

- A `repo-walk` SKILL.md update referencing `sumo_qa_scan_repo` is a
small follow-up (the skill-tool-crossref test currently whitelists the
tool as a standalone utility).
- Codex adversarial review on slices 2 + 3 is still pending — I'll
re-run it before merge once usage resets and surface findings in a
follow-up commit.

---------

Co-authored-by: t <t@t>
sumithr added a commit that referenced this pull request May 29, 2026
…#233)

## What

First consumer of the repo-map: `sumo_qa_analyze_diff_impact`. Given a
set of changed files it uses the persisted `.sumo-qa/repo-map.json`
(live-scan fallback) to answer the QA-native question — **which tests
exercise these changes, and which changed sources have no mapped
coverage (the risk surface)?**

This is the first cut of **issue #156** ("Add repo-map query and
diff-impact analysis tools"), branched off slice 3 so the diff shows
only the slice-4 delta. Scope is deliberately the **diff-impact tool
only**; `sumo_qa_query_repo_map` and the skill-wiring
(`reviewing-before-merge` / `preparing-for-work` / `strategising`) are
follow-up slices.

## How

Mirrors the slice-2 (pure service) + slice-3 (thin MCP wrapper) split:

- **`src/sumo_qa/repo_map_impact.py`** (new) — pure
`analyze_diff_impact(repo_map, changed_files) -> DiffImpact` (no I/O);
plus `changed_files_from_git(root, base_ref)` which diffs the working
tree against `merge-base(base_ref, HEAD)` using `git diff --name-only
-z` (clean GIT_* env + toplevel cross-check, same hygiene as the
scanner).
- **`repo_map_models.py`** — `ImpactNode` + `DiffImpact` models.
- **`server_schemas.py`** — compact `DiffImpactOutput` (bounded by the
changeset, no full node/edge arrays).
- **`server.py`** — the `sumo_qa_analyze_diff_impact` MCP tool: loads
the artifact (ignores a foreign-root artifact, falls back to a live
scan), resolves changed files from an explicit list or `base_ref`,
detects staleness vs HEAD, and optionally writes a
`.sumo-qa/diff-impact.json` overlay. Registered `_writer_local` from the
start (carries forward the PR #230 read-only-hint lesson).

## Output (per changeset)

`changed_nodes`, `affected_nodes` (one-hop), `related_tests`,
`unmapped_files`, **`risk_surface`** (changed sources with no mapped
test), `suggested_inspections`, plus `is_stale` / `used_live_scan` flags
and warning counts.

## Tests / verification

- New: `tests/test_repo_map_impact.py` (core + git helper),
`tests/test_server_diff_impact_tool.py` (wrapper). Contract/registration
tests + tools-list snapshot updated (31 → 32 tools; installer
required-tool count 17 → 18).
- Full suite: **1147 passed, 1 xfailed, 100% coverage**; ruff +
ruff-format + mypy(py3.10) clean.
- Live demo on this repo: changed sources mapped to their tests, risk
surface empty (both covered).

## Review

Codex reviewed the diff (two rounds): round 1 → diff against merge-base
not base-tip, `-z` for non-ASCII paths, foreign-artifact guard; round 2
→ suppress a redundant live-scan warning, tighten the foreign-artifact
test, sync the docstring. All applied and re-verified green. The GitHub
Codex bot will also review on open.

Stacked on #230 (slice 3). Merge order: #222 → #229 → #230 → this.

---------

Co-authored-by: t <t@t>
sumithr added a commit that referenced this pull request May 29, 2026
🤖 I have created a release *beep* *boop*
---


##
[0.18.0](v0.17.0...v0.18.0)
(2026-05-29)


### Features

* add deterministic repo-map scanner
([#155](#155) slice 2)
([#229](#229))
([4415e73](4415e73))
* add sumo_qa_analyze_diff_impact diff-impact tool
([#156](#156) slice 4)
([#233](#233))
([8ff6c9d](8ff6c9d))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

---------

Co-authored-by: release-please[bot] <release-please[bot]@users.noreply.github.com>
sumithr added a commit that referenced this pull request May 29, 2026
…l corpus (#236) (#244)

Closes #236

## What changed

**`sumo-qa-reviewing-before-merge` SKILL.md — mandatory adversarial
discovery pass (step 4).** Before naming risks, the reviewer now runs an
11-probe signal→defect-class sweep over the raw diff (reordered write
paths, removed guards, rollback/cleanup paths,
generated-artifact/version drift, file enumeration including deleted
entries, cwd-vs-repo-root path checks, platform branches, widened
types/schemas, retry/timeout/teardown, CI/merge gates, weakened
assertions). The pinned **discovery → verdict** rule converts each hit
into a NAMED RISK → coverage ledger → UNCOVERED → NOT SAFE, so a latent
defect the green tests don't exercise can't be demoted to a "residual
concern" under a SAFE verdict. The sweep is skipped only for the
docs-only / tool-only-config trivial-change exemption (so trivial
reviews don't manufacture phantom runtime risk). Token budget bumped
3300→4300 for the capability.

**New `skill-reviewing-before-merge-adversarial.yaml`** — 11-seed
discovery corpus seeded from real resolved Codex Review findings on
closed PRs, covering all 9 required defect families plus 2 negative
controls:

| family | seed PR |
|---|---|
| generated-artifact drift | #194/#210 |
| stale/deleted-file scan | #229 |
| weak assertion | #170 |
| rollback data-loss | #164 |
| CI required-check blind spot | #199 |
| path-root/cwd bypass | #100 |
| schema-contract weakening | #112 |
| protocol/timeout cleanup | #121 |
| platform-install mismatch | #231 |
| negative control (docs-only typo) | — |
| negative control (config-only) | — |

Each scenario hands the candidate a **raw diff with no pre-named risks**
plus a green-but-non-covering test run; it must independently name the
defect class, anchor it to file:line, and reach the correct
unsafe/needs-work verdict. Unlike the existing
`skill-reviewing-before-merge.yaml` (which pre-supplies risks and grades
verdict *formatting*), this measures **independent discovery**.

**New `skill-reviewing-before-merge-adversarial.ab.yaml`** — A0 (no
skill) / A1 (catalogues only) / B (full skill) discovery-lift
measurement over a representative 6-seed spread.

## Candidate model: gpt-5-mini (not the estate's gpt-4o-mini)

A discovery eval needs a candidate that can *reason* over a raw diff.
`gpt-4o-mini` proved too noisy to measure it — its full-corpus
baseline-vs-postcut **inverted** between runs. `gpt-5-mini` (a cheap
reasoning model; judge stays `gpt-5.5`) gives a stable signal.

## Evidence (gpt-5-mini candidate, gpt-5.5 judge)

- **Full corpus:** baseline (old skill) **7/11 → postcut (new skill)
10/11**.
- **Controlled `.ab` (same run, variance-immune):** **B 6/6** vs A0/A1
(no-skill / catalogues-only) only ~1–3/6 — the discovery pass
perfect-scores the hard families the bare model misses.
- **Both negative controls pass** (docs-only / config-only stay SAFE; no
invented runtime risk).
- One full-corpus seed flickers run-to-run — a *legitimate* anti-pattern
catch (e.g. the candidate leaking the literal taxonomy label
`docs_change`) or reasoning variance, not a graded false-fail. It's a
**high-bar stress test, not a 100%-green gate**; the signal is the delta
(baseline→postcut, B over A0), not a fixed 11/11.

Baseline/postcut/ab snapshots captured under
`docs/qa/runs/eval-baselines/` (gitignored, per the eval-run
convention).

## Verification

- Full suite: **100% coverage, all pass** (`uv run pytest -q`).
- Targeted gate (issue test plan): `test_skill_md_token_budget.py` +
`test_skill_conformance.py` + `test_workflow_expression_lint.py` — 243
passed.
- Host-neutrality guard clean; pre-commit + pre-push (mutmut, pytest)
green.

## Review

Self-reviewed via `sumo-qa-reviewing-before-merge` (dogfooding the new
discovery pass on this diff), then two adversarial codex passes. Codex
confirmed the grader relaxations keep every anti-pattern +
wrong-verdict-direction rule intact (no metric-gaming), fixed three
seed/grading-realism findings (seeds now *introduce* the defect, not
just comment on a pre-existing one; GROUNDING+SHAPE allow
stale-repo-state anchors for drift seeds; single-pass framing reconciled
with the skill's wait-gate), and returned **clean to merge**.

> `change_rules.yaml` left untouched — the issue marked a catalogue edit
"Potentially"; the discovery logic lives in the skill, and touching the
shared catalogue would destabilise the doc-drift eval that loads it.

Co-authored-by: t <t@t>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant