Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(coverage): name the test to extend for each uncovered change, and keep an agent's coverage current (#2650)
Raghav Chamadiya216a3bafee30
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 23e966cb9..463a25db3 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -672,8 +672,9 @@ computation and JSON shape `repowise coverage check --format json` gates on.`patch_coverage_pct` is null when no changed line is executable, files thecoverage never names read `not_in_report` rather than 0%, and`scope.freshness` is `stale` when the coverage was measured at another commit-than the change's head (`unknown` for uncommitted work), so its line numbers-may describe other code. `path_gates` lists the path-scoped gates in+than the change's head (for uncommitted work: ingested before the newest+edit), so its line numbers may describe other code. `path_gates` lists the+path-scoped gates in`coverage.gates`, each judged on the changed files its globs match (`gate`reads `fail` when one that is not informational fails). They are judged onlyon coverage measured at the change's head and valid config; otherwise they@@ -686,6 +687,24 @@ from the checkout's git history), `dependents`, `hotspot` and `bug_magnet`(`file_count`, `covered_line_count`, `coverable_line_count`,`patch_coverage_pct`, `threshold`, `gate`) summarizes coverage over the riskyfiles, null when no row's risk was assessed.+Each measured row also carries `hints`, one per uncovered range (the first+eight): `range`, `symbol` (the innermost indexed symbol, null outside any),+`tests` (up to three test files to extend, best first), `basis` (`per_test`,+`call_graph`, `import_graph` or `none`) and `total` (how many qualified before+the cap). `per_test` is measured (per-test coverage ran nearby lines);+`call_graph` and `import_graph` are inferred from the graph. `hints` is null+when the index could not be read. When changed lines are uncovered,+`directive.next_actions` gains one line naming the scope and the tests to+extend, or, when the coverage is stale, saying to re-run the tests first.++Without a `revspec`, `patch_coverage` covers everything a push would bring,+diffed from the merge-base with the CI or default base branch: `scope.label`+`origin/main...working tree` on a dirty tree (untracked files included),+`origin/main...HEAD` on a clean one, plain `working tree` when no base+resolves. For uncommitted work freshness is by time: `current` when the last+coverage ingest came after the newest edit to the changed files, else+`stale`. After a full test run the augment hook re-ingests a fresh report in+the background, and `get_change_risk` reads it once the ingest finishes.In workspace mode the response also carries `cross_repo`, and every`cross_repo.consumers[]` row gains a `tests` block: a `state` (`measured`,@@ -1457,7 +1476,7 @@ The MCP server automatically enriches responses with cross-repo intelligence:In addition to the MCP tools above, `repowise init` installs AI-agent hooks (Claude Code and Codex) that provide **passive, automatic** context enrichment:-- **Claude Code PostToolUse**: broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, and git operations can trigger stale-wiki notices.+- **Claude Code PostToolUse**: broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, git operations can trigger stale-wiki notices, and a full test run that wrote a fresh coverage report re-ingests it in the background, so `patch_coverage` reads the new run once the ingest finishes (off with `hooks.coverage_reingest: false`).- **Codex SessionStart**: Codex receives concise repowise MCP workflow guidance when a session starts.- **Codex PostToolUse**: after edits or git operations, Codex receives a freshness reminder when indexed context may be stale.diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex 83c5078a3..9bcbdbd12 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -318,6 +318,38 @@ set, a shallow clone or a measured row whose risk could not be read exits `2`,unless the flat or a path-scoped gate already failed, which is then reportedas the failure.+### Where to add the test++With an index, each uncovered range also says where its test belongs, naming+the test file to extend when one is found (`hints` on each measured row in+`json`, the REST response and `get_change_risk`). `hints` is `null` without an+index or when it could not be read; a measured row with no uncovered range has+an empty list; every uncovered range the index was asked about has a hint, with+basis `none` when nothing names a test. A hint names the innermost indexed+symbol containing the range (`null` outside any), up to three test files (best+first), the `basis` that found them and `total`, how many qualified before the+cap. Evidence is tried strongest first:++| `basis` | The test files are | Evidence |+|---|---|---|+| `per_test` | tests the per-test map says ran other lines of that symbol, or lines within 5 of a range outside any symbol; only when the coverage is `current` for the change | measured |+| `call_graph` | tests whose calls reach that symbol | inferred, symbol-precise |+| `import_graph` | tests that import the file | inferred, file-level |+| `none` | nothing names a test | the range needs a new one |++The index stores symbol lines at the commit it was built from. When the change+ends somewhere else (always, for uncommitted work), each file's symbols are+moved through the diff from that commit, so a range in a function added since+the index has no symbol and falls to file-level evidence.++Hints cover the first 8 ranges of each file, the ones every rendering lists.+The markdown table gains an "Extend" column ("extend tests/test_auth.py+(inferred: calls reach `login`)", "(measured: runs other lines of `login`)",+"(inferred: imports this file)", or "no test reaches this; add one"), the+terminal table the same, and each GitHub annotation ends with the same phrase.+Hints are advice: a missing or unreadable index leaves them `null` and never+changes the verdict.+A coverage.py `.coverage` database is not a text report: export it with`coverage lcov` or `coverage xml` first.@@ -407,6 +439,52 @@ map.cannot tell a guess from real coverage, and `no_coverage_data` already reportsthose files honestly.+### Self-checking before a push++`get_change_risk` without a `revspec` measures its `patch_coverage` block over+everything a push would bring, diffed from the merge-base with the branch CI+would compare against (the CI base variables, else the default branch). On a+dirty tree that is the working tree, untracked files included, labelled e.g.+`origin/main...working tree`; on a clean one it is `origin/main...HEAD`, so the+check does not shrink to the last commit once the work is committed. With no+base to find, it falls back to the plain working-tree diff (`working tree`) or+the commit scored. No commit names uncommitted code, so its freshness is by+time: `current` when the last coverage ingest came after the newest+modification of the changed files on disk, else `stale`. Ceiling: an old+report ingested after the last edit also reads current, because the report's+own run time is not stored; the hook below only ingests reports newer than the+last ingest, which keeps that case rare. Committed changes keep the commit+rule above. When changed lines are uncovered, the directive gains one+`next_actions` line: "N changed executable lines since origin/main are+uncovered; extend <the hinted tests>", or, when the coverage is stale, a line+saying to re-run the tests with coverage first.++The loop closes itself in Claude Code and Codex. After a Bash command that+runs a whole test suite, such as `pytest`, `python -m pytest`,+`coverage run -m pytest`, `go test ./...`, `npm test`, `npx vitest run`,+`jest`, `cargo test`, `cargo llvm-cov`, `mvn test` or `./gradlew test`, the+augment hook checks the aggregate reports (`coverage.paths`, else the fixed+default locations such as `coverage/lcov.info`, `coverage.xml` and+`coverage.out`). When some are newer than the index's last coverage ingest, it+starts `repowise coverage add` on exactly those reports in the background and+adds one line to the transcript: "Re-ingesting coverage from+coverage/lcov.info in the background (log: .repowise/.coverage.log);+get_change_risk reads it once the ingest finishes."++The ingest replaces the stored coverage, so the hook is conservative. It acts+only in a repository that has ingested coverage before, only on a run that+does not target some tests (a path, a `::` node id, `-k`, `-run`, `-t`,+`--testNamePattern` or `--filter` makes a run partial, and a partial report+must not replace full-suite coverage), never on a coverage.py `.coverage`+database alone, and not when discovery is customised (`auto_discover: false`+without `paths`, or custom `artifacts` globs). A `.repowise/.coverage.queued`+marker keeps a second test run from spawning over an ingest already running+for the same reports. It costs a few file stats and one SQLite read, only+after a test command, and reads only a repo-local index. A report that only a+`**` discovery pattern finds is not watched: name it in `coverage.paths`. Turn+it off with `hooks.coverage_reingest: false` in `.repowise/config.yaml`+(`REPOWISE_HOOK_COVERAGE_REINGEST=0` for one session).+## The inferred tier: no coverage report neededEverything above needs an ingest. Most repositories never do one, and the layerdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 98fdd3717..42941dc90 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1342,7 +1342,13 @@ are out of scope and only counted.Each changed file carries its risk: git bug-fix history always, plus hotspot,bug-magnet and dependent counts when an index opens (a missing index neverfails the check). Rows, annotations and the markdown table list risky files-first, and the table has a "Risk" column in words.+first, and the table has a "Risk" column in words. With an index, each+uncovered range also names the test file to extend when one is found: an+"Extend" column in the table and markdown ("extend tests/test_auth.py+(inferred: calls reach `login`)", "(measured: runs other lines of `login`)",+"(inferred: imports this file)", or "no test reaches this; add one"), the same+phrase at the end of each annotation, and `hints` in `json`. Hints never+change the verdict.`github` writes up to 10 `::warning` annotations (riskiest file, then largestuncovered range, first; titled "Uncovered change in a risky file" for a risky@@ -1358,7 +1364,9 @@ carries `patch_coverage_pct`, `covered_line_count`, `coverable_line_count`,`out_of_scope`), `files[]` (`file_path`, `status`, `changed_line_count`,`coverable_line_count`, `covered_line_count`, `patch_coverage_pct`,`uncovered_ranges`, `risk`: `fix_pressure`, `dependents`, `hotspot`,-`bug_magnet`, `basis`, `risky`, `reasons`), `scope` (`label`,+`bug_magnet`, `basis`, `risky`, `reasons`; `hints`, null without an index, one+per uncovered range: `range`, `symbol`, `tests`, `basis` (`per_test`,+`call_graph`, `import_graph`, `none`), `total`), `scope` (`label`,`source_formats`, `reports`, `report_path_count`,`unmatched_report_path_count`, `ignored_file_count`, `config_errors`),`path_gates[]` (`name`, `paths`, `threshold`, `informational`,diff --git a/docs/start/CI.md b/docs/start/CI.mdindex 24397dd34..04585809b 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -426,7 +426,9 @@ dependents", "none known", or "unknown" when it could not be read). A file isrisky when the index flags it a hotspot or a bug magnet; without an index, orfor a file the change adds, when its recency-weighted bug-fix weight from gitis in the top quartile of the files with bug-fix history. The report says-which basis each row used when not every file had index data.+which basis each row used when not every file had index data. When an index is+present, each annotation also names the test file to extend when one is found+("Extend tests/test_auth.py (inferred: calls reach `login`)").`--fail-under-risky` (the action's `coverage-fail-under-risky`) adds one moregate, stricter, over the risky files' changed lines alone, and the check failsdiff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.pyindex 4567960cf..2d3674686 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py@@ -139,9 +139,13 @@ def _extract_output_text(tool_output: object) -> str:MAX_OUTPUT_CHARS = 10_000-def hook_flag_enabled(repo_path: Path, flag: str) -> bool:+def hook_flag_enabled(repo_path: Path, flag: str, *, default: bool = False) -> bool:"""True when ``hooks.<flag>`` is on for this repo. Fails closed.+ *default* answers when the config or the key is absent; a surface that is+ on by default passes ``True`` and is switched off by ``<flag>: false``. A+ config that cannot be read or parsed still reads as off.+Every hook surface that *replaces* a tool result is opt-in behind one ofthese, and they are all written by the single init consent (see:func:`repowise.cli.helpers.save_hook_surface_enabled`). The env override@@ -158,8 +162,11 @@ def hook_flag_enabled(repo_path: Path, flag: str) -> bool:override = os.environ.get(f"REPOWISE_HOOK_{flag.upper()}")if override is not None:return override.strip().lower() in ("1", "true", "yes", "on")+ path = repo_path / ".repowise" / "config.yaml"try:- text = (repo_path / ".repowise" / "config.yaml").read_text(encoding="utf-8")+ text = path.read_text(encoding="utf-8")+ except FileNotFoundError:+ return defaultexcept (OSError, ValueError):# ValueError covers UnicodeDecodeError: a config with a latin-1 byte in# it means "cannot tell", which for an opt-in means no.@@ -168,13 +175,13 @@ def hook_flag_enabled(repo_path: Path, flag: str) -> bool:# not this key is the common case, and it should not pay ~70ms to learn so.# The parse below is still what decides; this only rules out.if flag not in text:- return False+ return defaulttry:import yamldata = yaml.safe_load(text) or {}hooks = data.get("hooks")- return bool(isinstance(hooks, dict) and hooks.get(flag) is True)+ return bool(isinstance(hooks, dict) and hooks.get(flag, default) is True)except Exception:return Falsediff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.pyindex b05463471..8070f461d 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py@@ -42,6 +42,10 @@ registers it any more — see :mod:`.codex`.)the wiki HEAD has drifted from .repowise/state.json's last synccommit AND no `repowise update` is in flight AND we haven'talready warned for this HEAD, emit a one-line stale-wiki notice.+ * After a full test run (pytest, go test, npm test, cargo test, ...),+ when aggregate coverage reports are newer than the index's last+ coverage ingest, start ``repowise coverage add`` on them in the+ background and say so in one line (``hooks.coverage_reingest``).PostToolUse → Read* Skeleton replacement: an unbounded Read of a large indexed file is@@ -99,6 +103,7 @@ from repowise.cli.agent_adapters import adapter_forfrom ._shared import HookResult, as_result, join_noticesfrom .bash_staleness import _handle_bash_postfrom .codex import _handle_codex_context_event, _handle_post_edit_use+from .coverage_reingest import coverage_reingest_noticefrom .decision_capture import commit_capture_noticefrom .read_state import _handle_edit_post, _handle_read_post, _record_editfrom .search import _handle_search_post@@ -394,6 +399,7 @@ def _handle_post_tool_use(join_notices(_handle_bash_post(tool_input, tool_output, cwd),commit_capture_notice(tool_input, tool_output, cwd, session_id),+ coverage_reingest_notice(tool_input, cwd),))if tool_name in adapter.search_tool_names:diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py b/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.pynew file mode 100644index 000000000..e226cbc85--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py@@ -0,0 +1,380 @@+"""PostToolUse Bash: re-ingest the coverage a test run just wrote.++An agent that runs the tests and then asks ``get_change_risk`` whether its+change is covered should get an answer about the run it just did, not the one+before. So after a command that runs a whole test suite, when an aggregate+coverage report on disk is newer than the index's last coverage ingest, the+hook starts ``repowise coverage add`` on exactly those reports in the+background and says so in one line.++It writes the store without being asked, so it is conservative: on by default+but switched off by ``hooks.coverage_reingest: false`` (or+``REPOWISE_HOOK_COVERAGE_REINGEST=0``); only in a repo that has ingested+coverage before; never for a run that targets some tests (a partial report+would replace full-suite coverage); never when discovery is customised in a+way this hook cannot follow; and never raising.++Cost is a few stats and one indexed SQLite read, only after a test command:+every other Bash call returns before touching the disk.+"""++from __future__ import annotations++import contextlib+import json+import re+import shlex+import time+from pathlib import Path++from ._shared import _find_repo_root, hook_flag_enabled++#: Report locations checked when ``coverage.paths`` is not set: the literal+#: (glob-free) entries of ``discovery.DEFAULT_DISCOVERY_GLOBS``. Spelled out+#: rather than imported because the discovery package costs ~1s to import;+#: kept in step by ``test_default_reports_match_discovery``. Ceiling: a report+#: only a ``**`` glob finds is not watched; name it in ``coverage.paths``.+DEFAULT_REPORTS = (+ "coverage/lcov.info",+ "lcov.info",+ "coverage.lcov",+ "coverage/cobertura.xml",+ "coverage/cobertura-coverage.xml",+ "coverage.xml",+ "coverage/coverage.xml",+ "coverage/clover.xml",+ "coverage.out",+ "cover.out",+ "target/site/jacoco/jacoco.xml",+)++QUEUED_FILENAME = ".coverage.queued"+LOG_FILENAME = ".coverage.log"++#: A queued marker older than this no longer blocks a spawn: the ingest it+#: stood for crashed or finished long ago.+QUEUED_STALE_AFTER_SECONDS = 10 * 60++#: Test runners the rewrite hook's ``test_output`` family does not name.+#: ``coverage run`` is a wrapper, peeled off before matching.+_EXTRA_TEST_RE = re.compile(+ r"^(?:cargo llvm-cov\b|mvn test\b|gradlew? test\b|bun test\b|npm run test[\w:-]*)"+)+_SEGMENT_SPLIT = re.compile(r"\|\||&&|[|;\n]")+_PREFIX_RE = re.compile(r"^(?:time|timeout\s+\S+|coverage run(?:\s+-m)?)\s+")+_DISTILL_RE = re.compile(r"^repowise distill(?:\s+--source\s+\S+)?\s+(?P<rest>.+)$", re.DOTALL)++#: Arguments that pick some tests out of a suite.+_TARGETING = ("-k", "-run", "-t", "--testnamepattern", "--filter", "--tests", "-dtest")+#: Positional arguments that still mean the whole suite.+_WHOLE_SUITE = frozenset({".", "./...", "...", "run", "--"})+++def is_test_command(command: object) -> bool:+ """Whether *command* runs a test suite, in any segment."""+ return any(_segment_kind(s) is not None for s in _segments(command))+++def is_full_test_run(command: object) -> bool:+ """Whether *command* runs a whole suite: a test command no segment narrows.++ Conservative on purpose: an argument that might name a test (a path, a+ ``::`` node id, ``-k``, ``-run``, ``-t``, ``--testNamePattern``,+ ``--filter``) marks the run partial. Ceiling: an option value that looks+ like a path after a short flag (``-p no:x``) also reads as partial, so such+ a run is not re-ingested; ``repowise coverage add`` by hand still is.+ """+ kinds = [_segment_kind(s) for s in _segments(command)]+ return any(k is not None for k in kinds) and "partial" not in kinds+++def _segments(command: object) -> list[str]:+ """The command's simple commands, the distill wrapper and prefixes peeled off."""+ if isinstance(command, list): # Codex sends argv+ command = " ".join(str(c) for c in command)+ if not isinstance(command, str):+ return []+ if unwrapped := _undistill(command.strip()):+ # Before splitting: the rewritten form quotes a whole chain as one token.+ return _segments(unwrapped)+ out = []+ for raw in _SEGMENT_SPLIT.split(command):+ segment = raw.strip()+ if unwrapped := _undistill(segment):+ out += _segments(unwrapped)+ elif segment:+ out.append(segment)+ return out+++def _undistill(segment: str) -> str | None:+ """The command inside ``repowise distill [--source X] <cmd>``, else ``None``."""+ m = _DISTILL_RE.match(segment)+ if m is None:+ return None+ rest = m.group("rest").strip()+ with contextlib.suppress(ValueError):+ tokens = shlex.split(rest)+ if len(tokens) == 1: # the rewritten form wraps one quoted token+ rest = tokens[0]+ return rest+++def _segment_kind(segment: str) -> str | None:+ """``"full"`` or ``"partial"`` for a test command, ``None`` for anything else."""+ from repowise.cli.rewrite_hook import FAMILY_PATTERNS, _normalize++ test_re = dict(FAMILY_PATTERNS)["test_output"]+ cmd = segment+ for _ in range(4):+ previous = cmd+ cmd = _PREFIX_RE.sub("", _normalize(cmd))+ if cmd == previous:+ break+ match = test_re.match(cmd) or _EXTRA_TEST_RE.match(cmd)+ if match is None:+ return None+ # A script suffix glued to the match (``npm run test:unit``) is still the name.+ args = re.sub(r"^\S+", "", cmd[match.end():])+ return "partial" if _targets_some(args) else "full"+++def _targets_some(args: str) -> bool:+ try:+ tokens = shlex.split(args)+ except ValueError:+ return True # cannot tell, so do not replace full-suite coverage+ previous = ""+ for token in tokens:+ if _is_targeting_flag(token) or _names_some_tests(token, previous):+ return True+ previous = token+ return False+++def _is_targeting_flag(token: str) -> bool:+ """``-k``, ``--filter=x``, ``-Dtest=Foo``, a ``::`` node id: picks tests out."""+ low = token.lower()+ return "::" in token or any(low == t or low.startswith(t + "=") for t in _TARGETING)+++def _names_some_tests(token: str, previous: str) -> bool:+ """A positional argument (not a long option's value) that is not "the whole suite"."""+ if token.startswith("-") or token in _WHOLE_SUITE:+ return False+ return not (previous.startswith("--") and "=" not in previous)+++def coverage_reingest_notice(tool_input: dict, cwd: str) -> str | None:+ """Spawn a background ``coverage add`` after a full test run with fresh reports.++ ``None`` (silence) in every other case, and on any error: the hook must+ never be the reason an agent's tool call reads as failed. Test runs often+ exit non-zero with a report written, so the exit code is not consulted.+ """+ try:+ return _notice(tool_input, cwd)+ except Exception:+ # The hook never raises: any failure is silence (no logger on this path).+ return None+++def _notice(tool_input: dict, cwd: str) -> str | None:+ if not is_full_test_run(tool_input.get("command")):+ return None+ found = _local_index(cwd)+ if found is None:+ return None+ repo, db = found+ fresh = _fresh_reports(repo, db)+ if not fresh:+ return None+ newest = max(mtime for _path, mtime in fresh)+ if _already_queued(repo, newest):+ return None+ paths = [path for path, _mtime in fresh]+ spawn_coverage_add(repo, paths)+ _write_queued(repo, newest)+ names = ", ".join(_rel(repo, p) for p in paths)+ return (+ f"[repowise] Re-ingesting coverage from {names} in the background "+ f"(log: .repowise/{LOG_FILENAME}); get_change_risk reads it once the ingest finishes."+ )+++def _local_index(cwd: str) -> tuple[Path, Path] | None:+ """``(repo root, wiki.db)`` when the repo has a local index and the hook is on."""+ repo = _find_repo_root(Path(cwd))+ if repo is None:+ return None+ db = repo / ".repowise" / "wiki.db"+ # Ceiling: an index configured elsewhere (REPOWISE_DB_URL) is not read+ # here; `coverage add` by hand still works.+ if not db.is_file() or not hook_flag_enabled(repo, "coverage_reingest", default=True):+ return None+ return repo, db+++def _fresh_reports(repo: Path, db: Path) -> list[tuple[Path, float]]:+ """Watched reports newer than the last ingest; none when the repo never ingested."""+ candidates = _candidates(repo)+ if not candidates:+ return []+ last = last_ingest_time(db)+ if not last:+ return [] # never ingested (0.0) or unreadable (None): not ours to start+ return [(path, mtime) for path, mtime in _existing(repo, candidates) if mtime > last]+++def _candidates(repo: Path) -> tuple[str, ...]:+ """The report paths to watch, or ``()`` when the config says not to guess.++ ``coverage.paths`` when set. Otherwise the default locations, unless+ discovery is off or customised: ``auto_discover: false`` with no paths+ means reports are named by hand, and custom ``artifacts`` globs are ones+ this hook does not expand (ceiling: those repos re-ingest by hand).+ """+ block = _coverage_block(repo)+ if block is None:+ return ()+ paths = block.get("paths")+ if isinstance(paths, str):+ return (paths,)+ if isinstance(paths, list) and paths:+ return tuple(str(p) for p in paths if p)+ if block.get("auto_discover", True) is False or block.get("artifacts"):+ return ()+ return DEFAULT_REPORTS+++def _coverage_block(repo: Path) -> dict | None:+ """``coverage:`` from ``.repowise/config.yaml``; ``{}`` when absent, ``None`` when unreadable.++ A substring check first, like ``_shared.hook_flag_enabled``, so a config+ without the block never pays for the yaml import.+ """+ try:+ text = (repo / ".repowise" / "config.yaml").read_text(encoding="utf-8")+ except FileNotFoundError:+ return {}+ except (OSError, ValueError):+ return None+ if "coverage" not in text:+ return {}+ try:+ import yaml++ block = (yaml.safe_load(text) or {}).get("coverage")+ except Exception:+ # The hook never raises: a config that does not parse reads as "cannot tell".+ return None+ return block if isinstance(block, dict) else {}+++def _existing(repo: Path, candidates: tuple[str, ...]) -> list[tuple[Path, float]]:+ """``(path, mtime)`` of the aggregate text reports among *candidates* that exist.++ A coverage.py ``.coverage`` database is skipped: it only feeds the per-test+ map, and ingesting it alone would stamp the older aggregate rows current.+ """+ found = []+ for rel in candidates:+ path = repo / rel+ if path.name.startswith(".coverage"):+ continue+ with contextlib.suppress(OSError):+ if path.is_file():+ found.append((path, path.stat().st_mtime))+ return found+++def _rel(repo: Path, path: Path) -> str:+ try:+ return path.relative_to(repo).as_posix()+ except ValueError:+ return path.as_posix()+++def last_ingest_time(db: Path) -> float | None:+ """Epoch seconds of the newest coverage ingest; ``0.0`` when none; ``None`` when unreadable."""+ import sqlite3++ try:+ con = sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True, timeout=0.1)+ except sqlite3.Error:+ return None+ try:+ raw = _newest_ingested_at(con)+ except sqlite3.Error:+ return None+ finally:+ con.close()+ if raw is _NO_TABLE:+ return None+ return 0.0 if raw is None else _epoch(raw)+++#: :func:`_newest_ingested_at` found neither table: an index too old to say.+_NO_TABLE = object()+++def _newest_ingested_at(con) -> object:+ """``MAX(ingested_at)`` from the ingest history, else the coverage rows."""+ import sqlite3++ found: object = _NO_TABLE+ for table in ("coverage_ingests", "coverage_files"):+ try:+ found = con.execute(f"SELECT MAX(ingested_at) FROM {table}").fetchone()[0]+ except sqlite3.OperationalError:+ continue # an index older than the table+ if found is not None:+ return found+ # Empty: an index upgraded from before the ingest history keeps its+ # ingests only on the coverage rows, so read those next.+ return found+++def _epoch(raw: object) -> float | None:+ """A stored ``ingested_at`` as epoch seconds; ``None`` when it does not parse."""+ from datetime import UTC, datetime++ try:+ at = datetime.fromisoformat(str(raw))+ except ValueError:+ return None+ # Stored in UTC; SQLite keeps no zone.+ return (at if at.tzinfo else at.replace(tzinfo=UTC)).timestamp()+++def _already_queued(repo: Path, newest: float) -> bool:+ """A recent spawn already covers reports this new."""+ try:+ marker = json.loads((repo / ".repowise" / QUEUED_FILENAME).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return False+ queued_at, report_mtime = marker.get("queued_at"), marker.get("report_mtime")+ if not isinstance(queued_at, (int, float)) or not isinstance(report_mtime, (int, float)):+ return False+ return time.time() - queued_at <= QUEUED_STALE_AFTER_SECONDS and report_mtime >= newest+++def _write_queued(repo: Path, newest: float) -> None:+ with contextlib.suppress(OSError):+ (repo / ".repowise" / QUEUED_FILENAME).write_text(+ json.dumps({"queued_at": time.time(), "report_mtime": newest}), encoding="utf-8"+ )+++def spawn_coverage_add(repo: Path, reports: list[Path]) -> None:+ """Start ``repowise coverage add <reports>`` detached, logging to ``.repowise/.coverage.log``.++ The log is truncated per spawn, so it holds the last ingest only.+ """+ import sys++ from repowise.cli.spawn import spawn_detached++ argv = [sys.executable, "-m", "repowise.cli.main", "coverage", "add", "--path", str(repo)]+ with open(repo / ".repowise" / LOG_FILENAME, "wb") as log:+ spawn_detached([*argv, *(str(p) for p in reports)], str(repo), log)diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.pyindex 581baaea8..bae818adf 100644--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py@@ -126,7 +126,8 @@ def coverage_check(Each changed file carries its risk (git bug-fix history, plus hotspot,bug-magnet and dependent counts when an index exists), and the rows read- riskiest first. ``--fail-under-risky`` gates the risky files alone.+ riskiest first. ``--fail-under-risky`` gates the risky files alone. With an+ index, each uncovered range also names the test file to extend."""notices = ci_notices(fmt)try:@@ -134,6 +135,7 @@ def coverage_check(revspec, reports, report_format, fail_under, min_coverable_lines, repo, notices)pc = _with_risk(repo, pc, fail_under_risky)+ pc = _with_hints(repo, pc)except CannotEvaluateError as exc:cannot_evaluate(fmt, exc.code, str(exc))_emit(pc, fmt)@@ -358,6 +360,40 @@ async def _index_facts(root: Path, paths: list[str]) -> dict:return {}+def _with_hints(repo, pc):+ """*pc* with the test to extend per uncovered range, when an index opens.++ Hints are advice, never part of the verdict, so a missing or unreadable+ index leaves the rows without them (``hints`` null) and the gate as it was.+ """+ from repowise.core import git_refs+ from repowise.core.analysis.change_risk.features import revspec_head+ from repowise.core.analysis.patch_coverage import attach_hints++ root = repo_root(repo)+ if not has_db_store(root):+ return pc+ head = git_refs.resolve(str(root), revspec_head(pc.scope.label or None)) or None+ try:+ hints = run_async(_read_hints(root, pc, head))+ except Exception:+ # Advice only: whatever an old or damaged index does to the read, the+ # gate's verdict must not change because of it.+ hints = None+ return pc if hints is None else attach_hints(pc, hints)+++async def _read_hints(root: Path, pc, head: str | None):+ """``{path: hints}`` from the index; ``None`` when it cannot say."""+ from repowise.core.analysis.patch_coverage import read_test_hints++ async with repo_index_session(root) as opened:+ if opened is None:+ return None+ session, repo_id = opened+ return await read_test_hints(session, repo_id, pc, repo_path=str(root), head_commit=head)++def _resolve_reports(root, cfg, report_prefixes, report_format, notices):"""Parse the reports against the files git tracks, failing when nothing usable remains."""from repowise.core import git_refs@@ -492,23 +528,32 @@ def _print_table(pc) -> None:RANGE_LIMIT,STATUS_TEXT,attention_rows,+ first_hint,format_ranges,+ hint_phrase,risk_words,)rows = attention_rows(pc)if not rows:return+ with_hint = any(f.hints for f in rows)table = Table(show_edge=False, pad_edge=False)table.add_column("File")table.add_column("Risk")table.add_column("Covered", justify="right")table.add_column("Uncovered changed lines")+ if with_hint:+ table.add_column("Extend")for f in rows:if f.status == "measured":covered = f"{f.covered_line_count} of {f.coverable_line_count}"gaps = format_ranges(f.uncovered_ranges, RANGE_LIMIT)else:covered, gaps = "", STATUS_TEXT[f.status]- table.add_row(escape(f.file_path), escape(risk_words(f.risk)), covered, gaps)+ cells = [escape(f.file_path), escape(risk_words(f.risk)), covered, gaps]+ if with_hint:+ hint = first_hint(f)+ cells.append(escape(hint_phrase(hint)) if hint else "")+ table.add_row(*cells)console.print(table)diff --git a/packages/cli/src/repowise/cli/platform/telemetry/emitter.py b/packages/cli/src/repowise/cli/platform/telemetry/emitter.pyindex 601b5d8f1..c89d584a9 100644--- a/packages/cli/src/repowise/cli/platform/telemetry/emitter.py+++ b/packages/cli/src/repowise/cli/platform/telemetry/emitter.py@@ -27,12 +27,12 @@ import atexitimport contextlibimport jsonimport os-import subprocessimport sysfrom repowise.cli.platform import identity, settingsfrom repowise.cli.platform.telemetry import environment, spoolfrom repowise.cli.platform.telemetry.events import TelemetryEvent+from repowise.cli.spawn import spawn_detached#: Module the detached flusher runs as._FLUSHER_MODULE = "repowise.cli.platform.telemetry.flusher"@@ -106,20 +106,7 @@ def _spawn_flusher() -> bool:"""if not sys.executable:return False- kwargs: dict[str, object] = {- "stdin": subprocess.DEVNULL,- "stdout": subprocess.DEVNULL,- "stderr": subprocess.DEVNULL,- "close_fds": True,- "cwd": os.getcwd(),- }- if os.name == "nt":- # DETACHED_PROCESS | CREATE_NO_WINDOW: no console window flashes up- # in front of the user between commands.- kwargs["creationflags"] = 0x00000008 | 0x08000000- else:- kwargs["start_new_session"] = True- subprocess.Popen([sys.executable, "-m", _FLUSHER_MODULE], **kwargs) # type: ignore[arg-type]+ spawn_detached([sys.executable, "-m", _FLUSHER_MODULE], os.getcwd())return Truediff --git a/packages/cli/src/repowise/cli/spawn.py b/packages/cli/src/repowise/cli/spawn.pynew file mode 100644index 000000000..923083c78--- /dev/null+++ b/packages/cli/src/repowise/cli/spawn.py@@ -0,0 +1,34 @@+"""Start a process that outlives this one. Stdlib only: hooks import it."""++from __future__ import annotations++import os+import subprocess+from typing import IO++#: DETACHED_PROCESS | CREATE_NO_WINDOW: no console window flashes up in front+#: of the user. CREATE_BREAKAWAY_FROM_JOB is deliberately absent: under a job+#: that forbids breakaway, CreateProcess then fails outright, and a child kept+#: in the job only dies with it, which the callers here tolerate.+_WINDOWS_FLAGS = 0x00000008 | 0x08000000+++def spawn_detached(argv: list[str], cwd: str, stdout: IO[bytes] | int | None = None) -> None:+ """Run *argv* in *cwd* in its own session or console, never waited on.++ No stdin; stdout and stderr go to *stdout* (a file opened by the caller)+ or nowhere, so the child can never write into the parent's terminal.+ """+ sink = subprocess.DEVNULL if stdout is None else stdout+ kwargs: dict[str, object] = {+ "stdin": subprocess.DEVNULL,+ "stdout": sink,+ "stderr": sink,+ "close_fds": True,+ "cwd": cwd,+ }+ if os.name == "nt":+ kwargs["creationflags"] = _WINDOWS_FLAGS+ else:+ kwargs["start_new_session"] = True+ subprocess.Popen(argv, **kwargs) # type: ignore[call-overload]diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.pyindex af7e169a7..009365aae 100644--- a/packages/core/src/repowise/core/analysis/changed_lines.py+++ b/packages/core/src/repowise/core/analysis/changed_lines.py@@ -49,6 +49,8 @@ class FileDiff:nothing it replaced); it records its *insert_anchors* instead - the old-sideline the new lines went in after, which is the only handle SZZ has on codethat was added rather than rewritten. 0 means "inserted at the top".+ *hunks* keeps each hunk's ``(old_start, old_count, new_start, new_count)``,+ what :func:`map_old_line` needs to move an old line number to the new side."""path: str@@ -57,6 +59,36 @@ class FileDiff:insert_anchors: list[int] = field(default_factory=list)removed: list[str] = field(default_factory=list)added: list[str] = field(default_factory=list)+ hunks: list[tuple[int, int, int, int]] = field(default_factory=list)+++def map_old_line(hunks: Iterable[tuple[int, int, int, int]], line: int, *, end: bool = False) -> int:+ """Where old-side *line* sits on the new side of a diff with these *hunks*.++ A line outside every hunk moves by what the hunks above it added or+ removed. A line inside a rewritten hunk maps to the hunk's new first line,+ or its new last line with *end*, so a span keeps covering its rewrite.+ """+ delta = 0+ for old_start, old_count, new_start, new_count in sorted(hunks):+ if not old_count:+ # A pure insertion after ``old_start``: moves only the lines below it.+ delta += new_count if line > old_start else 0+ elif line >= old_start + old_count:+ delta += new_count - old_count+ elif line >= old_start:+ return _inside_hunk(new_start, new_count, end=end)+ else:+ break # hunks are sorted, so none further up can move this line+ return line + delta+++def _inside_hunk(new_start: int, new_count: int, *, end: bool) -> int:+ """Where a line a hunk rewrote lands: its new first line, or last with *end*."""+ if new_count == 0:+ # Deleted outright: git names the new-side line the block sat after.+ return new_start if end else new_start + 1+ return new_start + new_count - 1 if end else new_start_C_ESCAPES = {"a": 7, "b": 8, "t": 9, "n": 10, "v": 11, "f": 12, "r": 13}@@ -128,6 +160,7 @@ def parse_unified_diff(diff: str) -> dict[str, FileDiff]:old_count = int(m.group(2)) if m.group(2) is not None else 1new_start = int(m.group(3))new_count = int(m.group(4)) if m.group(4) is not None else 1+ current.hunks.append((old_start, old_count, new_start, new_count))if old_count > 0:current.old_ranges.append((old_start, old_start + old_count - 1))elif new_count > 0:@@ -175,12 +208,18 @@ def _verify_ref(repo_path: str, ref: str) -> None:raise ValueError(f"unknown revision {ref!r}")+def working_tree_label(base: str | None = None) -> str:+ """How :func:`changed_lines` names a working-tree diff from *base*."""+ return f"{base}...working tree" if base and base != "HEAD" else "working tree"++def changed_lines(repo_path: str,revspec: str | None = None,*,staged: bool = False,working_tree: bool = False,+ base: str | None = None,) -> tuple[dict[str, set[int]], str]:"""Return ``({file: changed_lines}, label)`` for a change.@@ -188,16 +227,17 @@ def changed_lines(``base...head`` the change since the two forked, a bare ref a single commit. With no *revspec* (or *staged*), the staged diff(``git diff --cached``) is used - the "what will I commit" case.*working_tree* widens that to everything ``HEAD`` does not have, staged or- not, matching what change risk counts for an uncommitted change. *label*- is a human string naming what was diffed. Raises ``ValueError`` on an- unknown revision so the caller can fail loudly rather than silently+ not, matching what change risk counts for an uncommitted change. With+ *base* as well, it diffs the working tree from the merge-base of *base*+ and ``HEAD``, untracked files included (every line changed): everything a+ push of this branch would bring. A *base* that does not resolve, or shares+ no merge-base, falls back to the plain working-tree diff and its label.+ *label* is a human string naming what was diffed. Raises ``ValueError`` on+ an unknown revision so the caller can fail loudly rather than silentlyreporting "no changes"."""if working_tree:- # Untracked files are absent by design: they are new, so neither caller- # (prior fixes, per-test coverage) has a row to find for them anyway.- diff = _git(["diff", "--unified=0", *DIFF_PREFIXES, "HEAD"], repo_path)- return _parse_unified_diff(diff), "working tree"+ return _working_tree_lines(repo_path, base)if staged or not revspec:diff = _git(["diff", "--cached", "--unified=0", *DIFF_PREFIXES], repo_path)@@ -225,6 +265,61 @@ def changed_lines(return _parse_unified_diff(_diff(repo_path, args)), revspec+def _working_tree_lines(repo_path: str, base: str | None) -> tuple[dict[str, set[int]], str]:+ """The working-tree half of :func:`changed_lines`: from *base*'s merge-base, else ``HEAD``."""+ start = _merge_base_or_empty(repo_path, base) if base and base != "HEAD" else ""+ if start:+ diff = _git(["diff", "--unified=0", *DIFF_PREFIXES, start], repo_path)+ changed = _parse_unified_diff(diff)+ changed.update(_untracked_lines(repo_path))+ return changed, working_tree_label(base)+ diff = _git(["diff", "--unified=0", *DIFF_PREFIXES, "HEAD"], repo_path)+ changed = _parse_unified_diff(diff)+ if base:+ # Asked for what a push brings, with no merge-base to diff from: new+ # files are still part of it. Without a base this is what the commit+ # would change, and untracked files stay out by design.+ changed.update(_untracked_lines(repo_path))+ return changed, working_tree_label()+++def _merge_base_or_empty(repo_path: str, base: str) -> str:+ """The merge-base of *base* and ``HEAD``; ``""`` when *base* is unknown or unrelated."""+ try:+ _verify_ref(repo_path, base)+ return _diff(repo_path, ["merge-base", base, "HEAD"]).strip()+ except ValueError:+ return ""+++def _untracked_lines(repo_path: str) -> dict[str, set[int]]:+ """Every line of each untracked, not-ignored file: new code a push would add."""+ out: dict[str, set[int]] = {}+ listing = _git(["ls-files", "--others", "--exclude-standard", "-z"], repo_path)+ for path in filter(None, listing.split("\0")):+ try:+ data = (Path(repo_path) / path).read_bytes()+ except OSError:+ continue+ count = data.count(b"\n") + (1 if data and not data.endswith(b"\n") else 0)+ if count:+ out[path] = set(range(1, count + 1))+ return out+++def diff_since(+ repo_path: str, since: str, until: str | None, paths: Iterable[str]+) -> dict[str, FileDiff]:+ """Per-file diff of *paths* from *since* to *until* (the working tree when ``None``).++ What moves a line number read at one commit (an index's symbol spans) to+ the code being asked about (:func:`map_old_line` over ``FileDiff.hunks``).+ """+ tail = [until] if until else []+ args = ["diff", "--unified=0", *DIFF_PREFIXES, since, *tail, "--", *paths]+ return parse_unified_diff(_diff(repo_path, args))++def _diff(repo_path: str, args: list[str]) -> str:"""Run a diff, turning git's refusal (e.g. no merge-base) into ``ValueError``."""try:diff --git a/packages/core/src/repowise/core/analysis/health/coverage/freshness.py b/packages/core/src/repowise/core/analysis/health/coverage/freshness.pyindex 52e0bb85f..dcd6590a3 100644--- a/packages/core/src/repowise/core/analysis/health/coverage/freshness.py+++ b/packages/core/src/repowise/core/analysis/health/coverage/freshness.py@@ -4,10 +4,17 @@ One rule for every surface: coverage is ``current`` when it was measured atthe commit in question, ``stale`` when at another, ``unknown`` when eithercommit is missing. Callers differ only in which commit they ask about (theindexed tree, a change's head).++Uncommitted work has no commit to compare, so it gets the one rule time can+give (:func:`working_tree_freshness`): coverage ingested after the last edit+to every changed file ran against the code on disk."""from __future__ import annotations+from collections.abc import Iterable+from datetime import UTC, datetime+from pathlib import Pathfrom typing import LiteralFreshnessStatus = Literal["current", "stale", "unknown"]@@ -20,3 +27,31 @@ def coverage_freshness(if not measured_commit or not reference_commit:return "unknown"return "current" if measured_commit == reference_commit else "stale"+++def working_tree_freshness(+ ingested_at: datetime | None, newest_mtime: float | None+) -> FreshnessStatus:+ """Freshness of coverage ingested at *ingested_at* for files last modified at *newest_mtime*.++ ``current`` when the ingest came after the newest modification of the+ changed files on disk, else ``stale``; ``unknown`` when either time is+ missing. Ceiling: an ingest of an old report after the last edit reads+ current, because the report's own run time is not stored.+ """+ if ingested_at is None or newest_mtime is None:+ return "unknown"+ # SQLite hands back the stored UTC time without its zone.+ at = ingested_at if ingested_at.tzinfo else ingested_at.replace(tzinfo=UTC)+ return "current" if at.timestamp() > newest_mtime else "stale"+++def newest_mtime(repo_root: str | Path, paths: Iterable[str]) -> float | None:+ """The latest modification time among *paths* on disk; ``None`` when none exists."""+ times = []+ for path in paths:+ try:+ times.append((Path(repo_root) / path).stat().st_mtime)+ except OSError:+ continue+ return max(times, default=None)diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.pyindex babd206dd..1c1e4e7ce 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py@@ -12,6 +12,14 @@ from .compute import (compute_patch_coverage,patch_coverage_from_resolved,)+from .hints import (+ TestHint,+ attach_hints,+ build_hints,+ first_hint,+ hint_phrase,+ read_test_hints,+)from .render import (RANGE_LIMIT,STATUS_TEXT,@@ -51,19 +59,25 @@ __all__ = ["PatchCoverage","PatchScope","PathGateResult",+ "TestHint","assess_risks",+ "attach_hints","attach_risk","attention_rows",+ "build_hints","compute_patch_coverage",+ "first_hint","fmt_pct","format_ranges","github_annotations","headline",+ "hint_phrase","patch_coverage_from_resolved","path_gate_row","path_gate_verdict","read_git_fix_history","read_index_facts",+ "read_test_hints","render_markdown","risk_basis_line","risk_unreadable",diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.pyindex bacecd574..67868b1c7 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py@@ -41,6 +41,7 @@ from ..health.coverage.model import FileCoverageif TYPE_CHECKING:from ..health.coverage.discovery import PathGate, ResolvedCoverage+ from .hints import TestHintfrom .risk import FileRiskFileStatus = Literal["measured", "not_in_report", "no_line_data", "no_coverable_changes"]@@ -60,6 +61,9 @@ class FilePatchCoverage:uncovered_ranges: tuple[tuple[int, int], ...] = ()# What history says about the file (``risk.attach_risk``); ``None`` unread.risk: FileRisk | None = None+ # Where to add a test per uncovered range (``hints.attach_hints``); ``None``+ # without an index, empty when there is nothing to hint.+ hints: tuple[TestHint, ...] | None = None@propertydef patch_coverage_pct(self) -> float | None:@@ -79,6 +83,7 @@ class FilePatchCoverage:"patch_coverage_pct": _round(self.patch_coverage_pct),"uncovered_ranges": [list(r) for r in self.uncovered_ranges],"risk": self.risk.to_dict() if self.risk is not None else None,+ "hints": None if self.hints is None else [h.to_dict() for h in self.hints],}diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/hints.py b/packages/core/src/repowise/core/analysis/patch_coverage/hints.pynew file mode 100644index 000000000..53b3e891b--- /dev/null+++ b/packages/core/src/repowise/core/analysis/patch_coverage/hints.py@@ -0,0 +1,402 @@+"""Where to add a test for each uncovered range of a change.++A range with no covering test is a question ("which test should grow?") the+index can answer, so every uncovered range carries a :class:`TestHint`: the+innermost indexed symbol around it and the test files best placed to extend.++Evidence is tried strongest first, and the first that names a test answers:++* ``per_test`` (measured): the per-test coverage map (``coverage add`` on a+ report with contexts) has tests that ran other lines of the same symbol, or+ lines within :data:`WINDOW` of a range outside any symbol. Used only when the+ patch coverage is ``current``: the map's line numbers are ingest-time ones.+* ``call_graph`` (inferred): tests whose calls reach that symbol+ (``tests_reaching_by_tier`` seeded with the symbol id, so a test reaching a+ neighbour in the same file does not count).+* ``import_graph`` (inferred): tests that import the file. File-level.+* ``none``: nothing names a test; the range needs a new one.++Symbol spans are line numbers at the indexed commit, and the ranges are line+numbers in the change. When the two differ, each span is moved through the+diff between them (:func:`translate_spans`); a range in code added since the+index outside every moved span (a new function) has no symbol and falls to+file-level evidence.++The assembly is pure; :func:`read_test_hints` does the batched reads.+"""++from __future__ import annotations++import logging+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass, replace+from typing import TYPE_CHECKING, Any, Literal++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import AsyncSession++ from ..test_reachability import ReachedBy+ from .compute import FilePatchCoverage, PatchCoverage++log = logging.getLogger(__name__)++HintBasis = Literal["per_test", "call_graph", "import_graph", "none"]++#: Test files named per range, best first; ``total`` counts the rest.+TEST_LIMIT = 3++#: Lines either side of a range outside any symbol that a per-test hit may use.+WINDOW = 5++#: Uncovered ranges shown per file before "+N more", and hinted per file (the+#: first ones in line order): a hint is never computed for a range no surface+#: lists, and a file with hundreds of gaps stays bounded.+RANGE_LIMIT = 8++#: Seeds per graph walk. Each walk binds its seeds as one ``IN`` list, so a+#: change touching thousands of symbols must not reach SQLite's bound-variable+#: limit. Ceiling: past it, the later symbols and files get no graph evidence+#: (their hints read ``none`` unless per-test coverage answers).+MAX_SEEDS = 200++_REACHED_BASIS: dict[str, HintBasis] = {"call-graph": "call_graph", "import-graph": "import_graph"}+++@dataclass(frozen=True)+class SymbolSpan:+ """One indexed symbol's lines."""++ symbol_id: str+ qualified_name: str+ start_line: int+ end_line: int+++@dataclass(frozen=True)+class TestHint:+ """Where to extend the tests for one uncovered range."""++ __test__ = False # not a pytest class, whatever its name says++ range: tuple[int, int]+ #: The innermost indexed symbol containing the range start; ``None`` outside any.+ symbol: str | None+ tests: tuple[str, ...]+ basis: HintBasis+ #: How many test files qualified before :data:`TEST_LIMIT` cut ``tests``.+ total: int++ def to_dict(self) -> dict[str, Any]:+ return {+ "range": list(self.range),+ "symbol": self.symbol,+ "tests": list(self.tests),+ "basis": self.basis,+ "total": self.total,+ }+++def innermost_symbol(spans: Iterable[SymbolSpan], line: int) -> SymbolSpan | None:+ """The narrowest span containing *line*: a method over its class."""+ containing = [s for s in spans if s.start_line <= line <= s.end_line]+ return min(+ containing,+ key=lambda s: (s.end_line - s.start_line, -s.start_line, s.symbol_id),+ default=None,+ )+++def translate_spans(+ spans: Iterable[SymbolSpan], hunks: Iterable[tuple[int, int, int, int]]+) -> list[SymbolSpan]:+ """*spans* moved from the indexed commit to the change's line numbers.++ A symbol the diff deleted outright (its end lands above its start) is+ dropped.+ """+ from ..changed_lines import map_old_line++ hunks = list(hunks)+ out = []+ for s in spans:+ start = map_old_line(hunks, s.start_line)+ end = map_old_line(hunks, s.end_line, end=True)+ if end >= start:+ out.append(replace(s, start_line=start, end_line=end))+ return out+++def hint_ranges(f: FilePatchCoverage) -> tuple[tuple[int, int], ...]:+ """The ranges of *f* a hint is computed for."""+ return f.uncovered_ranges[:RANGE_LIMIT]+++def _per_test(rows: Sequence[Mapping[str, Any]], lo: int, hi: int) -> list[str]:+ """Test files whose covered lines fall in ``[lo, hi]``, most lines first."""+ hits: dict[str, int] = {}+ for row in rows:+ # A test id without a file is named by its id's path part, as the+ # workspace test impact reads it.+ test_file = row.get("test_file") or str(row.get("test_id", "")).split("::", 1)[0]+ count = sum(1 for line in row.get("covered_lines") or () if lo <= line <= hi)+ if test_file and count:+ hits[test_file] = max(hits.get(test_file, 0), count)+ return sorted(hits, key=lambda t: (-hits[t], t))+++def build_hints(+ f: FilePatchCoverage,+ spans: Sequence[SymbolSpan],+ per_test: Sequence[Mapping[str, Any]],+ reached: Mapping[str, ReachedBy],+) -> tuple[TestHint, ...]:+ """One :class:`TestHint` per hinted range of *f*.++ *spans* are the file's symbols in the change's line numbers, *per_test*+ its per-test coverage rows (``tests_covering_files``; pass none when they+ may describe other code), *reached* the graph walk keyed by symbol id+ (call graph) and by file path (import graph).+ """+ hints = []+ for a, b in hint_ranges(f):+ sym = innermost_symbol(spans, a)+ tests, basis, total = _evidence(f.file_path, sym, (a, b), per_test, reached)+ hints.append(+ TestHint(+ range=(a, b),+ symbol=sym.qualified_name if sym else None,+ tests=tuple(tests[:TEST_LIMIT]),+ basis=basis,+ total=total,+ )+ )+ return tuple(hints)+++def _evidence(+ path: str,+ sym: SymbolSpan | None,+ rng: tuple[int, int],+ per_test: Sequence[Mapping[str, Any]],+ reached: Mapping[str, ReachedBy],+) -> tuple[Sequence[str], HintBasis, int]:+ """``(tests, basis, total)`` for one range: per-test first, then the graph."""+ a, b = rng+ lo, hi = (sym.start_line, sym.end_line) if sym else (a - WINDOW, b + WINDOW)+ if tests := _per_test(per_test, lo, hi):+ return tests, "per_test", len(tests)+ for key in ((sym.symbol_id,) if sym else ()) + (path,):+ by = reached.get(key)+ # A tier this module does not know is no evidence at all.+ if by is not None and by.tests and by.via in _REACHED_BASIS:+ return by.tests, _REACHED_BASIS[by.via], by.total+ return (), "none", 0+++def attach_hints(pc: PatchCoverage, hints: Mapping[str, tuple[TestHint, ...]]) -> PatchCoverage:+ """*pc* with every measured row's hints set; a row with no gap gets none."""+ files = tuple(+ replace(f, hints=hints.get(f.file_path, ())) if f.status == "measured" else f+ for f in pc.files+ )+ return replace(pc, files=files)+++def hint_phrase(hint: TestHint) -> str:+ """How every surface words a hint, measured and inferred kept apart.++ ``"extend tests/test_auth.py (inferred: calls reach `login`)"``; a hint+ naming no test reads ``"no test reaches this; add one"``. The UI's+ ``hintReason`` mirrors this wording.+ """+ if not hint.tests:+ return "no test reaches this; add one"+ where = f"`{hint.symbol}`" if hint.symbol else None+ why = {+ "per_test": (+ f"measured: runs other lines of {where}" if where else "measured: runs nearby lines"+ ),+ "call_graph": f"inferred: calls reach {where or 'this code'}",+ "import_graph": "inferred: imports this file",+ }[hint.basis]+ return f"extend {hint.tests[0]} ({why})"+++def first_hint(f: FilePatchCoverage) -> TestHint | None:+ """The file's first hint that names a test, else its first hint, else ``None``."""+ hints = f.hints or ()+ return next((h for h in hints if h.tests), hints[0] if hints else None)+++async def read_test_hints(+ session: AsyncSession,+ repository_id: str,+ pc: PatchCoverage,+ *,+ repo_path: str | None = None,+ head_commit: str | None = None,+ working_tree: bool = False,+) -> dict[str, tuple[TestHint, ...]] | None:+ """``{path: hints}`` for every measured file with uncovered ranges; ``None`` on failure.++ Hints are advice, so any failure (an old index, a git error) is logged and+ reads as ``None``, never raised. *repo_path* names the checkout the ranges+ were read from, at *head_commit* or in the *working_tree*, so symbol spans+ stored at another commit can be moved there. Without *repo_path* the spans+ are taken as stored.+ """+ try:+ return await _read_test_hints(+ session, repository_id, pc, repo_path, head_commit, working_tree+ )+ except Exception:+ # Advice never breaks the caller: any failure is logged and reads as no hints.+ log.warning("patch_coverage_hints_failed", exc_info=True)+ return None+++async def _read_test_hints(+ session: AsyncSession,+ repository_id: str,+ pc: PatchCoverage,+ repo_path: str | None,+ head_commit: str | None,+ working_tree: bool,+) -> dict[str, tuple[TestHint, ...]]:+ """Batched reads for the whole change: symbols, per-test rows, the reverse test walk."""+ from repowise.core.persistence.crud.analysis.coverage_map import tests_covering_files++ files = [f for f in pc.with_status("measured") if f.uncovered_ranges]+ if not files:+ return {}+ paths = sorted(f.file_path for f in files)+ spans = await _read_spans(session, repository_id, paths)+ if spans and repo_path:+ indexed = await _indexed_commit(session, repository_id)+ spans = await _spans_at_change(repo_path, indexed, head_commit, working_tree, spans)++ # Per-test line numbers are the ingest's; only coverage current for this+ # change vouches that they are the change's too.+ per_test: Mapping[str, list] = {}+ if pc.scope.freshness == "current":+ per_test = await tests_covering_files(session, repository_id, set(paths))++ placed = {+ f.file_path: [innermost_symbol(spans.get(f.file_path, ()), a) for a, _b in hint_ranges(f)]+ for f in files+ }+ reached = await _walk_tests(session, repository_id, placed)+ return {+ f.file_path: build_hints(+ f, spans.get(f.file_path, ()), per_test.get(f.file_path, ()), reached+ )+ for f in files+ }+++async def _read_spans(+ session: AsyncSession, repository_id: str, paths: list[str]+) -> dict[str, list[SymbolSpan]]:+ """The stored symbols of *paths*, at the indexed commit's line numbers."""+ from sqlalchemy import select++ from repowise.core.persistence.models import WikiSymbol++ rows = await session.execute(+ select(+ WikiSymbol.file_path,+ WikiSymbol.symbol_id,+ WikiSymbol.qualified_name,+ WikiSymbol.start_line,+ WikiSymbol.end_line,+ ).where(WikiSymbol.repository_id == repository_id, WikiSymbol.file_path.in_(paths))+ )+ spans: dict[str, list[SymbolSpan]] = {}+ for path, symbol_id, name, start, end in rows:+ spans.setdefault(path, []).append(SymbolSpan(symbol_id, name, start, end))+ return spans+++async def _indexed_commit(session: AsyncSession, repository_id: str) -> str | None:+ from sqlalchemy import select++ from repowise.core.persistence.models import Repository++ return await session.scalar(+ select(Repository.head_commit).where(Repository.id == repository_id)+ )+++async def _walk_tests(+ session: AsyncSession,+ repository_id: str,+ placed: Mapping[str, list[SymbolSpan | None]],+) -> dict[str, ReachedBy]:+ """The reverse test walk, keyed by symbol id (call tier) and by file (import tier).++ Twice, the way the workspace test impact does: the call tier keyed by+ symbol id so each range is credited only with tests reaching its own+ symbol, then the import tier for only the files a range still needs it+ for. The test-file set is read once for both.+ """+ from ..test_reachability import load_test_files, tests_reaching_by_tier++ symbol_ids = sorted({s.symbol_id for syms in placed.values() for s in syms if s})[:MAX_SEEDS]+ test_files = await load_test_files(session, repository_id)+ reached: dict[str, ReachedBy] = {}+ if symbol_ids:+ reached.update(+ await tests_reaching_by_tier(+ session,+ repository_id,+ symbol_ids,+ import_depth=0,+ symbol_seeds={sid: {sid} for sid in symbol_ids},+ test_files=test_files,+ )+ )+ unanswered = [+ path+ for path in sorted(placed)+ if any(s is None or s.symbol_id not in reached for s in placed[path])+ ][:MAX_SEEDS]+ if unanswered:+ reached.update(+ await tests_reaching_by_tier(+ session, repository_id, unanswered, call_depth=0, test_files=test_files+ )+ )+ return reached+++async def _spans_at_change(+ repo_path: str,+ indexed: str | None,+ head_commit: str | None,+ working_tree: bool,+ spans: dict[str, list[SymbolSpan]],+) -> dict[str, list[SymbolSpan]]:+ """*spans* in the change's line numbers; ``{}`` when that cannot be worked out.++ No spans is the honest fallback: a symbol placed by stale line numbers+ would send the reader to the wrong test. Runs one ``git diff`` for all the+ files, off the event loop.+ """+ import asyncio+ import subprocess++ from ..changed_lines import diff_since++ if not indexed:+ return {}+ if not working_tree and indexed == head_commit:+ return spans+ until = None if working_tree else head_commit or "HEAD"+ try:+ diffs = await asyncio.to_thread(diff_since, repo_path, indexed, until, sorted(spans))+ except (ValueError, subprocess.SubprocessError, OSError):+ return {} # the indexed commit is gone (a rebase, a shallow clone)+ return {+ path: translate_spans(found, diffs[path].hunks) if path in diffs else found+ for path, found in spans.items()+ }diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.pyindex 81c2dda8a..e17022e2d 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py@@ -4,7 +4,8 @@ Markdown is what a CI step summary or a pull-request comment shows, so it iswritten to be read once and acted on: the verdict in words on the first linewith its denominator, the diff, report and file counts on the second, anddetail only for what needs attention. A passing change with no gaps is two-lines. A file the report never named reads "not in report", never 0%.+lines. A file the report never named reads "not in report", never 0%. With+an index, each gap names the test to extend (``hints``).Workflow-command and markdown mechanics (escaping, caps, collapsed lists)come from :mod:`repowise.core.ci`, shared with every other CI gate.@@ -18,11 +19,9 @@ from collections.abc import Sequencefrom ...ci import githubfrom ...ci.markdown import ROW_LIMIT, cell, details, more_line, pluralfrom .compute import FilePatchCoverage, PatchCoverage, PathGateResult+from .hints import RANGE_LIMIT, TestHint, first_hint, hint_phrasefrom .risk import FileRisk-#: Uncovered ranges shown per file before "+N more".-RANGE_LIMIT = 8-#: How a file that could not be measured reads, wherever it is listed.STATUS_TEXT = {"not_in_report": "not in report",@@ -279,26 +278,34 @@ def _gap_table(pc: PatchCoverage) -> list[str]:gaps = [f for f in attention_rows(pc) if f.status == "measured"]if not gaps:return []- if any(f.risk is not None for f in pc.files):- out = ["", "| File | Risk | Uncovered changed lines | Covered |", "|---|---|---|---|"]- out += [- f"| `{cell(f.file_path)}` | {cell(risk_words(f.risk))} | "- f"{format_ranges(f.uncovered_ranges, RANGE_LIMIT)} | "- f"{f.covered_line_count} of {f.coverable_line_count} |"- for f in gaps[:ROW_LIMIT]- ]- else:- out = ["", "| File | Uncovered changed lines | Covered |", "|---|---|---|"]- out += [- f"| `{cell(f.file_path)}` | {format_ranges(f.uncovered_ranges, RANGE_LIMIT)} | "- f"{f.covered_line_count} of {f.coverable_line_count} |"- for f in gaps[:ROW_LIMIT]- ]+ out = ["", *_gap_rows(pc, gaps[:ROW_LIMIT])]if len(gaps) > ROW_LIMIT:out += ["", more_line(len(gaps) - ROW_LIMIT, "files with uncovered changed lines")]return out+def _gap_rows(pc: PatchCoverage, rows: list[FilePatchCoverage]) -> list[str]:+ """The uncovered-lines table; Risk and Extend columns only when something fills them."""+ with_risk = any(f.risk is not None for f in pc.files)+ with_hint = any(f.hints for f in rows)+ head = ["File", *(["Risk"] if with_risk else []), "Uncovered changed lines", "Covered"]+ head += ["Extend"] if with_hint else []+ lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]+ for f in rows:+ cells = [f"`{cell(f.file_path)}`"]+ cells += [cell(risk_words(f.risk))] if with_risk else []+ cells += [+ format_ranges(f.uncovered_ranges, RANGE_LIMIT),+ f"{f.covered_line_count} of {f.coverable_line_count}",+ ]+ if with_hint:+ hint = first_hint(f)+ # The phrase's backticks are code spans; everything between is escaped.+ cells.append("`".join(cell(p) for p in hint_phrase(hint).split("`")) if hint else "")+ lines.append("| " + " | ".join(cells) + " |")+ return lines++def github_annotations(pc: PatchCoverage) -> list[str]:"""GitHub Actions workflow commands for a change's patch coverage.@@ -346,6 +353,9 @@ def _range_annotation(f: FilePatchCoverage, a: int, b: int) -> str:message = f"Changed {_span(a, b)} not covered by tests"if risky:message += f" ({risk_words(f.risk)})"+ if hint := _hint_for(f, a, b):+ phrase = hint_phrase(hint)+ message += f". {phrase[:1].upper()}{phrase[1:]}"return github.annotation("warning",message,@@ -356,6 +366,11 @@ def _range_annotation(f: FilePatchCoverage, a: int, b: int) -> str:)+def _hint_for(f: FilePatchCoverage, a: int, b: int) -> TestHint | None:+ """The hint for range ``(a, b)``, when the index gave one."""+ return next((h for h in f.hints or () if h.range == (a, b)), None)++def format_ranges(ranges: Sequence[tuple[int, int]], limit: int | None = None) -> str:"""``((1, 3), (7, 7))`` -> ``"1-3, 7"``, with ``+N more`` past *limit*."""shown = ranges if limit is None else ranges[:limit]diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.pyindex bc9b1e787..bce77261e 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py@@ -12,7 +12,7 @@ from typing import TYPE_CHECKINGfrom sqlalchemy.ext.asyncio import AsyncSession-from ..health.coverage.freshness import coverage_freshness+from ..health.coverage.freshness import coverage_freshness, working_tree_freshnessfrom .compute import PatchCoverage, PatchScope, compute_patch_coveragefrom .risk import IndexFacts@@ -29,6 +29,7 @@ async def stored_patch_coverage(head_commit: str | None = None,threshold: float | None = None,config: CoverageConfig | None = None,+ working_tree_mtime: float | None = None,) -> PatchCoverage | None:"""Patch coverage of *changed* against stored coverage; ``None`` when none is stored.@@ -40,6 +41,10 @@ async def stored_patch_coverage(head and with no ``gate_errors`` (invalid ``coverage.gates`` entries), theonly coverage and config the CLI gate itself judges; otherwise they read``no_data`` and the scope carries the errors.+ For a change that ends in the working tree, pass *working_tree_mtime* (the+ newest modification time of the changed files) instead of *head_commit*: no+ commit names that code, so freshness is whether the last ingest came after+ it (``working_tree_freshness``)."""from repowise.core.persistence.crud import (get_coverage_summary,@@ -58,7 +63,10 @@ async def stored_patch_coverage(coverage = await load_file_coverage(session, repository_id, file_paths=wanted) if wanted else {}commit = summary["ingested_commit_sha"]paths = summary["report_paths"]- freshness = coverage_freshness(commit, head_commit)+ if working_tree_mtime is not None:+ freshness = working_tree_freshness(summary["ingested_at"], working_tree_mtime)+ else:+ freshness = coverage_freshness(commit, head_commit)cfg = config or CoverageConfig()return compute_patch_coverage(changed,diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.pyindex 0cce03177..2a1dac574 100644--- a/packages/core/src/repowise/core/analysis/test_reachability.py+++ b/packages/core/src/repowise/core/analysis/test_reachability.py@@ -419,9 +419,14 @@ async def tests_reaching_by_tier(call_depth: int = DEFAULT_CALL_DEPTH,import_depth: int = DEFAULT_MAX_DEPTH,symbol_seeds: Mapping[str, Collection[str]] | None = None,+ test_files: set[str] | None = None,) -> dict[str, ReachedBy]:""":func:`tests_reaching`, also saying which tier answered each target.+ *test_files* is :func:`load_test_files`'s answer, for a caller that walks+ more than once and need not read it twice. A target may be a symbol id+ (``path::name``); its tests are ranked against the file part.+*symbol_seeds* narrows the call walk for the targets it names: the walkenters at exactly those symbol ids instead of at every symbol the filedeclares. A target it does not name, or names with no ids, keeps the@@ -444,7 +449,8 @@ async def tests_reaching_by_tier(if not seeds:return {}- test_files = await load_test_files(session, repo_id)+ if test_files is None:+ test_files = await load_test_files(session, repo_id)if not test_files:return {}@@ -454,7 +460,7 @@ async def tests_reaching_by_tier(session, repo_id, seeds, test_files, call_depth, symbol_seeds=symbol_seeds)for seed, tests in found.items():- ordered = tuple(rank_tests(seed, tests))+ ordered = tuple(rank_tests(seed.split("::", 1)[0], tests))out[seed] = ReachedBy(list(ordered[:MAX_TESTS_PER_TARGET]), "call-graph", len(ordered), ordered)@@ -463,7 +469,7 @@ async def tests_reaching_by_tier(if unanswered and import_depth >= 1:found = await _import_reaching(session, repo_id, unanswered, test_files, import_depth)for seed, tests in found.items():- ordered = tuple(rank_tests(seed, tests))+ ordered = tuple(rank_tests(seed.split("::", 1)[0], tests))out[seed] = ReachedBy(list(ordered[:MAX_TESTS_PER_TARGET]), "import-graph", len(ordered), ordered)diff --git a/packages/server/src/repowise/server/mcp_server/_change_health.py b/packages/server/src/repowise/server/mcp_server/_change_health.pyindex 001a47f8a..3519f2d04 100644--- a/packages/server/src/repowise/server/mcp_server/_change_health.py+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py@@ -85,6 +85,47 @@ def _render_action(action: ReviewAction, inspected: int) -> str | None:return action.explanation+def patch_coverage_action(block: dict[str, Any] | None) -> str | None:+ """The next action for uncovered changed lines, or ``None`` when there are none.++ Names the scope and the tests to extend from the rows' hints, riskiest+ file first, so the agent writes the missing test where the suite already+ exercises the code. Stale coverage leads instead: its gaps are not real yet.+ """+ uncovered = block["coverable_line_count"] - block["covered_line_count"] if block else 0+ if uncovered <= 0:+ return None+ lines = f"{uncovered} changed executable line{'' if uncovered == 1 else 's'}"+ lines += _scope_words(block["scope"].get("label") or "")+ if block["scope"]["freshness"] == "stale":+ # Stale line numbers describe other code: the fix is a fresh run first.+ return (+ "Stored coverage predates this change: re-run the tests with coverage, then "+ "`repowise coverage add` (the hook does it automatically) and call again "+ f"({lines} read as uncovered until then)"+ )+ tests = _hinted_tests(block["files"])+ text = f"{lines} {'is' if uncovered == 1 else 'are'} uncovered; "+ if tests:+ return text + f"extend {', '.join(tests[:_TESTS_SHOWN])}"+ return text + "add tests for them (patch_coverage.files)"+++def _hinted_tests(rows: list[dict[str, Any]]) -> list[str]:+ """Each hint's first test, in row order (riskiest file first), once each."""+ firsts = (hint["tests"][0] for row in rows for hint in row.get("hints") or () if hint["tests"])+ return list(dict.fromkeys(firsts))+++def _scope_words(label: str) -> str:+ """``" since origin/main"`` for a branch diff, ``" in <label>"`` otherwise."""+ if "..." in label:+ return f" since {label.split('...', 1)[0]}"+ if label == "working tree":+ return " in the working tree"+ return f" in {label}" if label else ""++def health_delta_block(delta: ChangeHealthDelta, *, revspec: str | None) -> dict[str, Any]:"""The compact delta: what got worse, how much was compared, and how sure."""emitted = delta.findings[:TOP_FINDINGS_LIMIT]diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex d41acb9ba..5305e454a 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -48,6 +48,9 @@ from repowise.server.mcp_server._change_health import (from repowise.server.mcp_server._change_health import (health_delta_block as _health_delta_block,)+from repowise.server.mcp_server._change_health import (+ patch_coverage_action as _patch_coverage_action,+)from repowise.server.mcp_server._helpers import (_get_repo,_is_workspace_mode,@@ -149,7 +152,8 @@ async def get_change_risk(change is not cleared.``impacted_tests`` keeps measured coverage and inferred candidates distinct.- ``patch_coverage`` is the share of changed executable lines stored coverage ran.+ ``patch_coverage`` is the share of changed executable lines stored coverage+ ran (no revspec: from the merge-base); ``hints`` name tests to extend.``fix_history`` is the changed files' bug-fix record, ``overlap`` the pastfixes on these exact lines. ``branch_overlap`` names other branches editingthem. ``diff_shape`` is one line on size, not a danger verdict. An empty@@ -230,8 +234,16 @@ async def get_change_risk(payload["impacted_tests"] = await _impacted_tests_block(ctx, changed, changed_error, collector)+ patch_changed, patch_error, patch_label, patch_revspec = await _push_change(+ str(ctx.path),+ revspec,+ result.working_tree,+ normalize_extensions(tuple(extensions or ())),+ result.riskignore_excludes + result.request_excludes,+ (changed, changed_error),+ )patch = await _patch_coverage_block(- ctx, changed, changed_error, revspec, result, collector+ ctx, patch_changed, patch_error, patch_revspec, result, collector, label=patch_label)if patch is not None:payload["patch_coverage"] = patch@@ -410,8 +422,11 @@ def _attach_health(payload: dict, delta: Any, revspec: str | None, *, expand: boblock["findings_emitted"] = len(delta.findings)block.pop("findings_reduced_reason", None)block.pop("all_findings_via", None)+ directive = _directive(delta, payload.get("impacted_tests"))+ if action := _patch_coverage_action(payload.get("patch_coverage")):+ directive["next_actions"].append(action)ordered = {- "directive": _directive(delta, payload.get("impacted_tests")),+ "directive": directive,"health_delta": block,}for key, value in payload.items():@@ -760,26 +775,49 @@ async def _changed_in_scope(without each re-reading git. Shared because ``changed_lines`` shells out andtwo blocks want the same answer."""+ changed, error, _label = await _changed_with_label(+ repo_path, revspec, extensions, exclude_patterns, working_tree=working_tree+ )+ return changed, error+++async def _changed_with_label(+ repo_path: str,+ revspec: str | None,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ *,+ working_tree: bool = False,+ base: str | None = None,+) -> tuple[dict[str, set[int]], tuple[str, str] | None, str | None]:+ """:func:`_changed_in_scope` plus the label ``changed_lines`` gave what it read.++ *base* widens a working-tree read to the merge-base with it, untracked+ files included, and falls back to the plain working tree (label and all)+ when the base does not resolve.+ """from repowise.core.analysis.changed_lines import changed_lines+ label = Nonetry:- changed, _label = await asyncio.to_thread(+ changed, label = await asyncio.to_thread(partial(changed_lines,repo_path,revspec or "HEAD",working_tree=working_tree,+ base=base,))except ValueError as exc:- return {}, ("unknown", f"Could not read changed lines: {exc}")+ return {}, ("unknown", f"Could not read changed lines: {exc}"), labelexcept (subprocess.SubprocessError, OSError):- return {}, ("unknown", "Could not read changed lines from git.")+ return {}, ("unknown", "Could not read changed lines from git."), labelchanged = _filter_changed(changed, extensions, exclude_patterns)if not changed:- return {}, ("no_source_line_changes", "No changed source lines to map to tests.")- return changed, None+ return {}, ("no_source_line_changes", "No changed source lines to map to tests."), label+ return changed, None, labelasync def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[str, Any] | None:@@ -1101,6 +1139,55 @@ async def _inferred_impacted(return block+async def _push_change(+ repo_path: str,+ revspec: str | None,+ working_tree: bool,+ extensions: tuple[str, ...],+ exclude_patterns: tuple[str, ...],+ scored: tuple[dict[str, set[int]], tuple[str, str] | None],+) -> tuple[dict[str, set[int]], tuple[str, str] | None, str | None, str | None]:+ """``(changed, error, label, revspec)`` the patch-coverage block measures.++ An explicit *revspec* is measured as given (*scored*, the lines the score+ read). Without one an agent is checking its work before a push, so the+ patch is everything the push brings, the branch's commits and any+ uncommitted edits, and the self-check does not shrink to the last commit+ once it lands: ``<base>...working tree`` when dirty, ``<base>...HEAD``+ when clean. No resolvable base keeps what was scored.+ """+ changed, error = scored+ if revspec is not None:+ return changed, error, None, revspec+ base = await asyncio.to_thread(_push_base, repo_path)+ if not working_tree and base == "HEAD":+ return changed, error, None, revspec+ branch = None if working_tree else f"{base}...HEAD"+ found, found_error, label = await _changed_with_label(+ repo_path, branch, extensions, exclude_patterns, working_tree=working_tree, base=base+ )+ if found_error is not None and branch is not None:+ # No merge-base with the base (a shallow clone): measure the commit as scored.+ return changed, error, None, revspec+ return found, found_error, label, branch+++def _push_base(repo_path: str) -> str:+ """The branch a push of this checkout is reviewed against, else ``HEAD``.++ The base ``repowise coverage check`` would diff from in CI, so an agent's+ self-check and the pull request's gate measure the same lines.+ """+ from repowise.core.analysis.change_risk.features import split_revspec+ from repowise.core.ci.base import BaseNotFoundError, default_revspec++ try:+ parts = split_revspec(default_revspec(repo_path))+ except (BaseNotFoundError, subprocess.SubprocessError, OSError):+ return "HEAD"+ return parts[0] if parts else "HEAD"++async def _patch_coverage_block(ctx: Any,changed: dict[str, set[int]],@@ -1108,6 +1195,8 @@ async def _patch_coverage_block(revspec: str | None,result: Any,collector: OmissionCollector,+ *,+ label: str | None = None,) -> dict[str, Any] | None:"""Share of the change's executable lines the stored coverage ran, or ``None``.@@ -1119,17 +1208,26 @@ async def _patch_coverage_block(``coverage.min_coverable_lines`` and the path-scoped ``coverage.gates``apply as they do in the CLI gate; path gates read ``no_data`` on stalecoverage or invalid config, which ``scope.config_errors`` names. Each row- carries its file's risk, from the index and the checkout's git history.+ carries its file's risk, from the index and the checkout's git history, and+ ``hints``: the test file to extend per uncovered range.++ With no revspec, *changed* is what a push would bring (the caller diffs+ from the merge-base with the push base, *label* names it). For uncommitted+ work no commit names that code, so freshness is by time: ``current`` when+ the last coverage ingest came after the newest edit to the changed files."""from repowise.core import git_refsfrom repowise.core.analysis.change_risk.features import revspec_headfrom repowise.core.analysis.health.coverage import configured_coverage+ from repowise.core.analysis.health.coverage.freshness import newest_mtimefrom repowise.core.analysis.patch_coverage import (assess_risks,+ attach_hints,attach_risk,attention_rows,read_git_fix_history,read_index_facts,+ read_test_hints,stored_patch_coverage,)from repowise.core.persistence.database import get_session@@ -1137,9 +1235,10 @@ async def _patch_coverage_block(session_factory = getattr(ctx, "session_factory", None)if session_factory is None or changed_error is not None or not changed:return None- # Uncommitted edits were never measured, so no commit can vouch for them.- head_commit = None- if not result.working_tree:+ head_commit = mtime = None+ if result.working_tree:+ mtime = await asyncio.to_thread(newest_mtime, ctx.path, changed)+ else:head_commit = git_refs.resolve(str(ctx.path), revspec_head(revspec)) or Noneindex: dict = {}try:@@ -1149,16 +1248,28 @@ async def _patch_coverage_block(session,repo_id,changed,- label=result.features.ref,+ label=label or result.features.ref,head_commit=head_commit,config=configured_coverage(ctx.path),+ working_tree_mtime=mtime,)- # An unreadable index row leaves risk to git alone.+ # An unreadable index row leaves risk to git alone and hints null.if patch is not None:with contextlib.suppress(SQLAlchemyError):index = await read_index_facts(session, repo_id, [f.file_path for f in patch.files])+ # Advice: read_test_hints logs any failure and returns None.+ hints = await read_test_hints(+ session,+ repo_id,+ patch,+ repo_path=str(ctx.path),+ head_commit=head_commit,+ working_tree=result.working_tree,+ )+ if hints is not None:+ patch = attach_hints(patch, hints)except (LookupError, SQLAlchemyError):return Noneif patch is None:diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.pyindex 23dceb6b4..6f73c3e71 100644--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py@@ -381,16 +381,19 @@ async def health_coverage_patch(``coverage.ignore`` and judges the path-scoped gates in ``coverage.gates``(with ``coverage.min_coverable_lines``) on current coverage and validconfig; the whole-change threshold stays with the CLI gate. Each file row- carries its risk, from the index and the checkout's git history.+ carries its risk, from the index and the checkout's git history, and the+ test to extend per uncovered range."""from sqlalchemy.exc import SQLAlchemyErrorfrom repowise.core.analysis.health.coverage import configured_coveragefrom repowise.core.analysis.patch_coverage import (assess_risks,+ attach_hints,attach_risk,read_git_fix_history,read_index_facts,+ read_test_hints,stored_patch_coverage,)@@ -410,6 +413,12 @@ async def health_coverage_patch(index = await read_index_facts(session, repo.id, paths)except SQLAlchemyError:index = {}+ # Advice: a failed read is logged inside and leaves hints null.+ hints = await read_test_hints(+ session, repo.id, patch, repo_path=repo.local_path, head_commit=head_sha or None+ )+ if hints is not None:+ patch = attach_hints(patch, hints)git = await asyncio.to_thread(read_git_fix_history, repo.local_path, f"{base}...{head}")patch = attach_risk(patch, assess_risks(paths, git, index))return PatchCoverageResponse.model_validate(patch.to_dict())diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex a5b97b683..d1ec42a27 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -224,6 +224,7 @@ if TYPE_CHECKING:PatchCoverageResponse,PatchCoverageRisky,PatchCoverageScope,+ PatchCoverageTestHint,)from .refactoring import (RefactoringOpportunitiesResponse,@@ -503,6 +504,7 @@ _EXPORTS: dict[str, tuple[str, ...]] = {"PatchCoverageResponse","PatchCoverageRisky","PatchCoverageScope",+ "PatchCoverageTestHint",),"refactoring": ("RefactoringOpportunitiesResponse",@@ -765,6 +767,7 @@ __all__ = ["PatchCoverageResponse","PatchCoverageRisky","PatchCoverageScope",+ "PatchCoverageTestHint","PopulationBreakdown","ProviderEntry","ProviderStatusResponse",diff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.pyindex 270e22193..a2eb79347 100644--- a/packages/server/src/repowise/server/schemas/patch_coverage.py+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py@@ -10,6 +10,7 @@ from pydantic import BaseModel, ConfigDictfrom repowise.core.analysis.health.coverage.freshness import FreshnessStatusfrom repowise.core.analysis.patch_coverage.compute import FileStatus, GateStatus+from repowise.core.analysis.patch_coverage.hints import HintBasisfrom repowise.core.analysis.patch_coverage.risk import RiskBasis@@ -33,6 +34,23 @@ class PatchCoverageFileRisk(_Strict):reasons: list[str]+class PatchCoverageTestHint(_Strict):+ """Where to extend the tests for one uncovered range."""++ #: Inclusive ``[start, end]``, one of the row's ``uncovered_ranges``.+ range: list[int]+ #: Innermost indexed symbol containing the range start; null outside any.+ symbol: str | None+ #: Up to three test files, best first.+ tests: list[str]+ #: ``per_test`` (measured per-test coverage of the same symbol or nearby+ #: lines) beats ``call_graph`` (tests reaching the symbol), which beats+ #: ``import_graph`` (tests importing the file); ``none`` names no test.+ basis: HintBasis+ #: How many test files qualified before the cap.+ total: int++class PatchCoverageFile(_Strict):file_path: strstatus: FileStatus@@ -45,6 +63,8 @@ class PatchCoverageFile(_Strict):uncovered_ranges: list[list[int]]#: Null when the file's risk was not assessed.risk: PatchCoverageFileRisk | None+ #: One per uncovered range (the first eight); null without an index.+ hints: list[PatchCoverageTestHint] | Noneclass PatchCoverageFileCounts(_Strict):diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex f4d9e3cf2..3bfbc2b9c 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2201,6 +2201,7 @@ export interface PatchCoverageFile {patch_coverage_pct: number | null;uncovered_ranges: number[][];risk: PatchCoverageFileRisk | null;+ hints: PatchCoverageTestHint[] | null;}export interface PatchCoverageFileCounts {@@ -2272,6 +2273,15 @@ export interface PatchCoverageScope {config_errors: string[];}+/** Where to extend the tests for one uncovered range. */+export interface PatchCoverageTestHint {+ range: number[];+ symbol: string | null;+ tests: string[];+ basis: "per_test" | "call_graph" | "import_graph" | "none";+ total: number;+}+/*** What the map is counting.*diff --git a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx b/packages/ui/__tests__/health/patch-coverage-summary.test.tsxindex e723f0d72..59bbe1851 100644--- a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx+++ b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx@@ -8,6 +8,7 @@ import {PatchCoverageSummary,floorPct,formatLineRanges,+ hintReason,riskWords,} from "../../src/health/patch-coverage-summary.js";@@ -35,6 +36,7 @@ function coverage(fileCount: number): PatchCoverageResponse {patch_coverage_pct: 50,uncovered_ranges: [[i + 1, i + 1]],risk: null,+ hints: null,})),scope: {label: "coverage.xml",@@ -175,6 +177,7 @@ describe("PatchCoverageSummary", () => {[7, 9],],risk: null,+ hints: null,},{file_path: "src/new.ts",@@ -185,6 +188,7 @@ describe("PatchCoverageSummary", () => {patch_coverage_pct: null,uncovered_ranges: [],risk: null,+ hints: null,},],scope: { ...base.scope, freshness: "stale" },@@ -322,6 +326,79 @@ describe("PatchCoverageSummary", () => {]);expect(screen.getAllByText("not in report")).toHaveLength(2);});++ it("names the test to extend from the file's first hint that has one", () => {+ const base = coverage(2);+ const [withHint, without] = base.files;+ render(+ <PatchCoverageSummary+ coverage={{+ ...base,+ files: [+ {+ ...withHint!,+ hints: [+ { range: [1, 1], symbol: null, tests: [], basis: "none", total: 0 },+ {+ range: [4, 5],+ symbol: "login",+ tests: ["tests/test_auth.py", "tests/test_session.py"],+ basis: "call_graph",+ total: 2,+ },+ ],+ },+ // An index with nothing to suggest shows no line at all.+ { ...without!, hints: [] },+ ],+ }}+ />,+ );+ expect(screen.getByText("tests/test_auth.py")).toBeTruthy();+ const line = screen.getByTitle(+ "extend tests/test_auth.py (inferred: calls reach login)",+ );+ expect(line.className).toContain("text-xs");+ expect(screen.queryByText("tests/test_session.py")).toBeNull();+ expect(screen.getAllByText(/^extend/)).toHaveLength(1);+ });++ it("says so when the index names no test", () => {+ const base = coverage(1);+ render(+ <PatchCoverageSummary+ coverage={{+ ...base,+ files: [+ {+ ...base.files[0]!,+ hints: [{ range: [1, 1], symbol: null, tests: [], basis: "none", total: 0 }],+ },+ ],+ }}+ />,+ );+ expect(screen.getByText("no test reaches this; add one")).toBeTruthy();+ });+});++describe("hintReason", () => {+ it("says which evidence named the test, measured or inferred", () => {+ const hint = { range: [1, 2], symbol: "run", tests: ["t.py"], total: 1 };+ expect(hintReason({ ...hint, basis: "per_test" })).toBe(+ "measured: runs other lines of run",+ );+ expect(hintReason({ ...hint, symbol: null, basis: "per_test" })).toBe(+ "measured: runs nearby lines",+ );+ expect(hintReason({ ...hint, basis: "call_graph" })).toBe("inferred: calls reach run");+ expect(hintReason({ ...hint, basis: "import_graph" })).toBe(+ "inferred: imports this file",+ );+ expect(hintReason({ ...hint, tests: [], basis: "none" })).toBe(+ "no test reaches this; add one",+ );+ });});describe("riskWords", () => {diff --git a/packages/ui/src/health/patch-coverage-summary.tsx b/packages/ui/src/health/patch-coverage-summary.tsxindex 270705d65..a3bbbc949 100644--- a/packages/ui/src/health/patch-coverage-summary.tsx+++ b/packages/ui/src/health/patch-coverage-summary.tsx@@ -12,7 +12,8 @@** Each file row names its file's risk in words, and the rows read riskiest* first, in the order `repowise coverage check` uses. A line says where the- * risk came from when not every file had index data.+ * risk came from when not every file had index data. With an index, a file+ * with uncovered lines also names the test file to extend.*/import type { ReactNode } from "react";@@ -21,6 +22,7 @@ import type {PatchCoverageFileRisk,PatchCoveragePathGate,PatchCoverageResponse,+ PatchCoverageTestHint,} from "@repowise-dev/types/generated/http";export interface PatchCoverageSummaryProps {@@ -84,6 +86,42 @@ function gitOnlyText(gitOnly: number, total: number): string {return `Risk for ${gitOnly} of ${plural(total, "file")} is from git bug-fix history alone: the index has no row for them yet`;}+/** The file's first hint that names a test, else its first hint; `null` without an index. */+export function firstHint(file: PatchCoverageFile): PatchCoverageTestHint | null {+ const hints = file.hints ?? [];+ return hints.find((h) => h.tests.length > 0) ?? hints[0] ?? null;+}++/**+ * Why the hint's test is the one to extend, measured or inferred. The source+ * of truth is the core's `hint_phrase` (patch_coverage/hints.py); keep the two+ * worded alike.+ */+export function hintReason(hint: PatchCoverageTestHint): string {+ switch (hint.basis) {+ case "per_test":+ return hint.symbol+ ? `measured: runs other lines of ${hint.symbol}`+ : "measured: runs nearby lines";+ case "call_graph":+ return `inferred: calls reach ${hint.symbol ?? "this code"}`;+ case "import_graph":+ return "inferred: imports this file";+ case "none":+ return "no test reaches this; add one";+ default: {+ const unknown: never = hint.basis;+ return unknown;+ }+ }+}++/** The whole hint as one sentence, the core's `hint_phrase` without code spans. */+export function hintText(hint: PatchCoverageTestHint): string {+ const test = hint.tests[0];+ return test ? `extend ${test} (${hintReason(hint)})` : hintReason(hint);+}+/** Risky first, then fix pressure, dependents, uncovered lines: the core's order. */export function byRisk(a: PatchCoverageFile, b: PatchCoverageFile): number {const key = (f: PatchCoverageFile): number[] => [@@ -336,6 +374,7 @@ function UncoveredList({key={f.file_path}file={f}trailing={`lines ${formatLineRanges(f.uncovered_ranges)}`}+ hint={firstHint(f)}onOpenFile={onOpenFile}/>))}@@ -378,10 +417,12 @@ function UnmeasuredList({function FileRow({file,trailing,+ hint = null,onOpenFile,}: {file: PatchCoverageFile;trailing: string;+ hint?: PatchCoverageTestHint | null;onOpenFile: OpenFile;}) {const body = (@@ -412,10 +453,30 @@ function FileRow({{body}</div>)}+ {hint && <HintLine hint={hint} />}</li>);}+/** Where to add the missing test: the file's first hint, one line under its row. */+function HintLine({ hint }: { hint: PatchCoverageTestHint }) {+ const test = hint.tests[0];+ return (+ <p+ title={hintText(hint)}+ className="truncate px-1.5 pb-1 text-xs text-[var(--color-text-tertiary)]"+ >+ {test ? (+ <>+ extend <span className="font-mono">{test}</span> · {hintReason(hint)}+ </>+ ) : (+ hintReason(hint)+ )}+ </p>+ );+}+/** A row's risk in words; nothing for "none known", which is not worth a label. */function RiskLabel({ risk }: { risk: PatchCoverageFile["risk"] | undefined }) {const words = riskWords(risk);diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex fd4353e7c..410e0f4e7 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -99,6 +99,15 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {risky: true,reasons: ["hotspot"],},+ hints: [+ {+ range: [3, 3],+ symbol: "boot",+ tests: ["src/core.test.ts"],+ basis: "per_test",+ total: 1,+ },+ ],},{file_path: "src/new.ts",@@ -109,6 +118,7 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {patch_coverage_pct: null,uncovered_ranges: [],risk: null,+ hints: null,},],risky: {@@ -503,8 +513,10 @@ describe("risk App", () => {/>,);- expect(await screen.findByText("66.6%")).toBeTruthy();- expect(screen.getByRole("list", { name: "Path-scoped gates" })).toBeTruthy();+ // Each throws when absent: the figure, the path-scoped gates, the hint naming the test to extend.+ await screen.findByText("66.6%");+ screen.getByRole("list", { name: "Path-scoped gates" });+ screen.getByText("src/core.test.ts");fireEvent.click(screen.getByTitle("Open src/core.ts"));expect(openFile).toHaveBeenCalledWith("src/core.ts");diff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.pyindex 3c19ec269..7fef179f3 100644--- a/tests/unit/analysis/test_changed_lines.py+++ b/tests/unit/analysis/test_changed_lines.py@@ -132,6 +132,50 @@ def test_changed_lines_three_dot_diffs_from_merge_base(git_repo) -> None:assert changed_lines(str(git_repo), "main..feat")[0] == {"mod.py": {2, 3}}+def test_working_tree_from_a_base_is_everything_a_push_brings(git_repo) -> None:+ # The branch committed line 2 and left line 4 uncommitted; base moved line 3.+ _git(git_repo, "branch", "-M", "main")+ _git(git_repo, "switch", "-qc", "feat")+ (git_repo / "mod.py").write_text("a = 1\nb = 22\nc = 3\n", encoding="utf-8")+ _git(git_repo, "commit", "-qam", "feat edit")+ _git(git_repo, "switch", "-q", "main")+ (git_repo / "mod.py").write_text("a = 1\nb = 2\nc = 33\n", encoding="utf-8")+ _git(git_repo, "commit", "-qam", "base edit")+ _git(git_repo, "switch", "-q", "feat")+ (git_repo / "mod.py").write_text("a = 1\nb = 22\nc = 3\nd = 4\n", encoding="utf-8")++ (git_repo / "new.py").write_text("x = 1\ny = 2", encoding="utf-8") # untracked++ changed, label = changed_lines(str(git_repo), working_tree=True, base="main")+ assert label == "main...working tree"+ # An untracked file is new code the push brings: every line changed.+ assert changed == {"mod.py": {2, 4}, "new.py": {1, 2}}+ # Without a base it stays the uncommitted edit alone.+ assert changed_lines(str(git_repo), working_tree=True) == ({"mod.py": {4}}, "working tree")+ # A base that does not resolve falls back to the uncommitted edit, still+ # with the new files a push would bring.+ assert changed_lines(str(git_repo), working_tree=True, base="nope") == (+ {"mod.py": {4}, "new.py": {1, 2}},+ "working tree",+ )+++def test_map_old_line_follows_insertions_deletions_and_rewrites() -> None:+ from repowise.core.analysis.changed_lines import map_old_line, parse_unified_diff++ diff = (+ "--- a/m.py\n+++ b/m.py\n"+ "@@ -0,0 +1,2 @@\n+n1\n+n2\n" # two lines inserted at the top+ "@@ -5,2 +7,0 @@\n-x\n-y\n" # lines 5-6 deleted+ "@@ -10 +10,3 @@\n-z\n+a\n+b\n+c\n" # line 10 rewritten as three+ )+ hunks = parse_unified_diff(diff)["m.py"].hunks+ assert map_old_line(hunks, 3) == 5+ assert map_old_line(hunks, 8) == 8+ assert (map_old_line(hunks, 10), map_old_line(hunks, 10, end=True)) == (10, 12)+ assert map_old_line(hunks, 20) == 22++def test_single_commit_at_a_shallow_boundary_raises(git_repo, tmp_path_factory) -> None:# Its parents are cut off, so git would diff against the empty tree and# report every line as changed.diff --git a/tests/unit/analysis/test_patch_coverage.py b/tests/unit/analysis/test_patch_coverage.pyindex b74515af1..8a86c7d80 100644--- a/tests/unit/analysis/test_patch_coverage.py+++ b/tests/unit/analysis/test_patch_coverage.py@@ -12,15 +12,20 @@ from repowise.core.analysis.patch_coverage import (IndexFacts,PatchScope,assess_risks,+ attach_hints,attach_risk,attention_rows,+ build_hints,compute_patch_coverage,fmt_pct,github_annotations,headline,+ hint_phrase,render_markdown,risky_line,)+from repowise.core.analysis.patch_coverage.hints import SymbolSpan, TestHint, translate_spans+from repowise.core.analysis.test_reachability import ReachedBydef _cov(path: str, covered: list[int], coverable: list[int]):@@ -834,3 +839,149 @@ def test_may_overlap_is_symmetric_and_errs_towards_yes() -> None:assert not _may_overlap("/pkg/", "/lib/")assert not _may_overlap("/src/a.py", "/src/b.py")assert not _may_overlap("!/pkg/", "/pkg/web/")+# ---------------------------------------------------------------------------+# hints: where to add a test for each uncovered range+# ---------------------------------------------------------------------------+++def _gappy(ranges_lines: set[int], path: str = "src/auth.py"):+ """One measured file whose changed lines *ranges_lines* are all uncovered."""+ pc = compute_patch_coverage(+ {path: ranges_lines}, _cov(path, covered=[], coverable=sorted(ranges_lines))+ )+ return pc, pc.files[0]+++_SPANS = [+ SymbolSpan("src/auth.py::Auth", "Auth", 1, 40),+ SymbolSpan("src/auth.py::Auth.login", "Auth.login", 10, 20),+ SymbolSpan("src/auth.py::Auth.logout", "Auth.logout", 22, 30),+]+++def _reached(tests: list[str], via: str = "call-graph", total: int | None = None) -> ReachedBy:+ return ReachedBy(tests, via, len(tests) if total is None else total)+++def test_a_hint_names_the_innermost_symbol_and_nothing_outside_one() -> None:+ _pc, f = _gappy({12, 35, 50})+ hints = build_hints(f, _SPANS, [], {})++ assert [h.symbol for h in hints] == ["Auth.login", "Auth", None]+ assert all(h.basis == "none" and h.tests == () and h.total == 0 for h in hints)+++def test_per_test_coverage_beats_the_graph() -> None:+ _pc, f = _gappy({12})+ rows = [+ {"test_id": "tests/test_auth.py::test_ok", "test_file": "tests/test_auth.py",+ "covered_lines": [11, 13, 14]},+ # Lines of another symbol only: not evidence for login.+ {"test_id": "tests/test_out.py::t", "test_file": "tests/test_out.py",+ "covered_lines": [25]},+ {"test_id": "tests/test_more.py::t", "test_file": None, "covered_lines": [15]},+ ]+ reached = {"src/auth.py::Auth.login": _reached(["tests/test_graph.py"])}+ (hint,) = build_hints(f, _SPANS, rows, reached)++ assert hint.basis == "per_test"+ # Most lines of the symbol first; a row without a file is named by its id.+ assert hint.tests == ("tests/test_auth.py", "tests/test_more.py")+ assert hint.total == 2+++def test_outside_a_symbol_per_test_uses_a_window_around_the_range() -> None:+ _pc, f = _gappy({50})+ near = [{"test_id": "t::a", "test_file": "tests/test_near.py", "covered_lines": [53]}]+ far = [{"test_id": "t::b", "test_file": "tests/test_far.py", "covered_lines": [60]}]++ assert build_hints(f, _SPANS, near, {})[0].tests == ("tests/test_near.py",)+ assert build_hints(f, _SPANS, far, {})[0].basis == "none"+++def test_the_call_graph_answers_for_the_symbol_then_imports_for_the_file() -> None:+ _pc, f = _gappy({12, 24})+ reached = {+ "src/auth.py::Auth.login": _reached(["tests/test_login.py"]),+ "src/auth.py": _reached(["tests/test_imports.py"], via="import-graph"),+ }+ login, logout = build_hints(f, _SPANS, [], reached)++ assert (login.basis, login.tests) == ("call_graph", ("tests/test_login.py",))+ # No test reaches logout, so the file's importers answer.+ assert (logout.basis, logout.tests) == ("import_graph", ("tests/test_imports.py",))+++def test_tests_are_capped_at_three_and_total_stays_honest() -> None:+ _pc, f = _gappy({12})+ many = [f"tests/test_{i}.py" for i in range(5)]+ (hint,) = build_hints(f, _SPANS, [], {"src/auth.py::Auth.login": _reached(many, total=7)})++ assert hint.tests == tuple(many[:3])+ assert hint.total == 7+++def test_hints_ride_on_the_row_and_every_rendering() -> None:+ pc, f = _gappy({12, 13})+ hints = build_hints(f, _SPANS, [], {"src/auth.py::Auth.login": _reached(["tests/test_auth.py"])})+ pc = attach_hints(pc, {f.file_path: hints})++ (row,) = pc.to_dict()["files"]+ assert row["hints"] == [+ {"range": [12, 13], "symbol": "Auth.login", "tests": ["tests/test_auth.py"],+ "basis": "call_graph", "total": 1}+ ]+ assert hint_phrase(hints[0]) == "extend tests/test_auth.py (inferred: calls reach `Auth.login`)"+ markdown = render_markdown(pc)+ assert "| File | Uncovered changed lines | Covered | Extend |" in markdown+ assert "extend tests/test_auth.py (inferred: calls reach `Auth.login`)" in markdown+ (annotation,) = github_annotations(pc)+ assert "Extend tests/test_auth.py (inferred: calls reach `Auth.login`)" in annotation+++def test_each_basis_says_measured_or_inferred() -> None:+ def phrase(basis, symbol="login", tests=("t.py",)):+ return hint_phrase(TestHint((1, 1), symbol, tests, basis, len(tests)))++ assert phrase("per_test") == "extend t.py (measured: runs other lines of `login`)"+ assert phrase("per_test", symbol=None) == "extend t.py (measured: runs nearby lines)"+ assert phrase("import_graph") == "extend t.py (inferred: imports this file)"+ assert phrase("none", tests=()) == "no test reaches this; add one"+++def test_a_tier_the_hints_do_not_know_is_no_evidence() -> None:+ _pc, f = _gappy({12})+ reached = {"src/auth.py": _reached(["tests/test_auth.py"], via="name-match")}+ (hint,) = build_hints(f, _SPANS, [], reached)+ assert (hint.basis, hint.tests, hint.total) == ("none", (), 0)+++def test_spans_move_with_the_code_since_the_index() -> None:+ # Five lines inserted at the top shift every symbol down by five.+ shifted = translate_spans(_SPANS, [(0, 0, 1, 5)])+ assert [(s.start_line, s.end_line) for s in shifted] == [(6, 45), (15, 25), (27, 35)]++ # A new top-level function inserted above Auth (new lines 1-8): its range+ # lies in no span, so it has no symbol; the old method keeps its own.+ moved = translate_spans(_SPANS, [(0, 0, 1, 8)])+ _pc, f = _gappy({3, 19})+ new, old = build_hints(f, moved, [], {})+ assert new.symbol is None+ assert old.symbol == "Auth.login"++ # A symbol the diff deleted outright is dropped.+ assert translate_spans([SymbolSpan("a::gone", "gone", 5, 6)], [(5, 2, 4, 0)]) == []+++def test_without_an_index_hints_are_null_and_nothing_changes() -> None:+ pc, _f = _gappy({12})+ assert pc.to_dict()["files"][0]["hints"] is None+ assert "Extend" not in render_markdown(pc)+ # An index that found nothing is an empty list, not null.+ empty = attach_hints(pc, {})+ assert empty.to_dict()["files"][0]["hints"] == []+ assert "Extend" not in github_annotations(empty)[0]+ # An index that found no test says so in words.+ none = attach_hints(pc, {"src/auth.py": (TestHint((12, 12), None, (), "none", 0),)})+ assert "no test reaches this; add one" in render_markdown(none)+ assert "No test reaches this; add one" in github_annotations(none)[0]diff --git a/tests/unit/cli/test_augment_coverage_reingest.py b/tests/unit/cli/test_augment_coverage_reingest.pynew file mode 100644index 000000000..0aed799d1--- /dev/null+++ b/tests/unit/cli/test_augment_coverage_reingest.py@@ -0,0 +1,267 @@+"""PostToolUse Bash: a full test run with a fresh coverage report re-ingests it in the background."""++from __future__ import annotations++import os+import sqlite3+import time++import pytest++from repowise.cli.commands.augment_cmd import coverage_reingest as hook+from repowise.cli.commands.augment_cmd.command import _handle_post_tool_use++#: When the last ingest happened, in the stored UTC shape SQLite keeps.+_INGESTED_AT = "2026-09-01 12:00:00.000000"+_INGESTED_EPOCH = 1788264000.0 # 2026-09-01T12:00:00Z+++def _db(root, *ingests: str) -> None:+ (root / ".repowise").mkdir(exist_ok=True)+ con = sqlite3.connect(root / ".repowise" / "wiki.db")+ con.execute("CREATE TABLE coverage_ingests (ingested_at DATETIME NOT NULL)")+ con.executemany("INSERT INTO coverage_ingests VALUES (?)", [(i,) for i in ingests])+ con.commit()+ con.close()+++def repo(tmp_path, monkeypatch):+ """An indexed repo whose last coverage ingest is ``_INGESTED_AT``."""+ monkeypatch.delenv("REPOWISE_HOOK_COVERAGE_REINGEST", raising=False)+ _db(tmp_path, _INGESTED_AT)+ return tmp_path+++def spawned(monkeypatch):+ calls: list[tuple] = []+ monkeypatch.setattr(hook, "spawn_coverage_add", lambda root, reports: calls.append((root, reports)))+ return calls+++def _report(repo, rel: str = "coverage/lcov.info", *, after: float = 60) -> None:+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("SF:a.py\nDA:1,1\nend_of_record\n", encoding="utf-8")+ os.utime(path, (_INGESTED_EPOCH + after,) * 2)+++def _config(repo, text: str) -> None:+ (repo / ".repowise" / "config.yaml").write_text(text, encoding="utf-8")+++ "command",+ [+ "pytest",+ "pytest -q -x",+ "cd api && python -m pytest -x",+ ".venv/Scripts/python.exe -m pytest",+ "coverage run -m pytest",+ "FOO=1 time timeout 600 pytest",+ "go test ./...",+ "npm test",+ "npm run test -- --coverage",+ "npm run test:unit",+ "pnpm test",+ "yarn test",+ "bun test",+ "npx vitest run",+ "vitest",+ "jest --coverage",+ "uv run pytest; echo done",+ "poetry run pytest | tail -5",+ "cargo test",+ "cargo llvm-cov --lcov --output-path coverage/lcov.info",+ "mvn test",+ "./gradlew test",+ "repowise distill pytest -q",+ "repowise distill --source hook 'cd api && pytest -q'",+ ["pytest", "-q"],+ ],+)+def test_full_test_runs_are_recognised(command) -> None:+ assert hook.is_full_test_run(command)+++ "command",+ [+ "pytest tests/unit/test_a.py",+ "pytest tests/test_a.py::test_one",+ "pytest -k login",+ "go test -run TestLogin ./...",+ "go test ./pkg/auth",+ "npx vitest run src/a.test.ts",+ "jest -t login",+ "jest --testNamePattern=login",+ "cargo test parse_",+ "mvn test -Dtest=AuthTest",+ "./gradlew test --tests AuthTest",+ "dotnet test --filter Auth",+ ],+)+def test_partial_runs_are_not_full(command) -> None:+ assert not hook.is_full_test_run(command)+++ "command",+ ["pytestify", "git commit -m pytest", "npm install", "echo pytest", "go build", None, 3],+)+def test_other_commands_are_not_test_runs(command) -> None:+ assert not hook.is_test_command(command)+++def test_default_reports_match_discovery() -> None:+ from repowise.core.analysis.health.coverage.discovery import DEFAULT_DISCOVERY_GLOBS++ literal = tuple(g for g in DEFAULT_DISCOVERY_GLOBS if not any(ch in g for ch in "*?["))+ assert literal == hook.DEFAULT_REPORTS+++def test_a_fresh_report_is_reingested_once(repo, spawned) -> None:+ _report(repo)++ note = hook.coverage_reingest_notice({"command": "pytest -q"}, str(repo))++ assert note == (+ "[repowise] Re-ingesting coverage from coverage/lcov.info in the background "+ "(log: .repowise/.coverage.log); get_change_risk reads it once the ingest finishes."+ )+ ((root, reports),) = spawned+ assert root == repo.resolve()+ assert reports == [repo.resolve() / "coverage" / "lcov.info"]+ # The queued marker stops a second run from spawning over the first.+ assert hook.coverage_reingest_notice({"command": "pytest -q"}, str(repo)) is None+ assert len(spawned) == 1+ # A newer report than the queued one spawns again.+ _report(repo, after=120)+ assert hook.coverage_reingest_notice({"command": "pytest -q"}, str(repo)) is not None+ assert len(spawned) == 2+++def test_only_the_fresh_reports_are_passed(repo, spawned) -> None:+ _report(repo, "coverage.xml", after=-60) # older than the ingest: left alone+ _report(repo)+ _report(repo, ".coverage") # a coverage.py database: never on its own account+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is not None+ assert spawned[0][1] == [repo.resolve() / "coverage" / "lcov.info"]+++def test_a_fresh_coverage_database_alone_does_nothing(repo, spawned) -> None:+ _config(repo, "coverage:\n paths: [.coverage]\n")+ _report(repo, ".coverage")+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None+ assert spawned == []+++def test_a_stale_queued_marker_does_not_block(repo, spawned) -> None:+ _report(repo)+ (repo / ".repowise" / hook.QUEUED_FILENAME).write_text(+ f'{{"queued_at": {time.time() - hook.QUEUED_STALE_AFTER_SECONDS - 1}, '+ f'"report_mtime": {_INGESTED_EPOCH + 60}}}',+ encoding="utf-8",+ )+ assert hook.coverage_reingest_notice({"command": "go test ./..."}, str(repo)) is not None+++def test_silent_for_partial_runs_other_commands_and_unindexed_repos(+ repo, tmp_path_factory, spawned+) -> None:+ _report(repo)+ assert hook.coverage_reingest_notice({"command": "git status"}, str(repo)) is None+ assert hook.coverage_reingest_notice({"command": "pytest -k login"}, str(repo)) is None+ bare = tmp_path_factory.mktemp("bare")+ (bare / ".repowise").mkdir()+ _report(bare)+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(bare)) is None+ assert spawned == []+++def test_an_upgraded_index_reads_its_ingests_from_the_coverage_rows(tmp_path, spawned) -> None:+ # The ingest history exists but is empty; earlier ingests live on the rows.+ _db(tmp_path)+ con = sqlite3.connect(tmp_path / ".repowise" / "wiki.db")+ con.execute("CREATE TABLE coverage_files (ingested_at DATETIME)")+ con.execute("INSERT INTO coverage_files VALUES (?)", (_INGESTED_AT,))+ con.commit()+ con.close()+ _report(tmp_path)+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(tmp_path)) is not None+ assert len(spawned) == 1+++def test_a_repo_that_never_ingested_coverage_is_left_alone(tmp_path, spawned) -> None:+ _db(tmp_path)+ _report(tmp_path)+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(tmp_path)) is None+ assert spawned == []+++def test_the_opt_out_and_its_env_override(repo, spawned, monkeypatch) -> None:+ _report(repo)+ _config(repo, "hooks:\n coverage_reingest: false\n")+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None+ monkeypatch.setenv("REPOWISE_HOOK_COVERAGE_REINGEST", "1")+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is not None+ monkeypatch.setenv("REPOWISE_HOOK_COVERAGE_REINGEST", "0")+ _report(repo, after=120)+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None+++def test_configured_paths_and_discovery_settings_are_respected(repo, spawned) -> None:+ _config(repo, "coverage:\n paths: [out/cov.info]\n")+ _report(repo) # the default location, not configured+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None+ _report(repo, "out/cov.info")+ assert "out/cov.info" in hook.coverage_reingest_notice({"command": "pytest"}, str(repo))+ assert spawned[0][1] == [repo.resolve() / "out" / "cov.info"]++ (repo / ".repowise" / hook.QUEUED_FILENAME).unlink()+ for block in ("coverage:\n auto_discover: false\n", "coverage:\n artifacts: ['x/*.info']\n"):+ _config(repo, block)+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None+ assert len(spawned) == 1+++def test_never_raises(repo, monkeypatch) -> None:+ _report(repo)++ def _boom(*_a, **_k):+ raise PermissionError("denied")++ monkeypatch.setattr(hook, "spawn_coverage_add", _boom)+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None+++def test_the_bash_dispatch_carries_the_note(repo, spawned) -> None:+ _report(repo)+ result = _handle_post_tool_use(+ "Bash", {"command": "pytest"}, {"stdout": "1 passed", "exit_code": 0}, str(repo)+ )+ assert "Re-ingesting coverage" in (result.context or "")+++def test_spawn_runs_coverage_add_detached_with_a_fresh_log(tmp_path, monkeypatch) -> None:+ import subprocess+ import sys++ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / hook.LOG_FILENAME).write_text("old run\n", encoding="utf-8")+ seen: dict = {}++ def _popen(argv, **kwargs):+ seen.update(argv=argv, **kwargs)++ monkeypatch.setattr(subprocess, "Popen", _popen)+ hook.spawn_coverage_add(tmp_path, [tmp_path / "lcov.info"])++ assert seen["argv"] == [+ sys.executable, "-m", "repowise.cli.main", "coverage", "add",+ "--path", str(tmp_path), str(tmp_path / "lcov.info"),+ ]+ assert seen["stdin"] is subprocess.DEVNULL+ assert "creationflags" in seen or seen.get("start_new_session") is True+ assert (tmp_path / ".repowise" / hook.LOG_FILENAME).read_text(encoding="utf-8") == ""diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.pyindex 515ffb965..c6ebe701b 100644--- a/tests/unit/cli/test_coverage_check_cmd.py+++ b/tests/unit/cli/test_coverage_check_cmd.py@@ -71,6 +71,8 @@ def test_json_reports_patch_coverage_without_an_index(repo) -> None:assert data["file_counts"]["out_of_scope"] == 1assert data["scope"]["label"] == "main...feat"assert data["scope"]["reports"] == [report]+ # No index, no hints: null, never an empty "nothing to suggest".+ assert all(f["hints"] is None for f in data["files"])def test_gate_fails_below_threshold(repo) -> None:@@ -439,6 +441,72 @@ def test_an_unreadable_index_still_gates_on_git_risk(fixed_repo, monkeypatch) ->assert data["risky"]["gate"] == "fail"+def _with_index(monkeypatch, read_hints) -> None:+ from contextlib import asynccontextmanager++ import repowise.cli.commands.coverage_check_cmd as cmd+ import repowise.core.analysis.patch_coverage as pc_module++ @asynccontextmanager+ async def _opened(_root):+ yield object(), "r"++ async def _no_facts(*_a, **_k):+ return {}++ monkeypatch.setattr(cmd, "has_db_store", lambda _root: True)+ monkeypatch.setattr(cmd, "repo_index_session", _opened)+ monkeypatch.setattr(pc_module, "read_index_facts", _no_facts)+ monkeypatch.setattr(pc_module, "read_test_hints", read_hints)+++def test_an_index_names_the_test_to_extend(repo, monkeypatch, tmp_path_factory) -> None:+ from repowise.core.analysis.patch_coverage import TestHint++ async def _hints(_session, _repo_id, _pc, **kwargs):+ # The checkout and head go along so stored spans can be moved to them.+ assert kwargs["repo_path"] and kwargs["head_commit"]+ return {+ "src/app.py": (+ TestHint((3, 3), "main", ("tests/test_app.py",), "call_graph", 1),+ )+ }++ _with_index(monkeypatch, _hints)+ report = _lcov(repo, {2: 1, 3: 0})+ summary = tmp_path_factory.mktemp("gh") / "summary.md"++ data = json.loads(_run(repo, "main...feat", "--report", report, "--format", "json").stdout)+ app = next(f for f in data["files"] if f["file_path"] == "src/app.py")+ assert app["hints"][0]["tests"] == ["tests/test_app.py"]+ github = _run(+ repo, "main...feat", "--report", report, "--format", "github",+ env={"GITHUB_STEP_SUMMARY": str(summary)},+ )+ assert "not covered by tests. Extend tests/test_app.py (inferred: calls reach `main`)" in (+ github.stdout+ )+ assert "extend tests/test_app.py (inferred: calls reach `main`)" in summary.read_text(+ encoding="utf-8"+ )+ table = _run(repo, "main...feat", "--report", report)+ assert "tests/test_app.py" in table.output+++def test_an_unreadable_index_leaves_hints_null_and_the_gate_alone(repo, monkeypatch) -> None:+ from sqlalchemy.exc import OperationalError++ async def _raise(*_a, **_k):+ raise OperationalError("select", {}, Exception("no such table: wiki_symbols"))++ _with_index(monkeypatch, _raise)+ report = _lcov(repo, {2: 1, 3: 0})++ result = _run(repo, "main...feat", "--report", report, "--fail-under", "80", "--format", "json")+ assert result.exit_code == 1, result.output+ assert all(f["hints"] is None for f in json.loads(result.stdout)["files"])++def test_stored_coverage_is_not_gated_when_stale_or_without_line_data() -> None:from repowise.cli.ci import CannotEvaluateErrorfrom repowise.cli.commands.coverage_check_cmd import _gateablediff --git a/tests/unit/persistence/test_patch_coverage_hints.py b/tests/unit/persistence/test_patch_coverage_hints.pynew file mode 100644index 000000000..bf0da4957--- /dev/null+++ b/tests/unit/persistence/test_patch_coverage_hints.py@@ -0,0 +1,176 @@+"""``read_test_hints`` against real index rows: symbols, per-test coverage, the graph."""++from __future__ import annotations++import json+import subprocess+from dataclasses import replace++from repowise.core.analysis.health.coverage import file_coverage+from repowise.core.analysis.patch_coverage import (+ PatchScope,+ compute_patch_coverage,+ read_test_hints,+)+from repowise.core.persistence.models import GraphEdge, GraphNode, TestCoverageEntry, WikiSymbol+from tests.unit.persistence.helpers import insert_repo+++def _symbol(repo_id: str, path: str, name: str, start: int, end: int) -> WikiSymbol:+ return WikiSymbol(+ repository_id=repo_id,+ file_path=path,+ symbol_id=f"{path}::{name}",+ name=name.rsplit(".", 1)[-1],+ qualified_name=name,+ kind="function",+ start_line=start,+ end_line=end,+ )+++async def _index(session, repo_id: str) -> None:+ """src/auth.py: ``login`` (10-20) and ``logout`` (22-30).++ tests/test_login.py calls ``login``; tests/test_io.py only imports the file;+ src/util.py has a per-test row from tests/test_util.py near line 5.+ """+ session.add_all(+ [+ _symbol(repo_id, "src/auth.py", "login", 10, 20),+ _symbol(repo_id, "src/auth.py", "logout", 22, 30),+ *(+ GraphNode(repository_id=repo_id, node_id=path, node_type="file", is_test=is_test)+ for path, is_test in (+ ("src/auth.py", False),+ ("src/util.py", False),+ ("tests/test_login.py", True),+ ("tests/test_io.py", True),+ )+ ),+ *(+ GraphEdge(+ repository_id=repo_id, source_node_id=src, target_node_id=dst, edge_type=etype+ )+ for src, dst, etype in (+ ("tests/test_login.py", "tests/test_login.py::test_it", "defines"),+ ("tests/test_login.py::test_it", "src/auth.py::login", "calls"),+ ("tests/test_io.py", "src/auth.py", "imports"),+ )+ ),+ TestCoverageEntry(+ repository_id=repo_id,+ test_id="tests/test_util.py::test_x",+ test_file="tests/test_util.py",+ source_file="src/util.py",+ covered_lines_json=json.dumps([3, 4]),+ source_format="coverage.py",+ ),+ ]+ )+ await session.flush()+++async def test_each_range_gets_its_strongest_evidence(async_session):+ repo = await insert_repo(async_session)+ await _index(async_session, repo.id)+ changed = {"src/auth.py": {12, 25}, "src/util.py": {6}, "src/done.py": {1}}+ pc = compute_patch_coverage(+ changed,+ {+ "src/auth.py": file_coverage("src/auth.py", [], [12, 25]),+ "src/util.py": file_coverage("src/util.py", [], [6]),+ "src/done.py": file_coverage("src/done.py", [1], [1]),+ },+ scope=PatchScope(freshness="current"),+ )++ hints = await read_test_hints(async_session, repo.id, pc)++ # A fully covered file has nothing to hint.+ assert set(hints) == {"src/auth.py", "src/util.py"}+ login, logout = hints["src/auth.py"]+ assert (login.symbol, login.basis, login.tests) == ("login", "call_graph", ("tests/test_login.py",))+ # No test calls logout; the file's importer is the fallback, labelled so.+ assert (logout.symbol, logout.basis, logout.tests) == (+ "logout",+ "import_graph",+ ("tests/test_io.py",),+ )+ (util,) = hints["src/util.py"]+ assert (util.symbol, util.basis, util.tests) == (None, "per_test", ("tests/test_util.py",))++ # Coverage not current for this change: per-test line numbers may describe+ # other code, so they are not evidence.+ stale = await read_test_hints(async_session, repo.id, replace(pc, scope=PatchScope()))+ assert stale["src/util.py"][0].basis == "none"+++async def test_an_empty_index_hints_none(async_session):+ repo = await insert_repo(async_session)+ pc = compute_patch_coverage({"a.py": {1}}, {"a.py": file_coverage("a.py", [], [1])})++ (hint,) = (await read_test_hints(async_session, repo.id, pc))["a.py"]+ assert (hint.symbol, hint.basis, hint.tests, hint.total) == (None, "none", (), 0)+++def _git(cwd, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True+ ).stdout.strip()+++async def test_spans_are_moved_to_the_working_tree(async_session, tmp_path):+ """The index saw ``login`` at 1-3; a new function now sits above it."""+ _git(tmp_path, "init", "-q")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ (tmp_path / "auth.py").write_text("def login():\n a = 1\n return a\n", encoding="utf-8")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "init")+ indexed = _git(tmp_path, "rev-parse", "HEAD")+ repo = await insert_repo(async_session, local_path=str(tmp_path))+ repo.head_commit = indexed+ async_session.add(_symbol(repo.id, "auth.py", "login", 1, 3))+ await async_session.flush()+ (tmp_path / "auth.py").write_text(+ "def fresh():\n return 0\n\n\ndef login():\n a = 2\n return a\n",+ encoding="utf-8",+ )+ pc = compute_patch_coverage(+ {"auth.py": {2, 6}}, {"auth.py": file_coverage("auth.py", [], [2, 6])}+ )++ raw = await read_test_hints(async_session, repo.id, pc)+ moved = await read_test_hints(+ async_session, repo.id, pc, repo_path=str(tmp_path), working_tree=True+ )++ # As stored, line 2 would read as login; moved, it is new code and line 6 is login.+ assert [h.symbol for h in raw["auth.py"]] == ["login", None]+ assert [h.symbol for h in moved["auth.py"]] == [None, "login"]+++async def test_a_symbol_keyed_walk_ranks_the_test_named_for_its_file_first(async_session):+ from repowise.core.analysis.test_reachability import tests_reaching_by_tier++ repo = await insert_repo(async_session)+ for path, is_test in (("src/auth.py", False), ("tests/a_other.py", True), ("tests/test_auth.py", True)):+ async_session.add(+ GraphNode(repository_id=repo.id, node_id=path, node_type="file", is_test=is_test)+ )+ for test in ("tests/a_other.py", "tests/test_auth.py"):+ for src, dst, etype in (+ (test, f"{test}::t", "defines"),+ (f"{test}::t", "src/auth.py::login", "calls"),+ ):+ async_session.add(+ GraphEdge(repository_id=repo.id, source_node_id=src, target_node_id=dst, edge_type=etype)+ )+ await async_session.flush()++ sid = "src/auth.py::login"+ found = await tests_reaching_by_tier(+ async_session, repo.id, [sid], import_depth=0, symbol_seeds={sid: {sid}}+ )+ assert found[sid].tests == ["tests/test_auth.py", "tests/a_other.py"]diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.pyindex 3b835eea4..2bee81f15 100644--- a/tests/unit/server/mcp/test_tool_change_risk.py+++ b/tests/unit/server/mcp/test_tool_change_risk.py@@ -526,3 +526,233 @@ async def test_patch_coverage_files_are_capped_to_what_needs_attention(# Totals still count every file, the fully covered one included.assert block["file_counts"]["measured"] == 16assert block["coverable_line_count"] == 16+++async def _stored_repo(monkeypatch, session, tmp_path, **save_kwargs):+ from repowise.core.analysis.health.coverage import file_coverage+ from repowise.core.persistence.crud import save_coverage_files, upsert_repository++ repo = await upsert_repository(session, name="r", local_path=str(tmp_path))+ await save_coverage_files(+ session,+ repo.id,+ [file_coverage("a.py", [1], [1, 2])],+ source_format="lcov",+ ingested_commit_sha="abc",+ **save_kwargs,+ )+ await session.commit()++ async def _repo(_session, *_a, **_k):+ return repo++ monkeypatch.setattr(tool, "_get_repo", _repo)+ return repo+++async def test_patch_coverage_rows_carry_the_test_to_extend(+ monkeypatch, factory, session, tmp_path+):+ import repowise.core.analysis.patch_coverage as pc_module+ from repowise.core import git_refs+ from repowise.core.analysis.patch_coverage import TestHint++ await _stored_repo(monkeypatch, session, tmp_path)+ monkeypatch.setattr(git_refs, "resolve", lambda _p, _rev: "abc")+ seen: dict = {}++ async def _hints(_session, _repo_id, _pc, **kwargs):+ seen.update(kwargs)+ return {"a.py": (TestHint((2, 2), "run", ("tests/test_a.py",), "call_graph", 4),)}++ monkeypatch.setattr(pc_module, "read_test_hints", _hints)+ ctx = SimpleNamespace(session_factory=factory, path=tmp_path)+ block = await tool._patch_coverage_block(+ ctx, {"a.py": {1, 2}}, None, "HEAD", _scored(), _collector(tmp_path)+ )+ assert block["files"][0]["hints"] == [+ {"range": [2, 2], "symbol": "run", "tests": ["tests/test_a.py"],+ "basis": "call_graph", "total": 4}+ ]+ # The checkout goes along so spans stored at the indexed commit can move.+ assert seen == {"repo_path": str(tmp_path), "head_commit": "abc", "working_tree": False}++ async def _unreadable(*_a, **_k):+ return None # read_test_hints logs its own failure and answers None++ # An index that cannot answer leaves hints null and the figure intact.+ monkeypatch.setattr(pc_module, "read_test_hints", _unreadable)+ block = await tool._patch_coverage_block(+ ctx, {"a.py": {1, 2}}, None, "HEAD", _scored(), _collector(tmp_path)+ )+ assert block["patch_coverage_pct"] == 50.0+ assert block["files"][0]["hints"] is None+++async def test_a_failing_hint_read_is_logged_and_reads_as_none(monkeypatch):+ import repowise.core.analysis.patch_coverage.hints as hints_module+ from repowise.core.analysis.health.coverage import file_coverage+ from repowise.core.analysis.patch_coverage import compute_patch_coverage, read_test_hints++ async def _raise(*_a, **_k):+ raise OperationalError("select", {}, Exception("no such table: wiki_symbols"))++ monkeypatch.setattr(hints_module, "_read_test_hints", _raise)+ # Record the call itself: whether a log record reaches caplog depends on how+ # earlier tests configured logging, which a full run changes.+ warned: list[str] = []+ monkeypatch.setattr(hints_module.log, "warning", lambda event, **_k: warned.append(event))+ pc = compute_patch_coverage({"a.py": {1}}, {"a.py": file_coverage("a.py", [], [1])})+ assert await read_test_hints(object(), "r", pc) is None+ assert warned == ["patch_coverage_hints_failed"]+++async def test_working_tree_coverage_is_current_only_when_ingested_after_the_last_edit(+ monkeypatch, factory, session, tmp_path+):+ import os+ from datetime import UTC, datetime++ ingested = datetime(2026, 9, 1, 12, 0, tzinfo=UTC)+ await _stored_repo(monkeypatch, session, tmp_path, ingested_at=ingested)+ source = tmp_path / "a.py"+ source.write_text("x = 1\ny = 2\n", encoding="utf-8")+ ctx = SimpleNamespace(session_factory=factory, path=tmp_path)++ async def _block():+ return await tool._patch_coverage_block(+ ctx, {"a.py": {1, 2}}, None, None, _scored(working_tree=True),+ _collector(tmp_path), label="origin/main...working tree",+ )++ os.utime(source, (ingested.timestamp() - 60,) * 2)+ before = await _block()+ assert before["scope"]["label"] == "origin/main...working tree"+ assert before["scope"]["freshness"] == "current"+ os.utime(source, (ingested.timestamp() + 60,) * 2)+ assert (await _block())["scope"]["freshness"] == "stale"+++def test_push_base_is_the_ci_base_else_head(monkeypatch):+ import repowise.core.ci.base as ci_base++ monkeypatch.setattr(ci_base, "default_revspec", lambda _root: "origin/main...HEAD")+ assert tool._push_base("/repo") == "origin/main"++ def _none(_root):+ raise ci_base.BaseNotFoundError("no base")++ monkeypatch.setattr(ci_base, "default_revspec", _none)+ assert tool._push_base("/repo") == "HEAD"+++def _patch_block(+ covered: int, coverable: int, hints=None, freshness="current", label="origin/main...HEAD"+) -> dict:+ return {+ "covered_line_count": covered,+ "coverable_line_count": coverable,+ "scope": {"freshness": freshness, "label": label},+ "files": [{"hints": hints}],+ }+++def test_the_directive_names_the_scope_and_the_tests_to_extend():+ from repowise.server.mcp_server._change_health import patch_coverage_action++ assert patch_coverage_action(None) is None+ assert patch_coverage_action(_patch_block(3, 3)) is None+ hints = [+ {"tests": ["tests/test_a.py", "tests/test_b.py"]},+ {"tests": ["tests/test_a.py"]},+ {"tests": ["tests/test_c.py"]},+ ]+ assert patch_coverage_action(_patch_block(1, 3, hints)) == (+ "2 changed executable lines since origin/main are uncovered; "+ "extend tests/test_a.py, tests/test_c.py"+ )+ assert patch_coverage_action(_patch_block(0, 1, label="working tree")) == (+ "1 changed executable line in the working tree is uncovered; "+ "add tests for them (patch_coverage.files)"+ )+ # Stale coverage leads: its gaps are not real until the tests run again.+ assert patch_coverage_action(_patch_block(0, 1, hints, freshness="stale")).startswith(+ "Stored coverage predates this change: re-run the tests with coverage, then "+ "`repowise coverage add`"+ )+++def _git(cwd, *args: str) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)+++def branch_repo(tmp_path, monkeypatch):+ """``main`` has a.py; branch ``feat`` committed line 2; the push base is main."""+ import repowise.core.ci.base as ci_base++ _git(tmp_path, "init", "-q", "-b", "main")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ (tmp_path / "a.py").write_text("a = 1\nb = 2\nc = 3\n", encoding="utf-8")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-qm", "init")+ _git(tmp_path, "switch", "-qc", "feat")+ (tmp_path / "a.py").write_text("a = 1\nb = 22\nc = 3\n", encoding="utf-8")+ _git(tmp_path, "commit", "-qam", "feat")+ monkeypatch.setattr(ci_base, "default_revspec", lambda _root: "main...HEAD")+ return tmp_path+++async def test_no_revspec_measures_everything_the_push_brings(branch_repo):+ scored = ({"a.py": {9}}, None) # what the score read; not what the push brings++ # Clean tree: the branch since main, not just the last commit.+ clean = await tool._push_change(str(branch_repo), None, False, (), (), scored)+ assert clean == ({"a.py": {2}}, None, "main...HEAD", "main...HEAD")++ # Dirty tree: committed and uncommitted together.+ (branch_repo / "a.py").write_text("a = 1\nb = 22\nc = 33\n", encoding="utf-8")+ dirty = await tool._push_change(str(branch_repo), None, True, (), (), scored)+ assert dirty[:3] == ({"a.py": {2, 3}}, None, "main...working tree")++ # An explicit revspec is measured as given.+ assert await tool._push_change(str(branch_repo), "HEAD", False, (), (), scored) == (+ *scored, None, "HEAD",+ )+++async def test_an_unresolvable_push_base_falls_back(branch_repo, monkeypatch):+ import repowise.core.ci.base as ci_base++ (branch_repo / "a.py").write_text("a = 1\nb = 22\nc = 33\n", encoding="utf-8")+ monkeypatch.setattr(ci_base, "default_revspec", lambda _root: "gone...HEAD")+ scored = ({"a.py": {3}}, None)++ # Dirty: the plain working-tree diff, labelled as such.+ dirty = await tool._push_change(str(branch_repo), None, True, (), (), scored)+ assert dirty[:3] == ({"a.py": {3}}, None, "working tree")+ # Clean: what was scored.+ _git(branch_repo, "commit", "-qam", "more")+ assert await tool._push_change(str(branch_repo), None, False, (), (), scored) == (+ *scored, None, None,+ )+++def test_the_patch_coverage_action_joins_the_directive(monkeypatch):+ def _broken(_path):+ raise RuntimeError("no comparison")++ monkeypatch.setattr(tool, "_delta_service", _broken)+ delta = tool._compare_health("/repo", None, (), ())+ payload = {"patch_coverage": _patch_block(1, 2, [{"tests": ["tests/test_a.py"]}])}++ tool._attach_health(payload, delta, None, expand=False)+ assert payload["directive"]["next_actions"][-1] == (+ "1 changed executable line since origin/main is uncovered; extend tests/test_a.py"+ )diff --git a/tests/unit/server/test_patch_coverage_schema.py b/tests/unit/server/test_patch_coverage_schema.pyindex 09355a473..1478b73c1 100644--- a/tests/unit/server/test_patch_coverage_schema.py+++ b/tests/unit/server/test_patch_coverage_schema.py@@ -6,6 +6,8 @@ from repowise.core.analysis.health.coverage import PathGate, file_coveragefrom repowise.core.analysis.patch_coverage import (FileRisk,PatchScope,+ TestHint,+ attach_hints,attach_risk,compute_patch_coverage,)@@ -70,3 +72,10 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:assert risked["risky"]["gate"] == "too_small"assert risked["files"][0]["risk"]["basis"] == "git_and_index"assert PatchCoverageResponse.model_validate(risked).model_dump() == risked++ # With hints attached: a measured row carries them, the others stay null.+ hint = TestHint((2, 3), "Auth.login", ("tests/test_a.py",), "per_test", 2)+ hinted = attach_hints(pc, {"a.py": (hint,)}).to_dict()+ assert hinted["files"][0]["hints"][0]["basis"] == "per_test"+ assert {f["file_path"] for f in hinted["files"] if f["hints"] is not None} == {"a.py"}+ assert PatchCoverageResponse.model_validate(hinted).model_dump() == hinteddiff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.pyindex 369545dfc..d0a8e3ae4 100644--- a/tests/unit/server/test_risk_range.py+++ b/tests/unit/server/test_risk_range.py@@ -272,6 +272,10 @@ async def test_patch_coverage_reads_stored_coverage(# The index has no git row for a file the change adds, so git alone answers.assert data["files"][0]["risk"]["basis"] == "git"assert data["risky"]["file_count"] == 0+ # The index knows no symbol or test here: a hint that honestly names none.+ assert data["files"][0]["hints"] == [+ {"range": [3, 3], "symbol": None, "tests": [], "basis": "none", "total": 0}+ ]assert (await client.get(url, params={"base": "nope"})).status_code == 400# The repository's coverage config reaches the stored-coverage surface as