Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(coverage): re-ingest after failing test runs, accept globs in coverage add, and show the trend in get_health (#2658)

Raghav Chamadiyafbaaba242304
diff --git a/README.md b/README.md
index cd25c6fb2..fa9f9e953 100644
--- a/README.md
+++ b/README.md
@@ -297,6 +297,10 @@ changed file and outside caller across the repository.
**[Install the PR bot →](https://github.com/apps/repowise-bot)** ·
[how it works →](https://www.repowise.dev/bot)
+Patch coverage, doc drift, security and change risk also run as CI gates in your own
+pipeline, with a GitHub Action and a GitLab template, and need no index or API key.
+[Repowise in CI →](docs/start/CI.md)
+
---
<a id="code-health"></a>
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index 53eae5d4c..ac381fdf9 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -24,6 +24,7 @@ crashes or blocks your agent.
| **SessionStart context** | Claude Code | `repowise init` | session `startup` / `resume` / `clear` | Live index-freshness line, core-tool trust rule, and the standing decisions relevant to this session |
| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / repowise MCP calls | Graph context on searches, read-intelligence notices, and edit-time "governed by" decision notices |
| **Wrong-path rescue** | Claude Code | `repowise init` | a `Read` / `Edit` / `Write` / `Grep` / `Glob` / `NotebookEdit` that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise |
+| **Coverage re-ingest** (opt-in) | Claude Code | `hooks.coverage_reingest: true`, then the next `repowise coverage add` / `init` / `update` | `Bash` / `PowerShell`, success or failure | Re-ingests a fresh full-suite coverage report in the background; a process start per shell command in that repo |
| **Command-rewrite (distill)** | Claude Code | `repowise hook rewrite install` (opt-in) | `Bash` / `PowerShell` | Rewrites noisy commands to `repowise distill <cmd>`; auto-allowed by default, set `permission: ask` to approve each one |
| **Codex context + staleness** | Codex | `repowise init --codex` | SessionStart / edit / shell | Reminds Codex to use the MCP tools and flags stale context after edits |
@@ -314,10 +315,12 @@ migrate either. A hook *you* wrote on that event is left alone, and a timeout
you raised yourself is never moved.
Codex names its shell tool `shell_command` on current releases and `Bash` on
-older ones, so the matcher covers both. The Claude Code hook deliberately does
-*not* watch shell commands: it has `Read` / `Grep` / `Glob` tools and a
+older ones, so the matcher covers both. The shared Claude Code hook deliberately
+does *not* watch shell commands: it has `Read` / `Grep` / `Glob` tools and a
SessionStart freshness line, so the shell adds cost without adding reach. Codex
-has neither, which is why it keeps the surface.
+has neither, which is why it keeps the surface. The opt-in exceptions are the
+decision capture prompt and the coverage re-ingest (see
+[What gets written where](#what-gets-written-where)).
Full Codex setup: [CODEX.md](CODEX.md).
@@ -352,13 +355,19 @@ returned silence.
## What gets written where
`repowise init` writes these entries into `~/.claude/settings.json` (Claude Code)
-and `.codex/hooks.json` (Codex when `--codex` is passed):
+and `.codex/hooks.json` (Codex when `--codex` is passed). The opt-in coverage
+re-ingest entries go to the repository's own `.claude/settings.local.json`
+instead: with `hooks.coverage_reingest: true`, the next `repowise coverage add`,
+`init` or `update` that finds stored coverage writes them when the Claude Code
+hooks above are installed, and removes them once the key is false or gone
+(`repowise uninstall` removes them too). The plugin does not carry them.
| Client | Hook type | Matcher | Command |
|--------|-----------|---------|---------|
| Claude Code | `SessionStart` | `startup\|resume\|clear` | `repowise-augment` [^guard] |
| Claude Code | `PostToolUse` | `Grep\|Glob\|Read\|Edit\|Write\|mcp__.*[Rr]epowise.*__.*` | `repowise-augment` [^guard] |
| Claude Code | `PreToolUse` (opt-in) | `Bash\|PowerShell` | `repowise-rewrite` |
+| Claude Code, this repo only | `PostToolUse` and `PostToolUseFailure` | `Bash\|PowerShell` | `repowise-augment --coverage-only` [^guard] |
| Codex | `SessionStart` | `startup\|resume\|clear` | context reminder |
| Codex | `PostToolUse` | `Bash\|shell_command`, `apply_patch\|Edit\|Write` | staleness check |
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 1d1d3e9c7..661d84db7 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -1246,6 +1246,11 @@ code that has moved), and `unknown` when either commit is missing.
it is null for coverage stored before that record existed. `source_formats`
lists every report format merged.
+In dashboard mode the block also carries `history`, one point per complete
+(not partial) ingest (`ingested_at`, `ingested_commit_sha`, `line_coverage_pct`,
+`branch_coverage_pct`), oldest first, newest 10, with `history_total`,
+`history_emitted` and `history_reduced_reason: "limit"` when cut.
+
In targeted mode each row also carries a `decay` block: how many of the
report's covered lines are unchanged since it ran (`confirmed_lines`) and how
many have moved since (`invalidated_lines`, now unknown rather than uncovered).
@@ -1476,7 +1481,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, 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`).
+- **Claude Code PostToolUse**: broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, git operations can trigger stale-wiki notices, and with `hooks.coverage_reingest: true` (opt-in) a full test run, passing or failing, re-ingests its fresh coverage report in the background ([details](HOOKS.md#what-gets-written-where)).
- **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.md
index 3d6bdba28..beb4ebbe6 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -486,31 +486,40 @@ rule above. When changed lines are uncovered, the directive gains one
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
+The loop can close itself in Claude Code and Codex, opt-in per repository
+with `hooks.coverage_reingest: true` in `.repowise/config.yaml`
+(`REPOWISE_HOOK_COVERAGE_REINGEST=1` for one session). It costs a process
+start after every shell command in that repository. 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."
+`jest`, `cargo test`, `cargo llvm-cov`, `mvn test` or `./gradlew test`,
+passed or failed (not interrupted), 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 any is newer
+than the index's last coverage ingest, it starts `repowise coverage add` on
+every watched report 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).
+only in a repository that has ingested coverage before, and only on a run
+that does not target some tests: a path, a `::` node id, `-k`, `-run`, `-t`,
+`--testNamePattern`, `--filter`, `--package`, `--workspace`, `-pl`,
+`--projects`, or a short flag's argument the runner does not document as a
+value (`cargo test -p x`) makes a run partial, and a partial report must not
+replace full-suite coverage. It never acts on a coverage.py `.coverage`
+database alone, when discovery is customised (`auto_discover: false` without
+`paths`, or custom `artifacts` globs), or under `REPOWISE_DB_URL`. 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 `**` pattern finds is not watched:
+name it in `coverage.paths` (single-level globs such as `coverage/*.xml` are
+watched).
+
+Claude Code runs it from repo-local entries ([what gets written
+where](../agent/HOOKS.md#what-gets-written-where)); Codex only after a
+successful command, so a failing run there may need `repowise coverage add`.
## The inferred tier: no coverage report needed
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 1f4132719..79dfc3b5d 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1293,8 +1293,16 @@ repowise coverage suggest-gates # propose path-scoped gates for coverage
|------|-------------|
| `--path` | Repo path (defaults to cwd / workspace primary) |
| `--format` | Force a parser instead of auto-detecting: `lcov`, `cobertura`, `clover`, `repowise-json`, `go-coverprofile`, `jacoco` |
+| `--strict` | Also exit non-zero when some report files did not map to the repo tree |
| `--verbose` / `-v` | Show debug logs while discovering and ingesting coverage |
+Each `PATH` is a report path or a quoted glob, relative to cwd, as in
+`coverage check --report`; only when it matches nothing is it read as
+`PATH=PREFIX`, prepending `PREFIX` to the paths inside the report (like
+`path_prefix` in `coverage.paths`). A `PATH` matching no file exits 2. A
+successful ingest also syncs the opt-in coverage re-ingest hook
+(`hooks.coverage_reingest`).
+
`add` ingests per-file line/branch coverage from LCOV, Cobertura, Clover,
JaCoCo XML, a Go coverprofile (`go test -coverprofile`), or a coverage.py
`.coverage` file. It auto-discovers `coverage/lcov.info`, `.coverage`,
@@ -1310,6 +1318,8 @@ per-file coverage; it just skips the map.
repowise coverage add # discover coverage/lcov.info, .coverage, etc.
repowise coverage add coverage/lcov.info
repowise coverage add web.lcov api.lcov # merged, hit wins
+repowise coverage add 'artifacts/**/lcov.info' # every shard's report
+repowise coverage add web/coverage/lcov.info=web # report paths are relative to web/
repowise coverage add --verbose # show ingestion debug logs
coverage run --contexts=test -m pytest # produce .coverage with contexts
repowise coverage add .coverage # per-file coverage + per-test map
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 433c63cbe..51076930f 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -319,8 +319,13 @@ hooks:
read_skeleton: false # serve large indexed files as skeletons
read_reread: false # serve unchanged re-reads as a pointer
search_digest: false # serve multi-file grep floods as a digest
+ coverage_reingest: false # re-ingest coverage after an agent's full test run
```
+- `coverage_reingest` re-ingests coverage after an agent's full test run, at
+ a process start per shell command (`REPOWISE_HOOK_COVERAGE_REINGEST=1` for
+ one session). Details: [test intelligence](../layers/TEST_INTELLIGENCE.md).
+
- `read_reread` lets the PostToolUse Read hook answer a *repeat* Read with a
short notice instead of the content, when the same range was already served
this session, no `Edit`/`Write` came between, and the bytes hash the same.
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
index 83fcca2f4..4d8906a81 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py
@@ -469,6 +469,14 @@ class ClaudeCodeTarget:
if repo_path is None:
raise ValueError("project-scope uninstall needs a repo_path")
result.record(*_remove_project_mcp_entry(project_mcp_config_path(repo_path)))
+ from repowise.cli.editor_integrations.claude_config import (
+ claude_code_local_settings_path,
+ set_repo_coverage_hook,
+ )
+
+ # The coverage re-ingest entries `coverage add` / init / update wrote.
+ if set_repo_coverage_hook(repo_path, False) is not None:
+ result.record(claude_code_local_settings_path(repo_path), FileAction.REMOVED)
return result
settings = settings_path()
@@ -518,7 +526,15 @@ class ClaudeCodeTarget:
def describe_paths(self, scope: Scope, *, repo_path: Path | None = None) -> list[str]:
if scope is Scope.PROJECT:
- return [str(project_mcp_config_path(repo_path or Path.cwd()))]
+ from repowise.cli.editor_integrations.claude_config import (
+ claude_code_local_settings_path,
+ )
+
+ root = repo_path or Path.cwd()
+ return [
+ str(project_mcp_config_path(root)),
+ str(claude_code_local_settings_path(root)),
+ ]
paths = [str(settings_path())]
desktop = desktop_config_path()
if desktop is not None:
diff --git a/packages/cli/src/repowise/cli/augment_hook.py b/packages/cli/src/repowise/cli/augment_hook.py
index 4897350e7..f334ee944 100644
--- a/packages/cli/src/repowise/cli/augment_hook.py
+++ b/packages/cli/src/repowise/cli/augment_hook.py
@@ -40,7 +40,9 @@ def main() -> None:
try:
from repowise.cli.commands.augment_cmd import _run_augment
- _run_augment(client=_parse_client_arg(sys.argv[1:]))
+ _run_augment(
+ client=_parse_client_arg(sys.argv[1:]), coverage_only="--coverage-only" in sys.argv
+ )
except (SystemExit, KeyboardInterrupt):
raise
except BaseException:
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
index 8070f461d..8eed8b4de 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -45,7 +45,13 @@ registers it any more — see :mod:`.codex`.)
* 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``).
+ background and say so in one line (opt-in: ``hooks.coverage_reingest: true``).
+ Codex only here; Claude Code runs it from ``--coverage-only`` below.
+
+ PostToolUse / PostToolUseFailure → Bash / PowerShell (``--coverage-only``)
+ * The coverage re-ingest alone, from the repo-local Claude Code entries
+ ``coverage_reingest.sync_repo_hook`` writes. A failing test run, which
+ still writes its report, arrives as PostToolUseFailure.
PostToolUse → Read
* Skeleton replacement: an unbounded Read of a large indexed file is
@@ -142,6 +148,12 @@ def _adapter(client: str | None):
default=None,
help="Hook client marker. Codex lifecycle hooks pass this explicitly.",
)
+ "--coverage-only",
+ is_flag=True,
+ default=False,
+ help="Run only the coverage re-ingest for shell tools (the repo-local hook entry).",
+)
@click.option(
"--verbose",
"-v",
@@ -149,11 +161,13 @@ def _adapter(client: str | None):
default=False,
help="Show debug logs from the hook pipeline.",
)
-def augment_command(client: str | None = None, verbose: bool = False) -> None:
+def augment_command(
+ client: str | None = None, coverage_only: bool = False, verbose: bool = False
+) -> None:
"""Enrich AI agent tool calls with codebase graph context (hook mode)."""
configure_cli_logging(verbose=verbose)
try:
- _run_augment(client=client)
+ _run_augment(client=client, coverage_only=coverage_only)
except (SystemExit, KeyboardInterrupt):
raise
except Exception:
@@ -161,7 +175,7 @@ def augment_command(client: str | None = None, verbose: bool = False) -> None:
sys.exit(0)
-def _run_augment(*, client: str | None = None) -> None:
+def _run_augment(*, client: str | None = None, coverage_only: bool = False) -> None:
"""Main entry point — reads stdin, dispatches to hook handlers."""
raw = sys.stdin.read()
if not raw.strip():
@@ -177,6 +191,10 @@ def _run_augment(*, client: str | None = None) -> None:
tool_input = payload.get("tool_input", {})
cwd = payload.get("cwd", "")
+ if coverage_only:
+ _run_coverage_only(payload, client)
+ return
+
if client == "codex" and event in ("SessionStart", "UserPromptSubmit"):
session_id = payload.get("session_id", "")
session_id = session_id if isinstance(session_id, str) else ""
@@ -242,6 +260,23 @@ def _run_augment(*, client: str | None = None) -> None:
_count_run(cwd, session_id, event, tool_name, emitted=bool(result))
+def _run_coverage_only(payload: dict, client: str | None) -> None:
+ """The coverage re-ingest for a shell call, success or failure, and nothing else."""
+ event = payload.get("hook_event_name", "")
+ tool_name = payload.get("tool_name", "")
+ if event not in ("PostToolUse", "PostToolUseFailure") or payload.get("is_interrupt"):
+ return
+ if tool_name not in _adapter(client).shell_tool_names:
+ return
+ cwd = payload.get("cwd", "")
+ session_id = payload.get("session_id", "")
+ session_id = session_id if isinstance(session_id, str) else ""
+ result = as_result(coverage_reingest_notice(payload.get("tool_input", {}), cwd))
+ if result:
+ _emit_response(event, result, session_id)
+ _count_run(cwd, session_id, event, tool_name, emitted=bool(result))
+
+
def _count_run(cwd: str, session_id: str, event: str, tool: str, *, emitted: bool) -> None:
"""Bill this invocation to the hook-latency counter; never fails the hook.
@@ -375,33 +410,14 @@ def _handle_post_tool_use(
Every tool-name test below is the adapter's answer for *this* harness.
"""
adapter = _adapter(client)
- # The edit-tool freshness notice is a Codex-only lifecycle hook, gated on
- # the Codex client so the widened Claude matcher (Read|Edit|Write) can't
- # emit Codex-flavored banners to Claude Code users. Both clients record
- # the edit for the per-session stale-read state machine; Claude clients
- # additionally get the once-per-decision governing-decision notice.
if tool_name in adapter.edit_tool_names:
- if client == "codex":
- _record_edit(tool_input, cwd, session_id)
- return as_result(
- _handle_post_edit_use(cwd, session_id=session_id, tool_input=tool_input)
- )
- return as_result(_handle_edit_post(tool_input, cwd, session_id))
+ return _edit_post(tool_input, cwd, client, session_id)
if tool_name in adapter.read_tool_names:
# Read-after-served KPI: logged to the ledger, never spoken about.
_log_read_after_served(tool_input, tool_output, cwd, session_id)
return _handle_read_post(tool_input, tool_output, cwd, session_id, adapter=adapter)
if tool_name in adapter.shell_tool_names:
- # The PowerShell tool (Windows Claude Code) and Codex's several names
- # for its shell all surface the same stdout/stderr response shape as
- # Bash — one handler covers them.
- return as_result(
- 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),
- )
- )
+ return _shell_post(tool_input, tool_output, cwd, client, session_id)
if tool_name in adapter.search_tool_names:
# The adapter reaches this one because the flood digest can *replace*
# the tool output, and not every harness's protocol can honour that.
@@ -414,3 +430,37 @@ def _handle_post_tool_use(
_handle_mcp_read_post(tool_output, cwd, session_id)
return HookResult()
return HookResult()
+
+
+def _edit_post(tool_input: dict, cwd: str, client: str | None, session_id: str) -> HookResult:
+ """The edit-tool surfaces.
+
+ The edit-tool freshness notice is a Codex-only lifecycle hook, gated on
+ the Codex client so the widened Claude matcher (Read|Edit|Write) can't
+ emit Codex-flavored banners to Claude Code users. Both clients record
+ the edit for the per-session stale-read state machine; Claude clients
+ additionally get the once-per-decision governing-decision notice.
+ """
+ if client == "codex":
+ _record_edit(tool_input, cwd, session_id)
+ return as_result(_handle_post_edit_use(cwd, session_id=session_id, tool_input=tool_input))
+ return as_result(_handle_edit_post(tool_input, cwd, session_id))
+
+
+def _shell_post(
+ tool_input: dict, tool_output: dict | str, cwd: str, client: str | None, session_id: str
+) -> HookResult:
+ """The shell surfaces.
+
+ The PowerShell tool (Windows Claude Code) and Codex's several names for its
+ shell all surface the same stdout/stderr response shape as Bash, so one
+ handler covers them.
+ """
+ return as_result(
+ join_notices(
+ _handle_bash_post(tool_input, tool_output, cwd),
+ commit_capture_notice(tool_input, tool_output, cwd, session_id),
+ # Claude Code gets this from its own ``--coverage-only`` entry.
+ coverage_reingest_notice(tool_input, cwd) if client == "codex" else None,
+ )
+ )
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.py
index e226cbc85..67de2e000 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
@@ -1,16 +1,17 @@
-"""PostToolUse Bash: re-ingest the coverage a test run just wrote.
+"""PostToolUse / PostToolUseFailure 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
+hook starts ``repowise coverage add`` on every watched report in the
+background and says so in one line. In Claude Code it fires from repo-local
+entries :func:`sync_repo_hook` writes.
+
+It writes the store without being asked, so it is opt-in and conservative:
+only with ``hooks.coverage_reingest: true`` (or
+``REPOWISE_HOOK_COVERAGE_REINGEST=1`` for one session); 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.
@@ -22,18 +23,21 @@ from __future__ import annotations
import contextlib
import json
+import os
import re
import shlex
import time
from pathlib import Path
from ._shared import _find_repo_root, hook_flag_enabled
+from .fast_lookup import _DB_ENV_VARS
#: 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``.
+#: only a ``**`` glob finds is not watched (a tree walk per test run); name it
+#: in ``coverage.paths`` without ``**``.
DEFAULT_REPORTS = (
"coverage/lcov.info",
"lcov.info",
@@ -64,10 +68,25 @@ _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")
+#: Arguments that pick some tests out of a suite (lower-cased).
+_TARGETING = (
+ "-k", "-run", "-t", "--testnamepattern", "--filter", "--tests", "-dtest",
+ "--package", "--workspace", "-pl", "--projects",
+)
#: Positional arguments that still mean the whole suite.
_WHOLE_SUITE = frozenset({".", "./...", "...", "run", "--"})
+#: Per runner, the single-dash options whose next argument is their value, not
+#: a test. Case-sensitive. Any other short flag's argument reads as a test, so
+#: ``cargo test -p x``, ``npm test -w x`` and ``go test -C sub`` stay partial.
+_PYTEST_VALUE_FLAGS = frozenset({"-p", "-n", "-c", "-o", "-W"})
+_VALUE_FLAGS: dict[str, frozenset[str]] = {
+ "pytest": _PYTEST_VALUE_FLAGS,
+ "py.test": _PYTEST_VALUE_FLAGS,
+ "go": frozenset({
+ "-count", "-timeout", "-parallel", "-cpu", "-tags", "-p",
+ "-covermode", "-coverprofile", "-coverpkg",
+ }),
+}
def is_test_command(command: object) -> bool:
@@ -80,9 +99,8 @@ def is_full_test_run(command: object) -> bool:
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.
+ ``--filter``, ``--package``, ``--workspace``) marks the run partial. The
+ value after one of the runner's :data:`_VALUE_FLAGS` is not a test.
"""
kinds = [_segment_kind(s) for s in _segments(command)]
return any(k is not None for k in kinds) and "partial" not in kinds
@@ -136,17 +154,27 @@ def _segment_kind(segment: str) -> str | 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)
+ tokens = _original_case(shlex.split(args), segment)
except ValueError:
- return True # cannot tell, so do not replace full-suite coverage
+ return "partial" # cannot tell, so do not replace full-suite coverage
+ runner = match.group(0).split()[0]
+ return "partial" if _targets_some(tokens, _VALUE_FLAGS.get(runner, frozenset())) else "full"
+
+
+def _original_case(tokens: list[str], segment: str) -> list[str]:
+ """*tokens* (lower-cased by normalization) as the segment spelled them, when they align."""
+ with contextlib.suppress(ValueError):
+ tail = shlex.split(segment)[-len(tokens):] if tokens else []
+ if [t.lower() for t in tail] == tokens:
+ return tail
+ return tokens
+
+
+def _targets_some(tokens: list[str], value_flags: frozenset[str]) -> bool:
previous = ""
for token in tokens:
- if _is_targeting_flag(token) or _names_some_tests(token, previous):
+ if _is_targeting_flag(token) or _names_some_tests(token, previous, value_flags):
return True
previous = token
return False
@@ -158,9 +186,9 @@ def _is_targeting_flag(token: str) -> bool:
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:
+def _names_some_tests(token: str, previous: str, value_flags: frozenset[str]) -> bool:
+ """A positional argument (not an option's value) that is not "the whole suite"."""
+ if token.startswith("-") or token in _WHOLE_SUITE or previous in value_flags:
return False
return not (previous.startswith("--") and "=" not in previous)
@@ -186,16 +214,16 @@ def _notice(tool_input: dict, cwd: str) -> str | None:
if found is None:
return None
repo, db = found
- fresh = _fresh_reports(repo, db)
- if not fresh:
+ reports = _reports_to_ingest(repo, db)
+ if not reports:
return None
- newest = max(mtime for _path, mtime in fresh)
+ newest = max(mtime for _path, mtime, _prefix in reports)
if _already_queued(repo, newest):
return None
- paths = [path for path, _mtime in fresh]
- spawn_coverage_add(repo, paths)
+ # A mapped ``coverage.paths`` entry keeps its prefix as ``PATH=PREFIX``.
+ spawn_coverage_add(repo, [f"{p}={pre}" if pre else p for p, _mtime, pre in reports])
_write_queued(repo, newest)
- names = ", ".join(_rel(repo, p) for p in paths)
+ names = ", ".join(_rel(repo, p) for p, _mtime, _prefix in reports)
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."
@@ -203,48 +231,68 @@ def _notice(tool_input: dict, cwd: str) -> str | None:
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 root, wiki.db)`` when the repo has a local index and the hook is on.
+
+ ``None`` under a configured database (``REPOWISE_DB_URL``): the ingest
+ would write there, so the local file cannot say whether it is due.
+ """
+ if any(os.environ.get(name) for name in _DB_ENV_VARS):
+ return None
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):
+ if not db.is_file() or not hook_flag_enabled(repo, "coverage_reingest"):
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."""
+def _reports_to_ingest(repo: Path, db: Path) -> list[tuple[Path, float, str | None]]:
+ """Every watched report, once any is newer than the last ingest; none otherwise.
+
+ All of them, not just the fresh ones: the ingest replaces the stored
+ coverage, so a run that rewrote one shard must not drop the others.
+ """
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]
+ found = _existing(repo, candidates)
+ return found if any(mtime > last for _path, mtime, _prefix in found) else []
-def _candidates(repo: Path) -> tuple[str, ...]:
- """The report paths to watch, or ``()`` when the config says not to guess.
+def _candidates(repo: Path) -> dict[str, str | None]:
+ """The report paths to watch, each with its prefix; none when the config says not to guess.
- ``coverage.paths`` when set. Otherwise the default locations, unless
+ ``coverage.paths`` when set (each entry a path, a glob or
+ ``{path, path_prefix}``). 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 ()
+ return {}
paths = block.get("paths")
if isinstance(paths, str):
- return (paths,)
+ return {paths: None}
if isinstance(paths, list) and paths:
- return tuple(str(p) for p in paths if p)
+ return dict(pair for pair in map(_path_entry, paths) if pair is not None)
if block.get("auto_discover", True) is False or block.get("artifacts"):
- return ()
- return DEFAULT_REPORTS
+ return {}
+ return dict.fromkeys(DEFAULT_REPORTS)
+
+
+def _path_entry(entry: object) -> tuple[str, str | None] | None:
+ """One ``coverage.paths`` entry as ``(pattern, prefix)``; ``None`` for an empty one."""
+ if not isinstance(entry, dict):
+ return (str(entry), None) if entry else None
+ if not entry.get("path"):
+ return None
+ prefix = entry.get("path_prefix")
+ return str(entry["path"]), (str(prefix) if prefix else None)
def _coverage_block(repo: Path) -> dict | None:
@@ -271,23 +319,37 @@ def _coverage_block(repo: Path) -> dict | 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.
+def _existing(
+ repo: Path, candidates: dict[str, str | None]
+) -> list[tuple[Path, float, str | None]]:
+ """``(path, mtime, prefix)`` 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))
+ for rel, prefix in candidates.items():
+ for path in _expand(repo, rel):
+ if path.name.startswith(".coverage"):
+ continue
+ with contextlib.suppress(OSError):
+ if path.is_file():
+ found.append((path, path.stat().st_mtime, prefix))
return found
+def _expand(repo: Path, rel: str) -> list[Path]:
+ """The files one watched entry names: a literal path as is, a glob expanded."""
+ if "**" in rel:
+ return [] # ceiling: see DEFAULT_REPORTS
+ if not any(c in rel for c in "*?["):
+ return [repo / rel]
+ # Only a glob pays for the discovery import (absolute roots, pruned dirs).
+ from repowise.core.analysis.health.coverage.discovery import expand_report_patterns
+
+ return expand_report_patterns([rel], repo)
+
+
def _rel(repo: Path, path: Path) -> str:
try:
return path.relative_to(repo).as_posix()
@@ -366,7 +428,7 @@ def _write_queued(repo: Path, newest: float) -> None:
)
-def spawn_coverage_add(repo: Path, reports: list[Path]) -> None:
+def spawn_coverage_add(repo: Path, reports: list[Path | str]) -> 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.
@@ -378,3 +440,40 @@ def spawn_coverage_add(repo: Path, reports: list[Path]) -> None:
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)
+
+
+def sync_repo_hook(repo_path: Path, console) -> None:
+ """Keep this repo's Claude Code coverage re-ingest entries in step with its policy.
+
+ Called wherever coverage gets stored (``coverage add``, ``init``,
+ ``update``). Adds the entries when ``hooks.coverage_reingest`` is true, the
+ repo has a stored coverage ingest and Claude Code has the repowise augment
+ hooks; removes them whenever it is not true. Prints one line when the file
+ changed. Never raises: a hook entry is not worth failing an ingest over.
+ """
+ try:
+ from repowise.cli.editor_integrations.claude_config import (
+ claude_code_augment_installed,
+ set_repo_coverage_hook,
+ )
+
+ if not hook_flag_enabled(repo_path, "coverage_reingest"):
+ removed = set_repo_coverage_hook(repo_path, False)
+ if removed is not None:
+ console.print(
+ f"[dim]Removed the coverage re-ingest hook from {removed} "
+ "(hooks.coverage_reingest is not true).[/dim]"
+ )
+ return
+ found = _local_index(str(repo_path))
+ if found is None or not last_ingest_time(found[1]) or not claude_code_augment_installed():
+ return
+ added = set_repo_coverage_hook(repo_path, True)
+ if added is not None:
+ console.print(
+ f"[dim]Added the coverage re-ingest hook to {added} (this repository only).[/dim]"
+ )
+ except OSError:
+ # A settings file we cannot write is not worth failing an ingest over;
+ # an unreadable one already reads as "no change" in the writer.
+ return
diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
index ada3bc1b2..7a57b9794 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
@@ -263,32 +263,15 @@ def _first_set(flag, configured):
def _cli_reports(args: tuple[str, ...], flag: str = "--report") -> dict[Path, str | None]:
- """``--report`` values: each a path or glob relative to cwd, optionally ``=PREFIX``.
-
- The whole argument is expanded first, so a path or glob holding ``=``
- (``artifacts/shard=1/*.info``) stays one; only when it matches nothing is
- it split on the last ``=``, and the prefix applies to every file the left
- side matches. One that matches no file cannot be evaluated: a report
- missing from a CI job is a broken setup, not a pass. *flag* names the
- option in that message (``--base-report`` reads the same way).
- """
- from repowise.core.analysis.health.coverage import expand_report_patterns
-
- cwd = Path() # relative, so reports read as the caller named them
- out: dict[Path, str | None] = {}
- for arg in args:
- pattern, prefix = arg, None
- matches = expand_report_patterns([arg], cwd)
- if not matches and "=" in arg:
- pattern, _, prefix = arg.rpartition("=")
- matches = expand_report_patterns([pattern], cwd)
- if not matches:
- raise CannotEvaluateError(
- "report_not_found", f"{flag} {arg}: no coverage report matches {pattern}."
- )
- for path in matches:
- out.setdefault(path, prefix or None)
- return out
+ """*flag* values (``--report``, ``--base-report``), relative to cwd; one that matches no file
+ cannot be evaluated."""
+ from repowise.core.analysis.health.coverage import expand_report_args
+
+ try:
+ # Relative, so reports read as the caller named them.
+ return expand_report_args(args, Path())
+ except FileNotFoundError as exc:
+ raise CannotEvaluateError("report_not_found", f"{flag}: {exc}") from None
_NO_REPORT = (
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index 03edc6a71..f04f83af4 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -65,7 +65,7 @@ coverage_group.add_command(coverage_suggest_gates)
@coverage_group.command("add")
[email protected]("paths", nargs=-1, type=click.Path(exists=True, dir_okay=False))
[email protected]("paths", nargs=-1)
@click.option(
"--path", "repo", default=None, help="Repo path (defaults to cwd / workspace primary)."
)
@@ -98,6 +98,16 @@ def coverage_add(
) -> None:
"""Ingest coverage (auto-discovers reports when none are given).
+ Each PATH is a report path or a glob (quote it, e.g. 'artifacts/**/lcov.info'),
+ relative to cwd. PATH=PREFIX prepends PREFIX to the paths inside every report
+ it matches, like a {path, path_prefix} entry in coverage.paths. A PATH that
+ matches no file is an error.
+
+ With hooks.coverage_reingest: true and the Claude Code repowise hooks
+ installed, a successful ingest also adds this repository's coverage
+ re-ingest hook to .claude/settings.local.json (removed again when the flag
+ is not true).
+
Stores per-file line/branch coverage, and additionally the per-test
"test-to-code" map when a report carries contexts - a coverage.py
``.coverage`` written with ``coverage run --contexts=test``, or a per-test
@@ -110,6 +120,8 @@ def coverage_add(
repowise coverage add coverage/lcov.info
repowise coverage add .coverage # per-test map from coverage.py
repowise coverage add web.lcov api.lcov # merged hit-wins
+ repowise coverage add 'artifacts/**/lcov.info'
+ repowise coverage add web/coverage/lcov.info=web
Exits non-zero when nothing was stored, so `coverage add ... || exit 1`
tells a complete ingest from a no-op. With --strict it also exits
@@ -124,6 +136,7 @@ def coverage_add(
CoverageConfig,
build_coverage_map,
discover_artifacts,
+ expand_report_args,
parse_contexts_file,
resolve_test_reports,
)
@@ -131,8 +144,13 @@ def coverage_add(
cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))
+ report_prefixes: dict[Path, str | None] = {}
if paths:
- report_paths = [Path(p) for p in paths]
+ try:
+ report_prefixes = expand_report_args(paths, Path())
+ except FileNotFoundError as exc:
+ raise click.BadParameter(str(exc), param_hint="PATHS") from None
+ report_paths = list(report_prefixes)
else:
report_paths = discover_artifacts(repo_path, globs=cfg.artifacts or None)
report_paths += _discover_context_reports(repo_path)
@@ -213,6 +231,7 @@ def coverage_add(
coverage_format=coverage_format or cfg.format,
strip_prefix=cfg.strip_prefix,
path_prefix=cfg.path_prefix,
+ report_prefixes=report_prefixes,
ignore=cfg.ignore,
)
for path, err in errors:
@@ -273,7 +292,7 @@ def coverage_add(
creport,
repo_keys,
strip_prefix=cfg.strip_prefix,
- path_prefix=cfg.path_prefix,
+ path_prefix=report_prefixes.get(report_path) or cfg.path_prefix,
ignore=cfg.ignore,
)
map_records.extend(rtc.records)
@@ -330,6 +349,9 @@ def coverage_add(
# exit status alone.
if not run_async(_do()):
raise click.exceptions.Exit(1)
+ from repowise.cli.commands.augment_cmd.coverage_reingest import sync_repo_hook
+
+ sync_repo_hook(repo_path, console)
_SQLITE_MAGIC = b"SQLite format 3\x00"
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index 004ec7eae..2240353f0 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -1960,6 +1960,11 @@ def init_command(
options=editor_options,
no_editor_setup=not editor_setup,
)
+ if editor_setup:
+ # The index may carry a coverage ingest now; see ``sync_repo_hook``.
+ from repowise.cli.commands.augment_cmd.coverage_reingest import sync_repo_hook
+
+ sync_repo_hook(repo_path, console)
_record_init_outcome(
result=result,
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index b2eff1130..90ada550f 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -176,6 +176,10 @@ def _refresh_editor_stamp(
# but a stale CLAUDE.md stamp is worth an honest mention.
if degraded is not None:
degraded.append(f"Editor file refresh: {exc}")
+ # This run may have stored coverage (or the flag changed): keep the hook in step.
+ from repowise.cli.commands.augment_cmd.coverage_reingest import sync_repo_hook
+
+ sync_repo_hook(repo_path, console)
def _surface_release_news(*, written_by: str | None) -> None:
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
index 78087b92f..f7fc53dc3 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import contextlib
import json
import sys
from pathlib import Path
@@ -401,6 +402,120 @@ def _failure_entry() -> dict:
}
+#: The repo-local coverage re-ingest entry (shell tools). ``--coverage-only``
+#: runs that one surface, so it never revives the shell notices the narrowed
+#: :data:`_AUGMENT_MATCHER` dropped.
+_COVERAGE_HOOK_COMMAND = (
+ "if command -v repowise-augment >/dev/null 2>&1; "
+ "then exec repowise-augment --coverage-only; fi"
+)
+_COVERAGE_HOOK_EVENTS = ("PostToolUse", "PostToolUseFailure")
+
+
+def claude_code_local_settings_path(repo_path: Path) -> Path:
+ """The repo's own, uncommitted Claude Code settings file."""
+ return Path(repo_path) / ".claude" / "settings.local.json"
+
+
+def _coverage_entry() -> dict:
+ return {
+ "matcher": SHELL_TOOL_MATCHER,
+ "hooks": [
+ {
+ "type": "command",
+ "command": _COVERAGE_HOOK_COMMAND,
+ "timeout": 10,
+ }
+ ],
+ }
+
+
+def _is_coverage_hook(hook: object) -> bool:
+ return "--coverage-only" in _hook_command(hook) and _is_repowise_hook(hook)
+
+
+def claude_code_augment_installed() -> bool:
+ """Whether ``~/.claude/settings.json`` carries the repowise augment hooks."""
+ path = _claude_code_settings_path()
+ try:
+ hooks = load_existing_config(path).get("hooks") if path.exists() else None
+ except Exception:
+ return False
+ post = hooks.get("PostToolUse") if isinstance(hooks, dict) else None
+ return isinstance(post, list) and _has_repowise_hook(post)
+
+
+def set_repo_coverage_hook(repo_path: Path, enabled: bool) -> Path | None:
+ """Add or remove the coverage re-ingest entries in the repo's ``settings.local.json``.
+
+ Claude Code delivers a shell command that exits non-zero, as a failing
+ test run does, as ``PostToolUseFailure``, so the entry sits under both
+ events. Repo-local because the per-shell-call process start is then paid
+ only in a repository that ingests coverage; Claude Code merges hooks across
+ settings files. Returns the file when it changed, else ``None``. A file
+ this leaves empty is removed.
+ """
+ path = claude_code_local_settings_path(repo_path)
+ settings = _read_local_settings(path, enabled)
+ if settings is None or not _apply_coverage_entries(settings, enabled):
+ return None
+ return _write_or_remove(path, settings)
+
+
+def _read_local_settings(path: Path, enabled: bool) -> dict | None:
+ """The file's object, ``{}`` when absent and adding, ``None`` when there is nothing to read."""
+ if not path.exists():
+ return {} if enabled else None
+ try:
+ return load_existing_config(path)
+ except Exception:
+ return None
+
+
+def _apply_coverage_entries(settings: dict, enabled: bool) -> bool:
+ """Add or remove our entry under each event of *settings*, in place; whether it changed."""
+ hooks = settings.setdefault("hooks", {}) if enabled else settings.get("hooks")
+ if not isinstance(hooks, dict):
+ return False
+ changed = False
+ for event in _COVERAGE_HOOK_EVENTS:
+ changed = _apply_coverage_entry(hooks, event, enabled) or changed
+ if not hooks:
+ settings.pop("hooks", None)
+ return changed
+
+
+def _apply_coverage_entry(hooks: dict, event: str, enabled: bool) -> bool:
+ entries = hooks.setdefault(event, []) if enabled else hooks.get(event)
+ if not isinstance(entries, list):
+ return False
+ # Ours only inside a shell-matcher entry: the same command under any other
+ # matcher was written by someone else and is left alone.
+ own = [e for e in entries if isinstance(e, dict) and e.get("matcher") == SHELL_TOOL_MATCHER]
+ present = any(_is_coverage_hook(h) for e in own for h in _hooks_of(e))
+ changed = enabled != present
+ if changed and enabled:
+ entries.append(_coverage_entry())
+ elif changed:
+ kept = list(own)
+ _strip_hooks(kept, _is_coverage_hook)
+ dropped = [e for e in own if not any(e is k for k in kept)]
+ entries[:] = [e for e in entries if not any(e is d for d in dropped)]
+ if not entries:
+ hooks.pop(event, None)
+ return changed
+
+
+def _write_or_remove(path: Path, settings: dict) -> Path | None:
+ """Write *settings*, or remove the file when nothing is left in it."""
+ if not settings:
+ with contextlib.suppress(OSError):
+ path.unlink()
+ return path
+ path.parent.mkdir(parents=True, exist_ok=True)
+ return path if _write_settings(path, settings) else None
+
+
def install_claude_code_hooks() -> Path | None:
"""Register the augment hooks in ~/.claude/settings.json.
diff --git a/packages/cli/src/repowise/cli/spawn.py b/packages/cli/src/repowise/cli/spawn.py
index 923083c78..6f11fde6a 100644
--- a/packages/cli/src/repowise/cli/spawn.py
+++ b/packages/cli/src/repowise/cli/spawn.py
@@ -7,10 +7,12 @@ 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.
+#: of the user.
_WINDOWS_FLAGS = 0x00000008 | 0x08000000
+#: Leave the parent's job, so a child outlives a host that closes its job on
+#: exit. A job that forbids breakaway fails CreateProcess with access denied,
+#: and the spawn is retried inside the job.
+_CREATE_BREAKAWAY_FROM_JOB = 0x01000000
def spawn_detached(argv: list[str], cwd: str, stdout: IO[bytes] | int | None = None) -> None:
@@ -27,8 +29,12 @@ def spawn_detached(argv: list[str], cwd: str, stdout: IO[bytes] | int | None = N
"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]
+ if os.name != "nt":
+ subprocess.Popen(argv, start_new_session=True, **kwargs) # type: ignore[call-overload]
+ return
+ try:
+ subprocess.Popen( # type: ignore[call-overload]
+ argv, creationflags=_WINDOWS_FLAGS | _CREATE_BREAKAWAY_FROM_JOB, **kwargs
+ )
+ except PermissionError:
+ subprocess.Popen(argv, creationflags=_WINDOWS_FLAGS, **kwargs) # type: ignore[call-overload]
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index bd5d150e6..8a4d64531 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -28,6 +28,7 @@ from .discovery import (
build_coverage_map,
configured_coverage,
discover_artifacts,
+ expand_report_args,
expand_report_patterns,
normalize_report_path,
resolve_reports,
@@ -69,6 +70,7 @@ __all__ = [
"decay_since",
"detect_format",
"discover_artifacts",
+ "expand_report_args",
"expand_report_patterns",
"file_coverage",
"is_test_file",
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
index 9b848f2c2..0d5c81d90 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -363,6 +363,31 @@ def expand_report_patterns(patterns: Iterable[str], base: Path) -> list[Path]:
return out
+def expand_report_args(args: Iterable[str], base: Path) -> dict[Path, str | None]:
+ """Report arguments given on a command line, each mapped to its prefix (or ``None``).
+
+ Each is a path or glob relative to *base*, optionally ``PATH=PREFIX``. The
+ whole argument is expanded first, so a path or glob holding ``=``
+ (``artifacts/shard=1/*.info``) stays one; only when it matches nothing is
+ it split on the last ``=``, and the prefix applies to every file the left
+ side matches. Raises :class:`FileNotFoundError` naming the argument when one
+ matches no file: a report the caller named and did not get is a broken setup.
+ """
+ out: dict[Path, str | None] = {}
+ for arg in args:
+ pattern, prefix = arg, None
+ matches = expand_report_patterns([arg], base)
+ if not matches and "=" in arg:
+ pattern, _, prefix = arg.rpartition("=")
+ matches = expand_report_patterns([pattern], base)
+ if not matches:
+ where = f"{arg}: " if pattern != arg else ""
+ raise FileNotFoundError(f"{where}no coverage report matches {pattern}.")
+ for path in matches:
+ out.setdefault(path, prefix or None)
+ return out
+
+
@dataclass
class ResolvedCoverage:
"""Outcome of resolving a parsed report against the indexed tree."""
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py b/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py
index 14ec02c0e..7ba453fc2 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py
@@ -49,6 +49,7 @@ def add_optional_blocks(
result["coverage"] = _coverage_block(
data.coverage_rows,
data.coverage_summary,
+ data.coverage_history,
scoped=data.pop.scoped,
pager=pager,
repo_path=repo_path,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py b/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py
index c4d8b3bda..c39e0dd35 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/coverage.py
@@ -8,16 +8,23 @@ from repowise.core.analysis.health.coverage import decay_since, measurement_ref
from repowise.core.persistence.crud import coverage_row_dict
from repowise.server.mcp_server.tool_health.paging import Pager
+#: The newest ingests the trend carries; ``history_total`` counts the complete ones kept.
+HISTORY_POINTS = 10
+
def _coverage_block(
rows: list[Any],
summary: dict[str, Any],
+ history: list[dict[str, Any]],
*,
scoped: bool,
pager: Pager,
repo_path: str,
) -> dict[str, Any]:
- """Per-file coverage rows plus the stored repo-wide summary.
+ """Per-file coverage rows, the stored repo-wide summary, and its trend.
+
+ ``history`` is the REST route's shape (one point per complete ingest, oldest
+ first), cut to the newest :data:`HISTORY_POINTS`.
Drop the bulky covered-lines arrays from dashboard mode; full
detail is available in targeted mode.
@@ -43,6 +50,12 @@ def _coverage_block(
}
if len(coverage_payload) < len(rows):
block["files_reduced_reason"] = "limit"
+ if history:
+ block["history"] = history[-HISTORY_POINTS:]
+ block["history_total"] = len(history)
+ block["history_emitted"] = len(block["history"])
+ if len(history) > HISTORY_POINTS:
+ block["history_reduced_reason"] = "limit"
return block
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
index a70698b0a..95a0d8c43 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
@@ -38,6 +38,7 @@ from repowise.core.persistence.crud import (
get_test_file_paths,
list_health_snapshots,
load_coverage_for_repo,
+ load_coverage_history,
)
from repowise.core.persistence.models import HealthFileMetric, RefactoringSuggestion
from repowise.server.mcp_server._helpers import filter_rows_by_attr
@@ -83,6 +84,7 @@ class HealthData:
refactoring_recommendations: list[Recommendation] = field(default_factory=list)
coverage_rows: list[Any] = field(default_factory=list)
coverage_summary: dict[str, Any] = field(default_factory=dict)
+ coverage_history: list[dict[str, Any]] = field(default_factory=list)
signals_by_path: dict[str, dict[str, Any]] = field(default_factory=dict)
drift_rows: list[Any] = field(default_factory=list)
drift_unavailable: str | None = None
@@ -138,7 +140,7 @@ async def load_health_data(
data.refactoring, data.performance = await _read_pillars(
session, repository, reference_repository, pop, req
)
- data.coverage_rows, data.coverage_summary = await _read_coverage(
+ data.coverage_rows, data.coverage_summary, data.coverage_history = await _read_coverage(
session, repository, pop, req
)
data.signals_by_path = await _read_signals(session, repository, pop, req)
@@ -265,9 +267,9 @@ async def _read_pillars(
async def _read_coverage(
session: Any, repository: Any, pop: Population, req: HealthRequest
-) -> tuple[list[Any], dict[str, Any]]:
+) -> tuple[list[Any], dict[str, Any], list[dict[str, Any]]]:
if "coverage" not in req.include_set or pop.nothing_resolved:
- return [], {}
+ return [], {}, []
rows = pop.in_scope_rows(
# ``effective_targets``: a raw ``module:foo`` is not a file path.
# Only targeted mode serializes ``covered_lines``, so the dashboard
@@ -290,7 +292,10 @@ async def _read_coverage(
session, repository.id, reference_commit=getattr(repository, "head_commit", None)
)
)
- return rows, summary
+ # Repo-wide and dashboard only, as on REST: a targeted read never draws it.
+ stored = summary.get("file_count") and not pop.scoped
+ history = await load_coverage_history(session, repository.id) if stored else []
+ return rows, summary, history
async def _read_signals(
diff --git a/tests/unit/cli/test_augment_cmd_logging.py b/tests/unit/cli/test_augment_cmd_logging.py
index d92a82c42..2ba5c00aa 100644
--- a/tests/unit/cli/test_augment_cmd_logging.py
+++ b/tests/unit/cli/test_augment_cmd_logging.py
@@ -23,7 +23,7 @@ def test_augment_configures_logging_before_hook_work(
def fake_configure_cli_logging(*, verbose: bool = False) -> None:
events.append(("logging", verbose))
- def fake_run_augment(*, client: str | None = None) -> None:
+ def fake_run_augment(*, client: str | None = None, coverage_only: bool = False) -> None:
events.append(("run", client))
monkeypatch.setattr(augment_cmd, "configure_cli_logging", fake_configure_cli_logging)
diff --git a/tests/unit/cli/test_augment_coverage_reingest.py b/tests/unit/cli/test_augment_coverage_reingest.py
index 0aed799d1..34363a325 100644
--- a/tests/unit/cli/test_augment_coverage_reingest.py
+++ b/tests/unit/cli/test_augment_coverage_reingest.py
@@ -2,14 +2,19 @@
from __future__ import annotations
+import io
+import json
import os
import sqlite3
+import sys
+import tempfile
import time
+from pathlib import Path
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
+from repowise.cli.commands.augment_cmd.command import _handle_post_tool_use, _run_augment
#: When the last ingest happened, in the stored UTC shape SQLite keeps.
_INGESTED_AT = "2026-09-01 12:00:00.000000"
@@ -25,11 +30,20 @@ def _db(root, *ingests: str) -> None:
con.close()
-def repo(tmp_path, monkeypatch):
- """An indexed repo whose last coverage ingest is ``_INGESTED_AT``."""
+#: The re-ingest is opt-in; every fixture repo opts in unless a test says otherwise.
+_OPT_IN = "hooks:\n coverage_reingest: true\n"
+
+
[email protected](autouse=True)
+def _no_env_override(monkeypatch):
monkeypatch.delenv("REPOWISE_HOOK_COVERAGE_REINGEST", raising=False)
+
+
+def repo(tmp_path):
+ """An opted-in indexed repo whose last coverage ingest is ``_INGESTED_AT``."""
_db(tmp_path, _INGESTED_AT)
+ _config(tmp_path, "")
return tmp_path
@@ -48,7 +62,9 @@ def _report(repo, rel: str = "coverage/lcov.info", *, after: float = 60) -> None
def _config(repo, text: str) -> None:
- (repo / ".repowise" / "config.yaml").write_text(text, encoding="utf-8")
+ """Write *text* as the config, opted in unless *text* sets the flag itself."""
+ opt_in = "" if "coverage_reingest" in text else _OPT_IN
+ (repo / ".repowise" / "config.yaml").write_text(opt_in + text, encoding="utf-8")
@pytest.mark.parametrize(
@@ -79,6 +95,11 @@ def _config(repo, text: str) -> None:
"repowise distill pytest -q",
"repowise distill --source hook 'cd api && pytest -q'",
["pytest", "-q"],
+ "pytest -p no:cacheprovider",
+ "pytest -n 4 -W error",
+ "go test -count 1 -coverprofile cover.out ./...",
+ "go test -p 4 ./...",
+ "cargo test --workspaces",
],
)
def test_full_test_runs_are_recognised(command) -> None:
@@ -100,6 +121,17 @@ def test_full_test_runs_are_recognised(command) -> None:
"mvn test -Dtest=AuthTest",
"./gradlew test --tests AuthTest",
"dotnet test --filter Auth",
+ "pytest -x tests/test_a.py",
+ "pytest -m slow",
+ "pytest -w x",
+ "cargo test -p x",
+ "cargo llvm-cov -p x --lcov --output-path lcov.info",
+ "npm test -w x",
+ "./gradlew test -p x",
+ "go test -C sub ./...",
+ "cargo test --package foo",
+ "npm test --workspace=foo",
+ "mvn test -pl core",
],
)
def test_partial_runs_are_not_full(command) -> None:
@@ -142,12 +174,38 @@ def test_a_fresh_report_is_reingested_once(repo, spawned) -> 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
+def test_one_fresh_report_reingests_every_watched_report(repo, spawned) -> None:
+ """The ingest replaces stored coverage, so an older shard must ride along."""
+ _report(repo, "coverage.xml", after=-60)
_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"]
+ assert spawned[0][1] == [
+ repo.resolve() / "coverage" / "lcov.info",
+ repo.resolve() / "coverage.xml",
+ ]
+
+
+def test_nothing_fresh_spawns_nothing(repo, spawned) -> None:
+ _report(repo, after=-60)
+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None
+
+
+def test_an_absolute_glob_skips_pruned_dirs(repo, spawned) -> None:
+ _config(repo, f"coverage:\n paths: ['{(repo / 'out').as_posix()}/*/lcov.info']\n")
+ _report(repo, "out/web/lcov.info")
+ _report(repo, "out/node_modules/lcov.info")
+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is not None
+ assert [Path(p).resolve() for p in spawned[0][1]] == [
+ (repo / "out" / "web" / "lcov.info").resolve()
+ ]
+
+
[email protected]("var", ["REPOWISE_DB_URL", "REPOWISE_DATABASE_URL"])
+def test_a_configured_database_keeps_the_hook_quiet(repo, spawned, monkeypatch, var) -> None:
+ _report(repo)
+ monkeypatch.setenv(var, "postgresql://x/y")
+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None
def test_a_fresh_coverage_database_alone_does_nothing(repo, spawned) -> None:
@@ -188,6 +246,7 @@ def test_an_upgraded_index_reads_its_ingests_from_the_coverage_rows(tmp_path, sp
con.execute("INSERT INTO coverage_files VALUES (?)", (_INGESTED_AT,))
con.commit()
con.close()
+ _config(tmp_path, "")
_report(tmp_path)
assert hook.coverage_reingest_notice({"command": "pytest"}, str(tmp_path)) is not None
assert len(spawned) == 1
@@ -195,16 +254,20 @@ def test_an_upgraded_index_reads_its_ingests_from_the_coverage_rows(tmp_path, sp
def test_a_repo_that_never_ingested_coverage_is_left_alone(tmp_path, spawned) -> None:
_db(tmp_path)
+ _config(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:
+def test_off_by_default_and_the_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")
+ for block in ("", "hooks:\n coverage_reingest: false\n", "coverage_reingest: true\n"):
+ # Absent, false, or not under ``hooks:``: all off.
+ (repo / ".repowise" / "config.yaml").write_text(block, encoding="utf-8")
+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None
+ assert spawned == []
+ monkeypatch.setenv("REPOWISE_HOOK_COVERAGE_REINGEST", "1") # one session
assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is not None
monkeypatch.setenv("REPOWISE_HOOK_COVERAGE_REINGEST", "0")
_report(repo, after=120)
@@ -236,11 +299,14 @@ def test_never_raises(repo, monkeypatch) -> None:
assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None
-def test_the_bash_dispatch_carries_the_note(repo, spawned) -> None:
+def test_the_codex_shell_dispatch_respects_the_flag(repo, spawned) -> None:
_report(repo)
- result = _handle_post_tool_use(
- "Bash", {"command": "pytest"}, {"stdout": "1 passed", "exit_code": 0}, str(repo)
- )
+ args = ("Bash", {"command": "pytest"}, {"stdout": "1 passed", "exit_code": 0}, str(repo))
+ _config(repo, "hooks:\n coverage_reingest: false\n")
+ assert "Re-ingesting" not in (_handle_post_tool_use(*args, client="codex").context or "")
+ assert spawned == []
+ _config(repo, "")
+ result = _handle_post_tool_use(*args, client="codex")
assert "Re-ingesting coverage" in (result.context or "")
@@ -265,3 +331,251 @@ def test_spawn_runs_coverage_add_detached_with_a_fresh_log(tmp_path, monkeypatch
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") == ""
+
+
+def test_a_mapped_config_entry_is_reingested_with_its_prefix(repo, spawned) -> None:
+ _config(
+ repo,
+ "coverage:\n paths:\n - {path: 'web/*.info', path_prefix: web}\n - out/cov.info\n",
+ )
+ _report(repo, "web/lcov.info")
+ _report(repo, "out/cov.info")
+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is not None
+ assert spawned[0][1] == [
+ f"{repo.resolve() / 'web' / 'lcov.info'}=web",
+ repo.resolve() / "out" / "cov.info",
+ ]
+
+
+def test_a_report_only_a_recursive_glob_finds_is_not_watched(repo, spawned) -> None:
+ _config(repo, "coverage:\n paths: ['**/lcov.info']\n")
+ _report(repo)
+ assert hook.coverage_reingest_notice({"command": "pytest"}, str(repo)) is None
+
+
+def _run_hook(payload: dict, monkeypatch, tmp_dir: Path, **kwargs) -> str:
+ """The real stdin/stdout entry point; a private tempdir isolates the emission dedup marker."""
+ out = io.StringIO()
+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_dir))
+ monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(payload)))
+ monkeypatch.setattr(sys, "stdout", out)
+ _run_augment(**kwargs)
+ return out.getvalue()
+
+
+def _shell_payload(repo, event: str, command: str, **extra) -> dict:
+ return {
+ "hook_event_name": event,
+ "tool_name": "Bash",
+ "tool_input": {"command": command},
+ "cwd": str(repo),
+ "session_id": "s1",
+ **extra,
+ }
+
+
+def test_a_failing_test_run_is_reingested_from_the_failure_event(
+ repo, spawned, monkeypatch, tmp_path_factory
+) -> None:
+ """Claude Code delivers a non-zero exit as PostToolUseFailure, with the rewritten command."""
+ _report(repo)
+ payload = _shell_payload(
+ repo,
+ "PostToolUseFailure",
+ "repowise distill --source hook 'pytest -q'",
+ error="Exit code 1\n1 failed, 3 passed",
+ is_interrupt=False,
+ )
+ out = _run_hook(payload, monkeypatch, tmp_path_factory.mktemp("tmp"), coverage_only=True)
+ assert "Re-ingesting coverage" in out
+ assert len(spawned) == 1
+
+
+def test_an_interrupted_test_run_is_left_alone(
+ repo, spawned, monkeypatch, tmp_path_factory
+) -> None:
+ _report(repo)
+ payload = _shell_payload(
+ repo, "PostToolUseFailure", "pytest", error="Interrupted", is_interrupt=True
+ )
+ out = _run_hook(payload, monkeypatch, tmp_path_factory.mktemp("tmp"), coverage_only=True)
+ assert out == ""
+ assert spawned == []
+
+
+def test_coverage_only_runs_nothing_else(repo, spawned, monkeypatch, tmp_path_factory) -> None:
+ """The repo-local entry must not revive the shell notices the shared matcher dropped."""
+ _report(repo)
+ payload = _shell_payload(repo, "PostToolUse", "git commit -m x", tool_response={})
+ out = _run_hook(payload, monkeypatch, tmp_path_factory.mktemp("tmp"), coverage_only=True)
+ assert out == ""
+
+
+def test_the_full_claude_handler_leaves_coverage_to_its_own_entry(repo, spawned) -> None:
+ """Otherwise a capture-prompt shell entry and the coverage entry would both spawn."""
+ _report(repo)
+ result = _handle_post_tool_use("Bash", {"command": "pytest"}, {"stdout": ""}, str(repo))
+ assert "Re-ingesting" not in (result.context or "")
+ assert spawned == []
+
+
[email protected]("nt", [True, False])
+def test_spawn_breaks_away_from_the_job_and_retries_inside_it(monkeypatch, nt) -> None:
+ import subprocess
+
+ from repowise.cli import spawn
+
+ calls: list[dict] = []
+
+ def _popen(argv, **kwargs):
+ calls.append(kwargs)
+ if kwargs.get("creationflags", 0) & spawn._CREATE_BREAKAWAY_FROM_JOB:
+ raise PermissionError(5, "Access is denied")
+
+ monkeypatch.setattr(spawn.os, "name", "nt" if nt else "posix")
+ monkeypatch.setattr(subprocess, "Popen", _popen)
+ spawn.spawn_detached(["x"], ".")
+
+ if nt:
+ assert [c["creationflags"] for c in calls] == [
+ spawn._WINDOWS_FLAGS | spawn._CREATE_BREAKAWAY_FROM_JOB,
+ spawn._WINDOWS_FLAGS,
+ ]
+ else:
+ assert len(calls) == 1 and calls[0]["start_new_session"] is True
+
+
+# --- the repo-local Claude Code entries --------------------------------------
+
+
+def claude_home(tmp_path_factory, monkeypatch) -> Path:
+ """A user settings.json carrying the repowise augment hooks."""
+ from repowise.cli.editor_integrations import claude_config
+
+ path = tmp_path_factory.mktemp("home") / "settings.json"
+ entry = {
+ "matcher": claude_config._AUGMENT_MATCHER,
+ "hooks": [{"type": "command", "command": claude_config._AUGMENT_HOOK_COMMAND}],
+ }
+ path.write_text(json.dumps({"hooks": {"PostToolUse": [entry]}}), encoding="utf-8")
+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: path)
+ return path
+
+
+class _Console:
+ def __init__(self) -> None:
+ self.lines: list[str] = []
+
+ def print(self, text: str) -> None:
+ self.lines.append(text)
+
+
+def _local_hooks(repo: Path) -> dict:
+ path = repo / ".claude" / "settings.local.json"
+ return json.loads(path.read_text(encoding="utf-8")).get("hooks", {}) if path.exists() else {}
+
+
+def test_sync_adds_the_coverage_only_entry_under_both_events(repo, claude_home) -> None:
+ console = _Console()
+ hook.sync_repo_hook(repo, console)
+
+ hooks = _local_hooks(repo)
+ for event in ("PostToolUse", "PostToolUseFailure"):
+ (entry,) = hooks[event]
+ assert entry["matcher"] == "Bash|PowerShell"
+ assert "repowise-augment --coverage-only" in entry["hooks"][0]["command"]
+ assert "statusMessage" not in hooks["PostToolUse"][0]["hooks"][0] # runs silently
+ (line,) = console.lines
+ assert "this repository only" in line and "settings.local.json" in line
+ hook.sync_repo_hook(repo, console) # idempotent, and silent when nothing changes
+ assert len(console.lines) == 1
+
+
+def test_default_config_writes_nothing(repo, claude_home) -> None:
+ (repo / ".repowise" / "config.yaml").unlink()
+ console = _Console()
+ hook.sync_repo_hook(repo, console)
+ assert _local_hooks(repo) == {}
+ assert console.lines == []
+
+
+def test_turning_the_flag_off_again_removes_the_entries(repo, claude_home) -> None:
+ hook.sync_repo_hook(repo, _Console())
+ (repo / ".repowise" / "config.yaml").unlink() # absent reads as off
+ hook.sync_repo_hook(repo, _Console())
+ assert _local_hooks(repo) == {}
+
+
+def test_the_opt_out_removes_only_our_entries(repo, claude_home) -> None:
+ local = repo / ".claude" / "settings.local.json"
+ local.parent.mkdir()
+ local.write_text(json.dumps({"permissions": {"allow": ["Bash(ls)"]}}), encoding="utf-8")
+ hook.sync_repo_hook(repo, _Console())
+ assert _local_hooks(repo)
+
+ _config(repo, "hooks:\n coverage_reingest: false\n")
+ console = _Console()
+ hook.sync_repo_hook(repo, console)
+
+ assert json.loads(local.read_text(encoding="utf-8")) == {
+ "permissions": {"allow": ["Bash(ls)"]}
+ }
+ assert "Removed" in console.lines[0]
+
+
+def test_a_file_the_opt_out_empties_is_removed(repo, claude_home) -> None:
+ hook.sync_repo_hook(repo, _Console())
+ _config(repo, "hooks:\n coverage_reingest: false\n")
+ hook.sync_repo_hook(repo, _Console())
+ assert not (repo / ".claude" / "settings.local.json").exists()
+
+
+def test_sync_needs_a_stored_ingest_and_the_augment_install(
+ repo, tmp_path_factory, claude_home
+) -> None:
+ never = tmp_path_factory.mktemp("never")
+ _db(never)
+ hook.sync_repo_hook(never, _Console())
+ assert _local_hooks(never) == {}
+
+ claude_home.write_text("{}", encoding="utf-8")
+ hook.sync_repo_hook(repo, _Console())
+ assert _local_hooks(repo) == {}
+
+
+def test_uninstall_sweeps_the_repo_local_entries(repo, claude_home) -> None:
+ from repowise.cli.agent_targets.targets.claude_code import ClaudeCodeTarget
+ from repowise.cli.agent_targets.types import Scope
+
+ hook.sync_repo_hook(repo, _Console())
+ local = str(repo / ".claude" / "settings.local.json")
+ assert local in ClaudeCodeTarget().describe_paths(Scope.PROJECT, repo_path=repo)
+
+ ClaudeCodeTarget().uninstall(Scope.PROJECT, repo_path=repo)
+
+ assert _local_hooks(repo) == {}
+
+
+def test_only_our_shell_entry_is_owned(repo, claude_home) -> None:
+ """A repowise ``--coverage-only`` command under another matcher is not ours to remove."""
+ from repowise.cli.agent_targets.targets.claude_code import ClaudeCodeTarget
+ from repowise.cli.agent_targets.types import Scope
+ from repowise.cli.editor_integrations import claude_config
+
+ foreign = {
+ "matcher": "Bash",
+ "hooks": [{"type": "command", "command": "repowise-augment --coverage-only --mine"}],
+ }
+ local = repo / ".claude" / "settings.local.json"
+ local.parent.mkdir()
+ local.write_text(json.dumps({"hooks": {"PostToolUse": [foreign]}}), encoding="utf-8")
+
+ hook.sync_repo_hook(repo, _Console())
+ assert len(_local_hooks(repo)["PostToolUse"]) == 2
+ claude_config.set_repo_coverage_hook(repo, False)
+ assert _local_hooks(repo) == {"PostToolUse": [foreign]}
+
+ hook.sync_repo_hook(repo, _Console())
+ ClaudeCodeTarget().uninstall(Scope.PROJECT, repo_path=repo)
+ assert _local_hooks(repo) == {"PostToolUse": [foreign]}
diff --git a/tests/unit/cli/test_coverage_cmd.py b/tests/unit/cli/test_coverage_cmd.py
index 897cb87ce..c140e3b35 100644
--- a/tests/unit/cli/test_coverage_cmd.py
+++ b/tests/unit/cli/test_coverage_cmd.py
@@ -212,3 +212,142 @@ def test_coverage_add_stamps_live_head_not_stored_column(tmp_path, monkeypatch)
assert result.exit_code == 0, result.output
assert recorded["sha"] == live_head
assert recorded["sha"] != _FakeRepoRow.head_commit
+
+
+def _fake_ingest(monkeypatch: pytest.MonkeyPatch, tmp_path, keys: set[str]) -> list:
+ """Run `coverage add` against *tmp_path* with *keys* indexed; returns the stored rows."""
+
+ class _Row:
+ id = "repo-1"
+ head_commit = None
+
+ class _Session:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ stored: list = []
+
+ async def _save(session, repository_id, files, **kwargs):
+ stored.extend(files)
+
+ async def _repo(session, local_path):
+ return _Row()
+
+ async def _keys(session, repo_id):
+ return keys
+
+ async def _noop(_url):
+ return None
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(coverage_cmd, "_resolve_coverage_repo", lambda _p: tmp_path)
+ monkeypatch.setattr(coverage_cmd, "_repo_file_keys", _keys)
+ monkeypatch.setattr(coverage_cmd, "get_db_url_for_repo", lambda path: "sqlite:///:memory:")
+ monkeypatch.setattr(coverage_cmd, "reconcile_schema_best_effort", _noop)
+ monkeypatch.setattr("repowise.core.persistence.crud.get_repository_by_path", _repo)
+ monkeypatch.setattr("repowise.core.persistence.crud.save_coverage_files", _save)
+ monkeypatch.setattr("repowise.core.persistence.create_engine", lambda url: object())
+ monkeypatch.setattr("repowise.core.persistence.create_session_factory", lambda e: object())
+ monkeypatch.setattr("repowise.core.persistence.get_session", lambda sf: _Session())
+ return stored
+
+
+def _lcov(path, source: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(f"SF:{source}\nDA:1,1\nend_of_record\n", encoding="utf-8")
+
+
+def test_coverage_add_expands_a_glob(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ stored = _fake_ingest(monkeypatch, tmp_path, {"a.py", "b.py"})
+ _lcov(tmp_path / "artifacts" / "one" / "lcov.info", "a.py")
+ _lcov(tmp_path / "artifacts" / "two" / "lcov.info", "b.py")
+
+ result = CliRunner().invoke(cli, ["coverage", "add", "artifacts/**/lcov.info"])
+
+ assert result.exit_code == 0, result.output
+ assert sorted(f.file_path for f in stored) == ["a.py", "b.py"]
+
+
+def test_coverage_add_applies_a_prefix_to_every_match(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ stored = _fake_ingest(monkeypatch, tmp_path, {"web/src/a.ts", "src/a.ts"})
+ _lcov(tmp_path / "web" / "coverage" / "lcov.info", "src/a.ts")
+
+ result = CliRunner().invoke(cli, ["coverage", "add", "web/*/lcov.info=web"])
+
+ assert result.exit_code == 0, result.output
+ assert [f.file_path for f in stored] == ["web/src/a.ts"]
+
+
+def test_coverage_add_rejects_an_argument_matching_nothing(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ _fake_ingest(monkeypatch, tmp_path, {"a.py"})
+
+ result = CliRunner().invoke(cli, ["coverage", "add", "nope/**/lcov.info"])
+
+ assert result.exit_code == 2
+ assert "no coverage report matches nope/**/lcov.info" in result.output
+
+
+def test_coverage_add_adds_the_repo_hook_and_says_so(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ import json
+
+ from repowise.cli.commands.augment_cmd import coverage_reingest
+ from repowise.cli.editor_integrations import claude_config
+
+ _fake_ingest(monkeypatch, tmp_path, {"a.py"})
+ _lcov(tmp_path / "lcov.info", "a.py")
+ (tmp_path / ".repowise").mkdir(exist_ok=True)
+ (tmp_path / ".repowise" / "wiki.db").write_bytes(b"")
+ user = tmp_path / "user-settings.json"
+ entry = {"matcher": "Read", "hooks": [{"command": claude_config._AUGMENT_HOOK_COMMAND}]}
+ user.write_text(json.dumps({"hooks": {"PostToolUse": [entry]}}), encoding="utf-8")
+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: user)
+ monkeypatch.setattr(coverage_reingest, "last_ingest_time", lambda _db: 1.0)
+ monkeypatch.delenv("REPOWISE_HOOK_COVERAGE_REINGEST", raising=False)
+ config = tmp_path / ".repowise" / "config.yaml"
+
+ result = CliRunner().invoke(cli, ["coverage", "add", "lcov.info"]) # off by default
+ assert result.exit_code == 0, result.output
+ assert not (tmp_path / ".claude" / "settings.local.json").exists()
+
+ config.write_text("hooks:\n coverage_reingest: true\n", encoding="utf-8")
+ result = CliRunner().invoke(cli, ["coverage", "add", "lcov.info"])
+
+ assert result.exit_code == 0, result.output
+ assert "this repository only" in result.output
+ assert (tmp_path / ".claude" / "settings.local.json").is_file()
+
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "hooks:\n coverage_reingest: false\n", encoding="utf-8"
+ )
+ result = CliRunner().invoke(cli, ["coverage", "add", "lcov.info"])
+ assert "Removed the coverage re-ingest hook" in result.output
+ assert not (tmp_path / ".claude" / "settings.local.json").exists()
+
+
+def test_init_and_update_keep_the_repo_hook_in_step(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ """Both store coverage, so both sync the hook: update on every outcome, init after setup."""
+ import inspect
+
+ from repowise.cli.commands.augment_cmd import coverage_reingest
+ from repowise.cli.commands.init_cmd import command as init_command
+ from repowise.cli.commands.update_cmd import command as update_command
+
+ calls: list = []
+ monkeypatch.setattr(coverage_reingest, "sync_repo_hook", lambda repo, _c: calls.append(repo))
+ monkeypatch.setattr(
+ "repowise.cli.editor_setup.refresh_editor_project_files", lambda *a, **k: None
+ )
+ update_command._refresh_editor_stamp(tmp_path, None)
+ assert calls == [tmp_path]
+ assert "sync_repo_hook(repo_path, console)" in inspect.getsource(getattr(init_command.init_command, "callback", init_command.init_command))
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 802f0b00d..bb8b8cf03 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -1635,6 +1635,46 @@ async def test_coverage_payload_shape_is_unchanged(setup_mcp, health_data):
assert "covered_lines" in row
+async def test_coverage_carries_its_trend_capped_to_the_newest_points(
+ setup_mcp, health_data, session
+):
+ """The REST route's history shape, newest ten, with the cap stated."""
+ from datetime import UTC, datetime, timedelta
+
+ from repowise.core.analysis.health.coverage import file_coverage
+ from repowise.core.persistence.crud import save_coverage_files
+ from repowise.server.mcp_server import get_health
+ from repowise.server.mcp_server.tool_health.coverage import HISTORY_POINTS
+
+ none = await get_health(include=["coverage"], only=["coverage"])
+ assert "history" not in none["coverage"]
+
+ start = datetime(2026, 9, 1, tzinfo=UTC)
+ for i in range(HISTORY_POINTS + 2):
+ # A different figure each time: an unchanged one restamps the newest ingest.
+ fc = file_coverage("src/auth/service.py", range(1, i + 2), range(1, 30))
+ await save_coverage_files(
+ session, health_data, [fc], source_format="lcov", ingested_at=start + timedelta(i)
+ )
+
+ block = (await get_health(include=["coverage"], only=["coverage"]))["coverage"]
+ history = block["history"]
+ assert len(history) == block["history_emitted"] == HISTORY_POINTS
+ assert block["history_total"] == HISTORY_POINTS + 2
+ assert block["history_reduced_reason"] == "limit"
+ assert set(history[0]) == {
+ "ingested_at", "ingested_commit_sha", "line_coverage_pct", "branch_coverage_pct"
+ }
+ stamps = [point["ingested_at"] for point in history]
+ assert stamps == sorted(stamps) # oldest first
+ assert stamps[-1].startswith("2026-09-12") # the newest ingest is kept
+
+ # Repo-wide, like REST: a targeted read does not draw the trend.
+ targeted = await get_health(include=["coverage"], targets=["src/auth/service.py"])
+ assert "history" not in targeted["coverage"]
+
+
@pytest.mark.asyncio
async def test_refactoring_plans_spread_across_files(setup_mcp, health_data, session):
"""The explicit file_spread view spreads the cap without changing rank.