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: Distill - index-aware output distillation (distill / expand / saved) (#378)
Raghav Chamadiya28ad369473c6
diff --git a/README.md b/README.mdindex 4608fb59b..dea58a50d 100644--- a/README.md+++ b/README.md@@ -141,7 +141,28 @@ Best case shown; across the two benchmarks the range is −49% to −70% tool cavia `get_context` costs **2,391 tokens vs 64,039** for the raw changed files —**~27× fewer**. Reports: [flask48](https://github.com/repowise-dev/repowise-bench/blob/master/BENCHMARK_REPORT_FLASK48.md) · [sklearn48](https://github.com/repowise-dev/repowise-bench/blob/master/BENCHMARK_REPORT_SKLEARN48.md)-### 2 · Code health predicts real defects+### 2 · Distill — index-aware output distillation++Most of what an agent reads from a shell command is noise: 300 lines of+passing tests around 4 failures, full commit bodies for "what changed+recently". `repowise distill <cmd>` compresses command output **before the+agent reads it** — errors-first, exit code preserved, and every omission+reversible via an inline `[repowise#<ref>]` marker (`repowise expand <ref>`).+Paired runs on a public OSS repo, per command:++| Command | Raw → distilled tokens | Saved |+|---|---|---:|+| `pytest -q` (11 failures) | 3,374 → 1,317 | **61%** — all 11 failure lines preserved |+| `git log -50` | 3,064 → 331 | **89%** |+| `git diff` (30 commits) | 62,833 → 8,635 | **86%** |++Small outputs pass through untouched (net-positive guard), and in an+end-to-end spot-check the agent reached the identical root-cause diagnosis+from distilled output as from raw. Opt-in Claude Code hook rewrites noisy+commands automatically (shown for approval); `repowise saved` tracks tokens+and dollars saved. Full guide: **[docs/DISTILL.md →](docs/DISTILL.md)**++### 3 · Code health predicts real defectsHealth scores are collected at a historical commit (T0); bug-fixing commits arecounted over the following 6 months; the two are correlated — strictly no@@ -286,7 +307,7 @@ To add the MCP server to another editor manually:> commit-triggered update takes **under 30 seconds** and only regenerates the> pages your change touched.-**Docs:** [Quickstart](docs/QUICKSTART.md) · [User Guide](docs/USER_GUIDE.md) · [CLI Reference](docs/CLI_REFERENCE.md) · [Codex](docs/CODEX.md) · [MCP Tools](docs/MCP_TOOLS.md) · [Workspaces](docs/WORKSPACES.md) · [Auto-Sync](docs/AUTO_SYNC.md) · [Config](docs/CONFIG.md)+**Docs:** [Quickstart](docs/QUICKSTART.md) · [User Guide](docs/USER_GUIDE.md) · [CLI Reference](docs/CLI_REFERENCE.md) · [Codex](docs/CODEX.md) · [MCP Tools](docs/MCP_TOOLS.md) · [Distill](docs/DISTILL.md) · [Workspaces](docs/WORKSPACES.md) · [Auto-Sync](docs/AUTO_SYNC.md) · [Config](docs/CONFIG.md)---@@ -385,6 +406,8 @@ repowise query "<q>" # ask anything from the terminalrepowise health # code-health KPIs + lowest-scoring filesrepowise risk main..HEAD # score a branch / PR range for defect riskrepowise dead-code # unreachable-code report+repowise distill pytest # compact errors-first output (reversible) — saves 60–90% tokens+repowise saved # tokens & dollars saved by distillationrepowise doctor # check setup, API keys, store drift```diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex c66bec1e8..b68f6fb4e 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -9,6 +9,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0---+## [Unreleased]++### Added+- **Distill — index-aware output distillation.** A new capability that+ compresses noisy command output before the agent reads it, errors-first and+ fully reversible. `repowise distill <cmd>` runs a command and prints a+ compact rendering (exit code preserved, every error line kept, raw output+ stashed behind an inline `[repowise#<ref>]` marker); `repowise expand <ref>`+ restores it, optionally filtered with `-q`. Eight content filters ship+ (test/build output, git status/log/diff, search floods, file listings,+ generic logs), measured at 60–90% token reduction on noisy commands with+ zero error-line loss. An opt-in Claude Code PreToolUse hook+ (`repowise hook rewrite install`, or the `repowise init` prompt) rewrites+ noisy agent commands to `repowise distill <cmd>` pending approval —+ ask-by-default, with per-repo / per-family `allow`/`deny` config; pipes,+ redirects, and compound commands are never rewritten. `repowise saved`+ reports tokens and estimated dollars saved (per-filter / per-day / per-source+ rollups), mirrored by a Distill savings card on the dashboard's Costs page.+- **Read intelligence: skeletons, stale-read notices, search digests.**+ `get_context(..., include=["skeleton"])` returns an indexed file with bodies+ elided — every signature plus the bodies of the most central symbols, sliced+ from persisted symbol bounds with zero query-time parsing (~15% of full-file+ tokens). The PostToolUse hook nudges once per file per session when a large+ `Read` could have been a skeleton, warns when a re-read follows an+ `Edit`/`Write` (excerpts predate the edit), and renders grep floods as a+ compact grouped-by-file digest ordered by graph centrality.+- **Reversible MCP truncation.** Tool responses were always token-budgeted;+ truncation is no longer silent. Dropped content is stored in the omission+ store and surfaced via a `_meta.omitted` envelope (`refs`, `tokens`,+ `restore`); `get_symbol` resolves `repowise#<ref>` omission refs (with an+ optional `query` parameter) alongside symbol ids — the tool count stays at+ nine. One durable store (`.repowise/omissions/`, TTL + size-cap pruned)+ serves the CLI, the hook, and MCP.+- **Distill config & doctor checks.** A `distill:` block in+ `.repowise/config.yaml` (master switch, hook permission posture, per-family+ overrides, disabled filters, omission-store TTL/size). `repowise doctor`+ validates the block, reports omission-store size against its cap, and shows+ rewrite-hook install state.++---+## [0.16.0] — 2026-06-03### Addeddiff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex 27cf69e4f..f673b9895 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -68,6 +68,7 @@ In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (| `--commit-limit` | Max commits to analyze per file (default: 500). || `--follow-renames` | Track file renames in git history. || `--no-claude-md` | Don't generate `CLAUDE.md`. |+| `--distill-hook / --no-distill-hook` | Install or skip the Distill command-rewrite hook (Claude Code PreToolUse). Strictly opt-in: interactive runs prompt (default No); `--no-distill-hook` also gates this repo off in config so a globally installed hook stays inert here. See [DISTILL.md](DISTILL.md). || `--agents / --no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. || `--codex / --no-codex` | Generate or skip project-local Codex MCP/hooks setup. Interactive runs prompt when Codex CLI is installed and logged in; non-interactive runs require `--codex`. || `--yes / -y` | Skip confirmation prompts. |@@ -354,6 +355,63 @@ repowise decision health [PATH] # health dashboard---+### `repowise distill <command>`++Run a command and print a compact, reversible rendering of its output. Noise+(pass parades, progress spam, boilerplate) is dropped; errors, failures, and+summaries always survive; the command's exit code is preserved. Dropped+content is stored in `.repowise/omissions/` and referenced by an inline+`[repowise#<ref>: ...]` marker. On any filter problem the raw output is+printed unchanged. See [DISTILL.md](DISTILL.md) for the full feature guide.++```bash+repowise distill pytest -x+repowise distill git status+repowise distill npm run build+```++Honors the `distill:` block in `.repowise/config.yaml` (master switch,+disabled filters, omission-store sizing).++---++### `repowise expand REF`++Restore the original output behind a `[repowise#<ref>: ...]` omission marker.+Accepts a bare 12-hex ref or a pasted whole marker. Looks in the current+repo's store first, then the user-level fallback store.++| Flag | Description |+|------|-------------|+| `--query / -q` | Return only the lines matching this regex (or substring) |++```bash+repowise expand a1b2c3d4e5f6+repowise expand a1b2c3d4e5f6 -q "FAILED"+```++---++### `repowise saved [PATH]`++Report tokens (and estimated dollars) saved by `repowise distill` — direct+invocations and hook rewrites. Covers the distill command/hook path only; MCP+response truncation is not part of this ledger.++| Flag | Description |+|------|-------------|+| `--by` | Grouping: `filter` (default), `day`, `source` |+| `--since` | Only count savings since this ISO date |+| `--model` | Pricing model for the dollar estimate (input-token rate; default `claude-sonnet-4-6`) |++```bash+repowise saved # per-filter rollup + totals+repowise saved --by day # daily rollup+repowise saved --since 2026-06-01+```++---+### `repowise costs`Show LLM spend tracking.@@ -449,6 +507,26 @@ repowise hook uninstall --workspaceSee [Auto-Sync](AUTO_SYNC.md) for all sync methods (hooks, file watcher, webhooks, polling).+### `repowise hook rewrite install|uninstall|status`++Manage the Distill command-rewrite hook (Claude Code PreToolUse). When+installed, noisy agent commands (tests, builds, git status/log/diff, searches,+listings) are rewritten to `repowise distill <command>` — pending your+approval by default — so the agent sees a compact, errors-first rendering.++```bash+repowise hook rewrite install # writes ~/.claude/settings.json (idempotent)+repowise hook rewrite status+repowise hook rewrite uninstall # removes only the repowise entry+```++`install` also re-enables the current repo's `distill.commands` config if a+prior `repowise init` opt-out had gated it off. `uninstall` is global+(settings.json) and leaves per-repo config untouched. Per-repo posture+(`permission: ask | allow`, per-family overrides) lives under+`distill.commands` in `.repowise/config.yaml` — see+[DISTILL.md](DISTILL.md#configuration).+---## Utility Commands@@ -551,6 +629,12 @@ unreachable. After upgrading, **restart Claude/Codex/Cursor or any MCP client**so it picks up the new executable. (A standalone `repowise version --check` maybe added later.)+**Distill checks.** `doctor` also validates the `distill:` config block+(unknown keys, bad permission values, unknown filter names, non-positive store+sizing), reports the omission store's size against its configured cap, and+shows whether the command-rewrite hook is installed. The hook is opt-in, so+its absence never fails doctor.+---### `repowise delete [REPO_ID]`diff --git a/docs/COMPUTED_GLOSSARY.md b/docs/COMPUTED_GLOSSARY.mdindex 45b93a8f8..c3dc4d05b 100644--- a/docs/COMPUTED_GLOSSARY.md+++ b/docs/COMPUTED_GLOSSARY.md@@ -352,6 +352,7 @@ workspace overlays, MCP responses, and CLI output.| `repowise workspace` | Workspace repo discovery, config entries, update status, cross-repo hook output. | `Found 2 new repo(s)` || `repowise generate-claude-md` | Editor-file data and rendered `.claude/CLAUDE.md`. | `hotspots`, `key_modules`, `decisions` in markdown || `repowise augment` | Hook-time graph/search enrichment for AI tool calls. | Related files, symbols, importers, dependencies |+| `repowise distill` / `expand` / `saved` | Compact errors-first command output with reversible omission markers, marker restoration, and the savings ledger rollup ([DISTILL.md](DISTILL.md)). | `[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); ...]` || `repowise mcp` | FastMCP server exposing the computed graph/wiki/risk tools below. | stdio or SSE transport |## MCP And API-Visible Computed Payloadsdiff --git a/docs/CONFIG.md b/docs/CONFIG.mdindex 17ba3059b..0419b6828 100644--- a/docs/CONFIG.md+++ b/docs/CONFIG.md@@ -13,6 +13,7 @@ repo root on first `init`..repowise/├── wiki.db # SQLite database — all pages, symbols, graph, git metadata, decisions├── lancedb/ # Vector search index (LanceDB)+├── omissions/ # Distill omission store + savings ledger (omissions.db)├── config.yaml # Provider, model, embedder, exclude patterns├── state.json # Last sync commit, page counts, token usage├── mcp.json # MCP server configuration@@ -58,6 +59,35 @@ or models that cannot translate an explicit mode fail before making an API call.> `.repowise/health-rules.json` (per-file biomarker overrides) — see> [CODE_HEALTH.md](CODE_HEALTH.md#configuration).+### The `distill:` block++Controls [output distillation](DISTILL.md) for this repo. Everything defaults+sensibly when the block is absent; `repowise doctor` validates it.++```yaml+distill:+ enabled: true # master switch for this repo+ commands:+ enabled: true # the command path (CLI + hook rewrites)+ permission: ask # ask | allow | off — rewrite-hook posture+ families: # per-filter overrides+ test_output: allow # auto-allow rewrites for test runs+ git_diff: deny # never rewrite git diff here+ disabled_filters: [] # filters to skip entirely, e.g. [logs]+ omission_store:+ ttl_days: 7 # prune stored omissions after this many days+ max_mb: 50 # size cap; oldest entries pruned first+```++- `permission: ask` (the default) means the agent's rewritten command is shown+ for approval; `allow` auto-approves rewrites; `off` disables rewrites here.+- `families` keys are filter names (`test_output`, `build_output`,+ `git_status`, `git_log`, `git_diff`, `search_results`, `file_listing`,+ `logs`) and accept `ask | allow | off | deny`.+- Declining the `repowise init` opt-in prompt writes+ `commands.enabled: false`, so a rewrite hook installed globally from another+ repo stays inert in this one.+---## LLM providersdiff --git a/docs/DISTILL.md b/docs/DISTILL.mdnew file mode 100644index 000000000..02bcf528a--- /dev/null+++ b/docs/DISTILL.md@@ -0,0 +1,258 @@+# Distill — index-aware output distillation++AI coding agents burn most of their context window on *output they never+needed*: 300 lines of passing-test dots to find 4 failures, a full `git log`+to learn "what changed recently", a 60k-token diff to review one hunk. Distill+compresses that output **before the agent reads it** — errors first, structure+preserved, everything reversible.++Distill is a **capability**, not a sixth intelligence layer: it reuses the+index the five layers already build (symbol bounds, graph centrality,+hotspots) to decide *what to keep*, instead of compressing blind.++```bash+repowise distill pytest -x # run pytest, print a compact errors-first rendering+repowise expand a1b2c3d4e5f6 # restore anything that was omitted+repowise saved # tokens & dollars saved so far+```++**Guarantees** (enforced by the engine, asserted by tests):++- **Errors always survive.** Every error/failure-classified line in the raw+ output appears in the distilled rendering.+- **Fully reversible.** Raw output is stored *before* any marker is emitted;+ `repowise expand <ref>` round-trips it byte-for-byte.+- **Fallback to raw.** Any filter error, storage failure, or non-improvement+ prints the original output unchanged. Distillation can never lose output.+- **Net-positive only.** Output is only distilled when it actually gets+ smaller (marker included) — small outputs pass through untouched.+- **Exit codes preserved.** `repowise distill <cmd>` is a drop-in wrapper in+ scripts and agent tool calls alike.++---++## The surfaces++### 1. `repowise distill <cmd>` — the executor++Runs the command (shell semantics preserved), captures stdout+stderr, picks a+filter by command shape (then by content sniff), and prints the compact+rendering. Eight filters ship:++| Filter | Commands | What it keeps |+|---|---|---|+| `test_output` | pytest, jest, vitest, cargo test, go test | failures + assertion details + summary; collapses pass parades |+| `build_output` | npm/tsc/cargo/go builds | errors and warnings grouped; strips progress/boilerplate |+| `git_status` | `git status` | porcelain-style compact status |+| `git_log` | `git log` | recent subjects + counts |+| `git_diff` | `git diff`/`show` | stat + the most relevant hunks |+| `search_results` | grep / rg floods | grouped-by-file digest with per-file counts and anchors |+| `file_listing` | ls / tree / find | grouped tree rendering |+| `logs` | anything log-shaped | template-collapse with counts (timestamps/ids normalized) |++Dropped content is stored in the omission store and referenced inline:++```+[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]+```++### 2. `repowise expand <ref>` — the reversal++```bash+repowise expand a1b2c3d4e5f6 # full original output+repowise expand a1b2c3d4e5f6 -q "FAILED" # only the matching lines+repowise expand "[repowise#a1b2…]" # a pasted whole marker works too+```++Looks in the current repo's store first, then the user-level fallback store.+MCP clients without a shell can resolve the same refs through+`get_symbol("repowise#<ref>")` — see [MCP](#5-mcp-response-budget--_metaomitted).++### 3. The command-rewrite hook (Claude Code)++Opt-in. A PreToolUse hook rewrites noisy agent commands —+`pytest -x` → `repowise distill pytest -x` — **pending your approval**: the+default posture is `ask`, so Claude Code shows you the modified command before+running it. Install:++```bash+repowise hook rewrite install # or opt in during `repowise init`+repowise hook rewrite status+repowise hook rewrite uninstall # removes only the repowise entry+```++The hook is deliberately conservative. It never rewrites:++- pipes, redirections, compound commands (`|`, `>`, `&&`, `;`, backticks, `$()`)+- watch/follow modes (`--watch`, `tail -f`, …)+- anything on the trivial-command ignore-list, or already-prefixed commands+- commands in repos that have not opted into repowise (no `.repowise/` upward)++Per-repo behavior is configured under `distill.commands` in+`.repowise/config.yaml` — see [Configuration](#configuration). Declining the+`repowise init` prompt writes `distill.commands.enabled: false`, so a hook+installed globally from another repo stays inert in this one. The hook answers+in well under 100 ms (stdlib-only hot path, no database).++`repowise init` also adds a short "Output Distillation" section to the managed+`CLAUDE.md`, teaching the agent to prefer `repowise distill <cmd>` voluntarily+and to expand markers instead of re-running commands — this works in **any**+agent that runs shell commands, hook or no hook.++### 4. Read intelligence — skeletons and stale-read notices++The index knows every symbol's line bounds, so repowise can render a **file+skeleton** — every signature, imports, and the bodies of only the most central+symbols — without parsing anything at query time:++```+get_context(["src/big_module.py"], include=["skeleton"])+```++A typical 600-line file skeletonizes to ~15% of its full tokens with every+signature present. Body selection is importance-ranked (symbol PageRank,+hotspot bit, query match) — this is where the index makes distillation+smarter than blind truncation.++The existing PostToolUse hook complements this passively:++- **Skeleton nudge** — after a large `Read` of an indexed file, the agent is+ told the skeleton's token cost vs the full file (once per file per session).+- **Stale-read notice** — after an `Edit`/`Write`, a later `Read` of the same+ file warns that earlier excerpts predate the edit.+- **Search digest** — grep floods (≥50 lines) get a compact grouped-by-file+ digest ordered by graph centrality.++### 5. MCP response budget — `_meta.omitted`++All MCP tool responses were always token-budgeted; before Distill, truncation+was silent. Now every drop goes through the same omission store:++```jsonc+"_meta": {+ "omitted": {+ "refs": ["a1b2c3d4e5f6"],+ "tokens": 5840,+ "restore": "repowise expand <ref> (CLI) or get_symbol(\"repowise#<ref>\", query?) (MCP)"+ }+}+```++`get_symbol` resolves omission refs as well as symbol ids — the+`repowise#<12-hex>` shape is unambiguous next to `path/to/file.py::Name`, and+the optional `query` parameter searches within the stored content. Tool count+stays at nine. See [MCP_TOOLS.md](MCP_TOOLS.md).++> **Note:** MCP truncation is *not* counted in the savings ledger — those+> responses were always capped, so nothing was "saved" relative to before.+> `repowise saved` covers the distill command/hook path only.++---++## The omission store++`.repowise/omissions/omissions.db` — a SQLite sidecar (WAL), deliberately+separate from `wiki.db` so hook-time writes never contend with indexing.+Falls back to `~/.repowise/omissions/` when the current directory is not+inside a repowise repo.++- Content is keyed by a 12-hex truncated SHA-256 — the same ref that appears+ in markers, so one store serves the CLI, the hook, and MCP.+- **Durable across sessions** by design: an agent resuming work tomorrow can+ still expand yesterday's markers.+- Pruning is TTL + size-cap based (`7 days` / `50 MB` by default, configurable),+ applied opportunistically on write. The most recent row is never evicted, so+ a just-rendered marker cannot dangle.++---++## `repowise saved` — the savings report++```bash+repowise saved # per-filter rollup + totals + est. dollars+repowise saved --by day # daily rollup+repowise saved --by source # cli vs hook+repowise saved --since 2026-06-01+repowise saved --model claude-opus-4-6 # price the estimate differently+```++Dollar estimates price saved tokens at the chosen model's *input* rate (saved+tokens are input the agent never had to read) using the same pricing table as+`repowise costs`. Token counts are chars/4 estimates.++The report covers the **distill command/hook path only** — MCP response+truncation is intentionally not in the ledger (see above).++The local dashboard mirrors this: the Costs page's *Cache & savings* tab shows+a Distill savings card with the same rollup.++---++## Measured savings++On a public OSS repository (microdot), one run per command, tokens estimated+chars/4 — the same estimator the ledger uses:++| Command | Raw tokens | Distilled | Saved |+|---|---:|---:|---:|+| `pytest -q` (11 failures) | 3,374 | 1,317 | **61%** — all 11 `FAILED` lines preserved |+| `git log -50` | 3,064 | 331 | **89%** |+| `git diff` (30 commits of history) | 62,833 | 8,635 | **86%** |+| `git log --oneline -30` | 321 | 321 | 0% — already compact, passed through |+| `git status` (clean tree) | 83 | 83 | 0% — too small to distill, passed through |++The 0% rows are the net-positive guard working: distill never bloats small+output. In an end-to-end agent spot-check on the same repo (a seeded+11-failure bug), the agent diagnosed the exact root-cause line and fix from+the distilled test output — identical conclusion to the raw-output run.++Fixture-suite medians across the seven core filters: ≥60% reduction on+test/build output with zero error-line loss (asserted in CI).++---++## Configuration++The `distill:` block in `.repowise/config.yaml`:++```yaml+distill:+ enabled: true # master switch for this repo+ commands:+ enabled: true # the command path (CLI + hook rewrites)+ permission: ask # ask | allow | off — hook posture+ families: # per-filter overrides+ test_output: allow # auto-allow rewrites for test runs+ git_diff: deny # never rewrite git diff here+ disabled_filters: [] # filters to skip entirely, e.g. [logs]+ omission_store:+ ttl_days: 7 # prune stored omissions after this+ max_mb: 50 # size cap, oldest pruned first+```++Everything defaults sensibly with no block present. `repowise doctor`+validates the block (unknown keys, bad permission values, unknown filter+names, non-positive store sizing) and reports the store size against its cap+and whether the rewrite hook is installed.++---++## Safety model, in one place++| Risk | Mitigation |+|---|---|+| A filter eats a critical line | errors-first invariant + fixture tests + `expand` recovery + fallback-to-raw |+| Silent permission escalation | rewrites default to `ask`; the user sees the modified command |+| Marker with nothing behind it | content stored *before* the marker renders; store failure ⇒ raw output |+| Compound-command semantics | pipes/redirects/`&&` are never rewritten |+| Unindexed or stale repo | filters work index-free; index only improves ranking |+| Store growth | TTL + size cap, pruned on write; `repowise doctor` reports size |++---++## See also++- [CLI_REFERENCE.md](CLI_REFERENCE.md) — `distill`, `expand`, `saved`, `hook rewrite`+- [MCP_TOOLS.md](MCP_TOOLS.md) — `_meta.omitted`, skeleton include, `get_symbol` ref overload+- [CONFIG.md](CONFIG.md) — the `distill:` block+- [INTELLIGENCE_LAYERS.md](INTELLIGENCE_LAYERS.md) — the five layers whose index Distill reusesdiff --git a/docs/INTELLIGENCE_LAYERS.md b/docs/INTELLIGENCE_LAYERS.mdindex cdcb08745..327283c64 100644--- a/docs/INTELLIGENCE_LAYERS.md+++ b/docs/INTELLIGENCE_LAYERS.md@@ -230,6 +230,11 @@ and notifies the agent:Run `repowise update` to refresh documentation and graph context.```+> **Related capability:** [Distill](DISTILL.md) reuses these layers' index+> (symbol bounds, centrality, hotspots) to compress noisy command output and+> large file reads before the agent sees them — a capability built *on* the+> five layers, not a sixth layer.+---## Auto-sync — five ways to stay currentdiff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.mdindex f34558150..0ec8aa693 100644--- a/docs/MCP_TOOLS.md+++ b/docs/MCP_TOOLS.md@@ -29,6 +29,31 @@ repowise mcp --transport sse --port 7338 # for web clients---+## Reversible truncation — `_meta.omitted`++Tool responses are token-budgeted. When a response is truncated, the dropped+content is no longer silently lost: it is stored in the repo's+[omission store](DISTILL.md#the-omission-store) and the response's `_meta`+envelope lists how to get it back:++```jsonc+"_meta": {+ "omitted": {+ "refs": ["a1b2c3d4e5f6"],+ "tokens": 5840,+ "restore": "repowise expand <ref> (CLI) or get_symbol(\"repowise#<ref>\", query?) (MCP)"+ }+}+```++Truncated skeleton blocks are replaced in place by a `[repowise#<ref>: ...]`+marker; everything else is captured into one combined document per response.+Resolve refs with `repowise expand <ref>` from a shell, or+`get_symbol("repowise#<ref>")` from any MCP client — the tool count stays at+nine. See [DISTILL.md](DISTILL.md) for the full reversibility model.++---+## `get_overview`Architecture summary, module map, entry points, git health, and community summary.@@ -83,7 +108,7 @@ The workhorse tool. Returns docs, symbols, ownership, freshness, and community m| Parameter | Type | Required | Description ||-----------|------|----------|-------------|| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. |-| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this — symbol targets), `"callees"` (what this calls — symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only) |+| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this — symbol targets), `"callees"` (what this calls — symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only — the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens) || `compact` | boolean | No | Default `true`. Set `false` for full structure block and importer list. || `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |@@ -97,36 +122,51 @@ The workhorse tool. Returns docs, symbols, ownership, freshness, and community mget_context(targets=["src/auth/middleware.ts"])get_context(targets=["middleware", "api/routes", "payments"], include=["callers", "metrics"])get_context(targets=["src/auth"], compact=false, include=["community"])+get_context(targets=["src/big_module.py"], include=["skeleton"])```+**Skeletons:** with `include=["skeleton"]`, file targets gain a structure-level+rendering sliced from the index's persisted symbol bounds (no parsing at query+time): every signature, the import preamble, and the bodies of the top symbols+ranked by graph centrality / hotspot / query match. Elision markers carry+1-indexed line ranges so you can range-`Read` anything back. For+structure-level questions ("what's in this file", "which function handles X")+this replaces a full file read at a fraction of the cost.+---## `get_symbol`Raw source bytes for one indexed symbol with exact line bounds — cheaper andsafer than `Read` + offset math. The only tool that returns actual source code.+Also resolves **omission refs** (`repowise#<12-hex>`) from truncated responses.**Parameters:**| Parameter | Type | Required | Description ||-----------|------|----------|-------------|-| `symbol_id` | string | Yes | Canonical `"path/to/file.py::SymbolName"` from `get_context`'s symbol list. Normalises `::` / `.` / `/` separators across languages. |+| `symbol_id` | string | Yes | Canonical `"path/to/file.py::SymbolName"` from `get_context`'s symbol list (normalises `::` / `.` / `/` separators across languages), **or** an omission ref `"repowise#<12-hex>"` / a pasted whole `[repowise#…]` marker. |+| `query` | string | No | Omission refs only — return just the stored lines matching this regex (or substring). Ignored for symbol ids. || `context_lines` | int | No | Extra source lines before/after the symbol (0–50, default 0) || `repo` | string | No | *(workspace only)* Usually omitted; `"all"` is not supported |-**Returns:** The symbol's source bytes (bounded at ~400 lines), its exact start/end-line numbers, kind, and a `truncated` flag. On a miss, returns an `error` with-the closest matches.+**Returns:** For a symbol id: the symbol's source bytes (bounded at ~400 lines),+its exact start/end line numbers, kind, and a `truncated` flag; on a miss, an+`error` with the closest matches. For an omission ref: the stored content plus+provenance (`source`, `created_at`, `original_tokens`).-**When to use:** When you need the body of one function or class. Pipe the-`symbol_id` straight from `get_context`'s symbol list. Deterministic resolution-on overloads.+**When to use:** When you need the body of one function or class — pipe the+`symbol_id` straight from `get_context`'s symbol list. Or when a response's+`_meta.omitted` lists refs you want back and you have no shell for+`repowise expand` (e.g. Claude Desktop).-**Example call:**+**Example calls:**```get_symbol(symbol_id="src/auth/service.py::AuthService")get_symbol(symbol_id="src/auth/service.py::login", context_lines=10)+get_symbol(symbol_id="repowise#a1b2c3d4e5f6")+get_symbol(symbol_id="repowise#a1b2c3d4e5f6", query="FAILED")```---diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.mdindex a080855ca..ef7b405e3 100644--- a/docs/QUICKSTART.md+++ b/docs/QUICKSTART.md@@ -103,6 +103,19 @@ repowise mcp --transport stdio> **Automatic for Codex:** run `repowise init --codex` to write project-local `.codex/config.toml`, `.codex/hooks.json`, and managed `AGENTS.md`. See [Codex Integration](CODEX.md).+**Cut your agent's context spend (optional):**++```bash+repowise distill pytest -x # compact errors-first output; raw recoverable via `repowise expand`+repowise saved # tokens & dollars saved so far+```++Distill compresses noisy command output (tests, builds, git, searches) before+the agent reads it — **60–90% fewer tokens on noisy commands, with zero+error-line loss** (measured on a public OSS repo). Opt into the Claude Code+rewrite hook at `init` (or `repowise hook rewrite install`) to apply it+automatically, with each rewrite shown for approval. See [Distill](DISTILL.md).+## 5. Keep It in SyncAfter pulling changes or editing code:diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 4caffe0a3..af3a33221 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -27,10 +27,11 @@ Everything you need to know to install, use, and get the most out of repowise.4. [Web UI](#web-ui)5. [MCP Integration with AI Editors](#mcp-integration-with-ai-editors)6. [Proactive Context Enrichment (Hooks)](#proactive-context-enrichment-hooks)-7. [Auto-Sync](#auto-sync)-8. [Environment Variables](#environment-variables)-9. [Common Workflows](#common-workflows)-10. [Troubleshooting](#troubleshooting)+7. [Output Distillation (Distill)](#output-distillation-distill)+8. [Auto-Sync](#auto-sync)+9. [Environment Variables](#environment-variables)+10. [Common Workflows](#common-workflows)+11. [Troubleshooting](#troubleshooting)---@@ -949,6 +950,66 @@ For most day-to-day coding tasks, hooks provide sufficient context automatically---+## Output Distillation (Distill)++Most of an agent's context is spent on command output it never needed — 300+lines of passing tests to find 4 failures, a full `git log` for "what changed+recently". Distill compresses noisy output **before the agent reads it**,+errors-first and fully reversible. Full guide: [DISTILL.md](DISTILL.md).++**Try it from the terminal:**++```bash+repowise distill pytest -x # compact errors-first rendering, exit code preserved+repowise distill git log -50 # recent subjects + counts instead of full bodies+```++Dropped content is referenced by an inline marker and always recoverable:++```+[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]+```++```bash+repowise expand a1b2c3d4e5f6 # full original output+repowise expand a1b2c3d4e5f6 -q "FAILED" # just the matching lines+```++**Make your agent use it.** Two complementary ways:++1. `repowise init` adds an "Output Distillation" section to the managed+ `CLAUDE.md`, so the agent prefers `repowise distill <cmd>` voluntarily —+ works in any agent that runs shell commands.+2. Opt into the **command-rewrite hook** (Claude Code): noisy commands are+ rewritten to `repowise distill <cmd>` automatically, pending your approval.++```bash+repowise hook rewrite install # or answer Yes at the `repowise init` prompt+```++The hook never rewrites pipes/compound commands or watch modes, and defaults+to `ask` so you see every rewritten command. Per-repo behavior lives under+`distill.commands` in `.repowise/config.yaml` (see [CONFIG.md](CONFIG.md)).++**Skeletons for large files.** For structure-level questions about an indexed+file, `get_context(["path"], include=["skeleton"])` returns every signature+plus the bodies of only the most central symbols — typically ~15% of the full+file's tokens. After a large `Read`, the PostToolUse hook nudges the agent+with the skeleton's cost once per file per session.++**Track what you save:**++```bash+repowise saved # per-filter rollup, totals, est. dollars+repowise saved --by day+```++The Costs page in the web UI shows the same numbers on its *Cache & savings*+tab. The ledger covers the distill command/hook path only — MCP response+truncation is not counted.++---+## Auto-Syncrepowise supports five methods to keep your wiki in sync with code changes. See [Auto-Sync](AUTO_SYNC.md) for the full guide.diff --git a/packages/cli/src/repowise/cli/agent_adapters/__init__.py b/packages/cli/src/repowise/cli/agent_adapters/__init__.pynew file mode 100644index 000000000..401f6cdea--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_adapters/__init__.py@@ -0,0 +1,18 @@+"""Agent adapters — one module per AI coding agent that can rewrite tool input.++The distill engine is agent-agnostic: it sees commands and content, never+hook payloads. Everything an agent's hook protocol touches (payload parsing,+response rendering, hook install/uninstall) lives behind the+:class:`~repowise.cli.agent_adapters.base.AgentAdapter` interface, so+supporting a new agent is an additive module here — no engine or hook-script+refactors.++Hot-path discipline: these modules are imported by the ``repowise-rewrite``+PreToolUse hook, which must answer well under its timeout on every shell+command an agent runs. Module scope is stdlib-only; anything heavier+(settings writers, config helpers) is imported lazily inside methods.+"""++from repowise.cli.agent_adapters.base import AgentAdapter, RewriteRequest, RewriteResult++__all__ = ["AgentAdapter", "RewriteRequest", "RewriteResult"]diff --git a/packages/cli/src/repowise/cli/agent_adapters/base.py b/packages/cli/src/repowise/cli/agent_adapters/base.pynew file mode 100644index 000000000..f0a87ae7f--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_adapters/base.py@@ -0,0 +1,83 @@+"""AgentAdapter interface and the agent-agnostic rewrite request/result types.++Deliberately frugal imports: no ``dataclasses`` (pulls ``inspect``), no+``pathlib`` — this module sits on the PreToolUse hot path where every+millisecond of interpreter startup counts. The request/result types are+plain ``__slots__`` classes for the same reason.+"""++from __future__ import annotations++from abc import ABC, abstractmethod+from typing import TYPE_CHECKING, ClassVar++if TYPE_CHECKING:+ from pathlib import Path+++class RewriteRequest:+ """Agent-agnostic view of one shell command an agent is about to run."""++ __slots__ = ("command", "cwd")++ def __init__(self, command: str, cwd: str) -> None:+ self.command = command+ self.cwd = cwd+++class RewriteResult:+ """A decision to rewrite the command before the agent executes it."""++ __slots__ = ("command", "permission", "reason")++ def __init__(self, command: str, permission: str, reason: str) -> None:+ #: The replacement command (e.g. ``repowise distill pytest -x``).+ self.command = command+ #: ``"ask"`` surfaces the rewritten command for user approval;+ #: ``"allow"`` executes it without a prompt. Never auto-allow unless+ #: the user opted in per command family — a silently mutated command+ #: is a permission escalation.+ self.permission = permission+ #: One-line human explanation shown in the agent's permission UI.+ self.reason = reason+++class AgentAdapter(ABC):+ """Everything agent-specific about the command-rewrite hook.++ Implementations translate between one agent's hook protocol and the+ agent-agnostic :class:`RewriteRequest`/:class:`RewriteResult` pair, and+ own that agent's hook install/uninstall. The classification logic in+ :mod:`repowise.cli.rewrite_hook` never sees a hook payload.+ """++ #: Stable adapter identifier (e.g. ``"claude-code"``).+ name: ClassVar[str]++ @abstractmethod+ def detect(self) -> bool:+ """True when this agent appears to be installed for the current user."""++ @abstractmethod+ def parse_hook_payload(self, raw: str) -> RewriteRequest | None:+ """Parse the agent's hook stdin into a request, or None to pass through.++ Must never raise on malformed input — a broken payload is a+ passthrough, not an error.+ """++ @abstractmethod+ def render_response(self, result: RewriteResult) -> str:+ """Render *result* as the agent's hook stdout protocol."""++ @abstractmethod+ def install_rewrite_hook(self) -> Path | None:+ """Register the rewrite hook with this agent; returns the config path."""++ @abstractmethod+ def uninstall_rewrite_hook(self) -> bool:+ """Remove the rewrite hook; True when something was removed."""++ @abstractmethod+ def rewrite_hook_installed(self) -> bool:+ """True when the rewrite hook is currently registered."""diff --git a/packages/cli/src/repowise/cli/agent_adapters/claude_code.py b/packages/cli/src/repowise/cli/agent_adapters/claude_code.pynew file mode 100644index 000000000..51fe623f4--- /dev/null+++ b/packages/cli/src/repowise/cli/agent_adapters/claude_code.py@@ -0,0 +1,78 @@+"""Claude Code adapter — PreToolUse payloads and ``hookSpecificOutput`` responses.++Protocol reference (Claude Code hooks): a PreToolUse hook receives a JSON+payload on stdin with ``hook_event_name``/``tool_name``/``tool_input``/``cwd``+(snake_case) and may answer with camelCase ``hookSpecificOutput`` JSON on+stdout. ``updatedInput`` replaces only the fields it names; with+``permissionDecision: "ask"`` the user is shown the *modified* command for+approval, which is exactly the posture we want for a rewritten command.+"""++from __future__ import annotations++import json+import os.path+from typing import TYPE_CHECKING, ClassVar++from repowise.cli.agent_adapters.base import AgentAdapter, RewriteRequest, RewriteResult++if TYPE_CHECKING:+ from pathlib import Path+++class ClaudeCodeAdapter(AgentAdapter):+ name: ClassVar[str] = "claude-code"++ def detect(self) -> bool:+ return os.path.isdir(os.path.expanduser("~/.claude"))++ def parse_hook_payload(self, raw: str) -> RewriteRequest | None:+ try:+ payload = json.loads(raw)+ except (json.JSONDecodeError, TypeError):+ return None+ if not isinstance(payload, dict):+ return None+ if payload.get("hook_event_name") != "PreToolUse":+ return None+ if payload.get("tool_name") != "Bash":+ return None+ tool_input = payload.get("tool_input")+ command = tool_input.get("command") if isinstance(tool_input, dict) else None+ if not isinstance(command, str) or not command.strip():+ return None+ cwd = payload.get("cwd")+ return RewriteRequest(command=command, cwd=cwd if isinstance(cwd, str) else "")++ def render_response(self, result: RewriteResult) -> str:+ return json.dumps(+ {+ "hookSpecificOutput": {+ "hookEventName": "PreToolUse",+ "permissionDecision": result.permission,+ "permissionDecisionReason": result.reason,+ "updatedInput": {"command": result.command},+ }+ }+ )++ def install_rewrite_hook(self) -> Path | None:+ from repowise.cli.editor_integrations.claude_config import (+ install_claude_code_rewrite_hook,+ )++ return install_claude_code_rewrite_hook()++ def uninstall_rewrite_hook(self) -> bool:+ from repowise.cli.editor_integrations.claude_config import (+ uninstall_claude_code_rewrite_hook,+ )++ return uninstall_claude_code_rewrite_hook()++ def rewrite_hook_installed(self) -> bool:+ from repowise.cli.editor_integrations.claude_config import (+ claude_code_rewrite_hook_installed,+ )++ return claude_code_rewrite_hook_installed()diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd.py b/packages/cli/src/repowise/cli/commands/augment_cmd.pyindex 7b07e6897..db8988d6a 100644--- a/packages/cli/src/repowise/cli/commands/augment_cmd.py+++ b/packages/cli/src/repowise/cli/commands/augment_cmd.py@@ -29,7 +29,21 @@ Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.commit AND no `repowise update` is in flight AND we haven'talready warned for this HEAD, emit a one-line stale-wiki notice.- PostToolUse → edit tools+ PostToolUse → Read+ * Skeleton nudge: a large Read of an indexed file gets a one-line+ pointer at the skeleton surface (get_context include=["skeleton"]),+ with a cheap bounds-arithmetic estimate of the saving. Once per file+ per session.+ * Stale-read notice: when this file was Edited/Written after the+ session's previous Read of it, flag that earlier excerpts are stale.+ Once per file per session, never blocking.++ PostToolUse → Edit / Write+ * Record the edit in the per-session state file so a later Read can+ detect staleness. Emits nothing itself (Claude clients); Codex+ lifecycle hooks additionally get the index-staleness reminder below.++ PostToolUse → edit tools (Codex)* After file edits, emit a short reminder that the indexed context maybe stale.@@ -62,6 +76,11 @@ import click_TRIAGE_THRESHOLD = 15 # grep result lines before we surface a ranking_TRIAGE_TOP_N = 3_RESCUE_TOP_N = 2+_DIGEST_THRESHOLD = 50 # grep result lines before the full compact digest+_DIGEST_TOP_FILES = 10+_READ_NUDGE_MIN_LINES = 100 # Read output lines before a skeleton nudge+_READ_NUDGE_MIN_TOKENS = 800 # full-file tokens below which a nudge is noise+_READ_NUDGE_MAX_RATIO = 0.5 # skeleton must be at most this fraction of full@click.command("augment")@@ -108,7 +127,15 @@ def _run_augment(*, client: str | None = None) -> None:returntool_output = payload.get("tool_response", payload.get("tool_output", {}))- result = _handle_post_tool_use(tool_name, tool_input, tool_output, cwd, client=client)+ session_id = payload.get("session_id", "")+ result = _handle_post_tool_use(+ tool_name,+ tool_input,+ tool_output,+ cwd,+ client=client,+ session_id=session_id if isinstance(session_id, str) else "",+ )if result:_emit_response(event, result)@@ -217,6 +244,21 @@ def _handle_search_post(cwd: str,) -> str | None:"""Decide whether to enrich a Grep/Glob result and how."""+ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return None++ output_text = _extract_output_text(tool_output)+ result_count = _count_search_results(output_text)++ # A genuine flood gets a compact per-file digest regardless of what the+ # pattern looks like — it summarizes the actual results, not the concept.+ if result_count >= _DIGEST_THRESHOLD:+ digest = _grep_flood_digest(repo_path, output_text)+ if digest:+ return digest+ # Unparseable output (e.g. Glob path lists): fall through to triage.+pattern = tool_input.get("pattern")if not isinstance(pattern, str) or not pattern.strip():return None@@ -226,13 +268,6 @@ def _handle_search_post(if _looks_like_path_lookup(pattern):return None- repo_path = _find_repo_root(Path(cwd))- if repo_path is None:- return None-- output_text = _extract_output_text(tool_output)- result_count = _count_search_results(output_text)-# Decision tree. The skip case is the most common — that's by design.if result_count == 0:mode = "rescue"@@ -246,6 +281,97 @@ def _handle_search_post(return asyncio.run(_search_enrich(repo_path, pattern, mode, result_count))+def _grep_flood_digest(repo_path: Path, output_text: str) -> str | None:+ """Compact per-file digest of a Grep flood, index-ranked when possible.++ Cannot replace the tool output (PostToolUse is additionalContext only),+ so this is positioned as a digest the agent can navigate by instead of+ scanning hundreds of match lines. Grouping is pure text work from the+ shared distill filter; PageRank ordering is attempted against the index+ and silently skipped when there is no graph (plain count order then).+ """+ from repowise.core.distill.filters.search_results import (+ group_search_matches,+ render_search_digest,+ )++ groups = group_search_matches(output_text)+ if groups is None or len(groups) < 3:+ # One or two files: the raw output is already navigable.+ return None++ file_order = None+ ranked_by_graph = False+ try:+ import asyncio++ file_order = asyncio.run(_pagerank_file_order(repo_path, list(groups.keys())))+ ranked_by_graph = file_order is not None+ except Exception:+ file_order = None++ if file_order is None:+ file_order = sorted(groups, key=lambda p: -len(groups[p]))++ digest = render_search_digest(groups, file_order=file_order, max_files=_DIGEST_TOP_FILES)+ order_note = "graph centrality" if ranked_by_graph else "match count"+ return f"[repowise] Search flood — compact digest (files ordered by {order_note}):\n{digest}"+++async def _pagerank_file_order(repo_path: Path, paths: list[str]) -> list[str] | None:+ """Order *paths* by indexed PageRank, or None when the graph can't help."""+ db_path = repo_path / ".repowise" / "wiki.db"+ if not db_path.exists():+ # Bail before the sqlalchemy imports — unindexed repos shouldn't pay+ # the heavy-import cost for a digest that falls back to count order.+ return None++ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import get_repository_by_path+ from repowise.core.persistence.database import resolve_db_url++ # Grep output paths may be absolute or OS-native; graph node ids are+ # repo-relative POSIX. Normalize both ways and keep the original spelling.+ normalized: dict[str, str] = {}+ repo_posix = repo_path.as_posix().rstrip("/") + "/"+ for p in paths:+ norm = p.replace("\\", "/").removeprefix("./")+ if norm.startswith(repo_posix):+ norm = norm[len(repo_posix) :]+ normalized[norm] = p++ engine = create_engine(resolve_db_url(repo_path))+ try:+ from sqlalchemy import select++ from repowise.core.persistence import GraphNode++ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return None+ stmt = select(GraphNode.node_id, GraphNode.pagerank).where(+ GraphNode.repository_id == repo.id,+ GraphNode.node_type == "file",+ GraphNode.node_id.in_(normalized.keys()),+ )+ rows = (await session.execute(stmt)).all()+ finally:+ await engine.dispose()++ if not rows:+ return None+ rank = {normalized[node_id]: pr or 0.0 for node_id, pr in rows if node_id in normalized}+ ranked = sorted(rank, key=lambda p: -rank[p])+ rest = [p for p in paths if p not in rank]+ return ranked + rest++def _looks_like_path_lookup(pattern: str) -> bool:"""Heuristic: pattern is a literal file path, not a search concept.@@ -580,6 +706,219 @@ def _name_variants(token: str) -> list[str]:return seen+# ---------------------------------------------------------------------------+# PostToolUse — Read / Edit / Write: per-session read intelligence+# ---------------------------------------------------------------------------+#+# A small JSON state file under .repowise/ tracks which files this agent+# session has Read and Edited, keyed by the hook payload's session_id. Two+# behaviors ride on it:+#+# * Stale-read notice — a Read of a file whose previous Read predates a+# recorded Edit/Write gets a one-line "earlier excerpts are stale" flag.+# * Skeleton nudge — a large Read of an indexed file gets a pointer at+# get_context(include=["skeleton"]) with a bounds-arithmetic estimate.+#+# Rate limiting is the state file itself (per-file, per-session lists), NOT+# the _claim_emission temp marker — that TTL-based dedup only suppresses the+# two concurrently-registered hooks racing on one tool event, which still+# applies on top. A new session_id resets the state.+++def _session_state_path(repo_path: Path) -> Path:+ return Path(repo_path) / ".repowise" / ".augment-session.json"+++def _load_session_state(repo_path: Path, session_id: str) -> dict:+ """Load the per-session read/edit state, resetting on session change.++ ``reads``/``edits`` map repo-relative paths to a monotonically increasing+ per-session sequence number (``seq``) rather than wall-clock time — two+ hook events can land within one clock tick on Windows, and ordering is+ the only thing the stale-read comparison needs.+ """+ fresh = {+ "session_id": session_id,+ "seq": 0,+ "reads": {},+ "edits": {},+ "nudged": [],+ "stale_notified": [],+ }+ try:+ state = json.loads(_session_state_path(repo_path).read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return fresh+ if not isinstance(state, dict) or state.get("session_id") != session_id:+ return fresh+ for key, default in fresh.items():+ if not isinstance(state.get(key), type(default)):+ state[key] = default+ return state+++def _save_session_state(repo_path: Path, state: dict) -> None:+ """Persist session state; trims unbounded growth, never raises."""+ for key in ("reads", "edits"):+ entries = state.get(key, {})+ if len(entries) > 500:+ keep = sorted(entries, key=entries.get, reverse=True)[:400]+ state[key] = {k: entries[k] for k in keep}+ with contextlib.suppress(OSError, TypeError, ValueError):+ _session_state_path(repo_path).write_text(json.dumps(state), encoding="utf-8")+++def _relativize(file_path: str, repo_path: Path) -> str | None:+ """Repo-relative POSIX path for *file_path*, or None when outside it."""+ try:+ rel = Path(file_path).resolve().relative_to(Path(repo_path).resolve())+ except (ValueError, OSError):+ return None+ return rel.as_posix()+++def _record_edit(tool_input: dict, cwd: str, session_id: str) -> None:+ """Note an Edit/Write so a later Read of the file can flag staleness."""+ file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else None+ if not isinstance(file_path, str) or not file_path.strip():+ return+ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return+ rel = _relativize(file_path, repo_path)+ if rel is None:+ return+ state = _load_session_state(repo_path, session_id)+ state["seq"] += 1+ state["edits"][rel] = state["seq"]+ _save_session_state(repo_path, state)+++def _handle_read_post(+ tool_input: dict,+ tool_output: object,+ cwd: str,+ session_id: str,+) -> str | None:+ """Stale-read notice + skeleton nudge for a completed Read."""+ file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else None+ if not isinstance(file_path, str) or not file_path.strip():+ return None+ repo_path = _find_repo_root(Path(cwd))+ if repo_path is None:+ return None+ rel = _relativize(file_path, repo_path)+ if rel is None:+ return None++ state = _load_session_state(repo_path, session_id)+ notices: list[str] = []++ # Stale-read: this session Read the file, then Edited/Wrote it, and is+ # now Reading it again. The fresh Read is fine — the flag is about any+ # reasoning still anchored on the pre-edit excerpt.+ last_read = state["reads"].get(rel)+ last_edit = state["edits"].get(rel)+ if (+ last_read is not None+ and last_edit is not None+ and last_read < last_edit+ and rel not in state["stale_notified"]+ ):+ state["stale_notified"].append(rel)+ notices.append(+ f"[repowise] {rel} changed (Edit/Write) after your previous read of it — "+ "excerpts from before that edit are stale."+ )++ state["seq"] += 1+ state["reads"][rel] = state["seq"]++ nudge = _skeleton_nudge(repo_path, rel, tool_output, state)+ if nudge:+ notices.append(nudge)++ _save_session_state(repo_path, state)+ return "\n".join(notices) if notices else None+++def _read_output_line_count(tool_output: object) -> int:+ """Line count of a Read result across the hook payload shapes we see."""+ if isinstance(tool_output, dict):+ file_block = tool_output.get("file")+ if isinstance(file_block, dict):+ n = file_block.get("numLines")+ if isinstance(n, int):+ return n+ content = file_block.get("content")+ if isinstance(content, str):+ return content.count("\n") + 1+ text = _extract_output_text(tool_output)+ return (text.count("\n") + 1) if text.strip() else 0+++def _skeleton_nudge(repo_path: Path, rel: str, tool_output: object, state: dict) -> str | None:+ """One-line skeleton pointer for a large Read of an indexed file.++ Cheap by construction: bails before any non-stdlib import when the repo+ has no wiki.db, and the size estimate is pure bounds arithmetic — the+ skeleton itself is never rendered on the hook path.+ """+ if rel in state["nudged"]:+ return None+ if _read_output_line_count(tool_output) < _READ_NUDGE_MIN_LINES:+ return None+ db_path = repo_path / ".repowise" / "wiki.db"+ if not db_path.exists():+ return None++ bounds = _file_symbol_bounds(db_path, rel)+ if not bounds:+ return None+ try:+ size = (repo_path / rel).stat().st_size+ except OSError:+ return None+ full_tokens = size // 4+ if full_tokens < _READ_NUDGE_MIN_TOKENS:+ return None++ from repowise.core.distill.skeleton import estimate_skeleton_tokens++ skeleton_tokens = estimate_skeleton_tokens(bounds, file_size_bytes=size)+ if skeleton_tokens > full_tokens * _READ_NUDGE_MAX_RATIO:+ return None++ state["nudged"].append(rel)+ return (+ f"[repowise] A skeleton of {rel} is ~{skeleton_tokens} tokens vs ~{full_tokens} "+ f'for the full file. For structure-level questions use get_context(["{rel}"], '+ 'include=["skeleton"]).'+ )+++def _file_symbol_bounds(db_path: Path, rel: str) -> list[tuple[int, int]]:+ """Persisted (start_line, end_line) pairs for one file, or [] on any miss.++ Direct read-only stdlib sqlite3 — the hook path must not pay the+ sqlalchemy import for two integers per symbol.+ """+ import sqlite3++ try:+ con = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=1)+ try:+ rows = con.execute(+ "SELECT start_line, end_line FROM wiki_symbols WHERE file_path = ?",+ (rel,),+ ).fetchall()+ finally:+ con.close()+ except sqlite3.Error:+ return []+ return [(s, e) for s, e in rows if isinstance(s, int) and isinstance(e, int) and s > 0]++# ---------------------------------------------------------------------------# PostToolUse — Bash: stale-wiki detection after git commits# ---------------------------------------------------------------------------@@ -602,13 +941,20 @@ def _handle_post_tool_use(cwd: str,*,client: str | None = None,+ session_id: str = "",) -> str | None:"""Dispatch PostToolUse events from Claude or Codex."""- # The edit-tool freshness notice is a Codex-only lifecycle hook. Gate it on the- # Codex client so a future widening of the Claude installer's PostToolUse matcher- # can't start emitting Codex-flavored banners to existing Claude Code users.- if client == "codex" and tool_name in _EDIT_TOOL_NAMES:- return _handle_post_edit_use(cwd)+ # 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 first.+ if tool_name in _EDIT_TOOL_NAMES:+ _record_edit(tool_input, cwd, session_id)+ if client == "codex":+ return _handle_post_edit_use(cwd)+ return None+ if tool_name == "Read":+ return _handle_read_post(tool_input, tool_output, cwd, session_id)if tool_name == "Bash":return _handle_bash_post(tool_input, tool_output, cwd)if tool_name in ("Grep", "Glob"):@@ -711,7 +1057,9 @@ def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str |_record_warning(repo_path, head)target_short = (in_flight.get("target_commit") or head)[:8]elapsed = in_flight.get("elapsed_seconds")- elapsed_str = f"started {int(elapsed)}s ago" if isinstance(elapsed, (int, float)) else "running now"+ elapsed_str = (+ f"started {int(elapsed)}s ago" if isinstance(elapsed, (int, float)) else "running now"+ )return (f"[repowise] Wiki update in background — {elapsed_str}, "f"target {target_short}. State will catch up once it finishes."@@ -730,7 +1078,7 @@ def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str |)-def _read_in_flight_marker(repo_path: "object") -> dict | None:+def _read_in_flight_marker(repo_path: object) -> dict | None:"""Return a normalised in-flight marker, or None when nothing is running.Considers two on-disk signals as evidence of an in-flight update:diff --git a/packages/cli/src/repowise/cli/commands/distill_cmd.py b/packages/cli/src/repowise/cli/commands/distill_cmd.pynew file mode 100644index 000000000..c87e5690d--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/distill_cmd.py@@ -0,0 +1,130 @@+"""``repowise distill`` — run a command and emit a distilled rendering.++Executes the real command, captures its output, and prints the compact+errors-first rendering with an omission marker pointing at the stashed raw+output (``repowise expand <ref>`` round-trips it). The wrapped command's+exit code is always preserved, so this is a drop-in replacement in scripts+and agent tool calls alike.+"""++from __future__ import annotations++import subprocess+import sys+from pathlib import Path++import click++from repowise.cli.helpers import find_repowise_repo_root+++ "distill",+ context_settings={"ignore_unknown_options": True},+ short_help="Run a command and print a compact, reversible rendering of its output.",+)[email protected]("command", nargs=-1, required=True, type=click.UNPROCESSED)+def distill_command(command: tuple[str, ...]) -> None:+ """Run COMMAND and print a distilled rendering of its output.++ Examples:++ repowise distill git status++ repowise distill pytest tests/unit -x++ repowise distill npm run build++ Noise (pass parades, progress spam, hint boilerplate) is dropped; errors,+ failures, and summaries always survive. Dropped content is stored in+ .repowise/ and referenced by an inline ``[repowise#<ref>: ...]`` marker —+ restore it with ``repowise expand <ref>``. On any filter problem the raw+ output is printed unchanged. The command's exit code is preserved.+ """+ command_str = _render_command(command)+ # shell=True on purpose: the user's own command may be a shell builtin+ # or a .cmd shim (npm on Windows); we execute exactly what they typed.+ proc = subprocess.run(+ command_str,+ shell=True,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ output = proc.stdout+ if proc.stderr:+ output = output + ("\n" if output and not output.endswith("\n") else "") + proc.stderr++ text = _distill_or_raw(output, command_str, proc.returncode)+ _echo_safely(text)+ sys.exit(proc.returncode)+++def _render_command(tokens: tuple[str, ...]) -> str:+ """Rejoin click's pre-split tokens into one shell command string."""+ if len(tokens) == 1:+ return tokens[0]+ if sys.platform == "win32":+ return subprocess.list2cmdline(tokens)+ import shlex++ return shlex.join(tokens)+++def _distill_or_raw(output: str, command_str: str, exit_code: int) -> str:+ """Distill *output*, honoring the repo's ``distill:`` config block."""+ try:+ repo_root = find_repowise_repo_root()+ enabled, disabled, (ttl_days, max_mb) = _load_distill_config(repo_root)+ if not enabled:+ return output+ from repowise.core.distill import distill_output+ from repowise.core.distill.store import OmissionStore, default_store_path++ # Open the store here (rather than letting the engine) so the+ # configured TTL / size cap apply to this write's opportunistic prune.+ store = OmissionStore(+ default_store_path(repo_root or Path.cwd()), ttl_days=ttl_days, max_mb=max_mb+ )+ try:+ return distill_output(+ output,+ command=command_str,+ exit_code=exit_code,+ source="cli",+ store=store,+ disabled_filters=disabled,+ ).text+ finally:+ store.close()+ except Exception:+ # The wrapped command already ran; never let distillation lose it.+ return output+++def _load_distill_config(+ repo_root: Path | None,+) -> tuple[bool, tuple[str, ...], tuple[float, float]]:+ from repowise.core.distill.config import omission_store_settings++ if repo_root is None:+ return True, (), omission_store_settings(None)+ from repowise.core.repo_config import load_repo_config++ cfg = load_repo_config(repo_root).get("distill") or {}+ if not isinstance(cfg, dict):+ return True, (), omission_store_settings(None)+ enabled = bool(cfg.get("enabled", True))+ commands_cfg = cfg.get("commands") or {}+ raw_disabled = commands_cfg.get("disabled_filters") if isinstance(commands_cfg, dict) else None+ disabled = tuple(str(name) for name in raw_disabled) if isinstance(raw_disabled, list) else ()+ return enabled, disabled, omission_store_settings(cfg)+++def _echo_safely(text: str) -> None:+ """Echo *text* without dying on non-UTF-8 consoles (Windows cp1252)."""+ try:+ click.echo(text)+ except UnicodeEncodeError:+ sys.stdout.buffer.write(text.encode("utf-8", errors="replace") + b"\n")diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.pyindex 940844013..ce5a9779d 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py@@ -2,18 +2,18 @@from __future__ import annotations+import contextlib+from pathlib import Path as _DoctorPath+import clickfrom rich.table import Table-from pathlib import Path as _DoctorPath-from repowise.cli.helpers import (console,get_db_url_for_repo,get_repowise_dir,load_state,resolve_command_target,- resolve_repo_path,run_async,)@@ -57,10 +57,7 @@ def _print_cli_version_status() -> None:)else:status = "[green]OK[/green]"- detail = (- f"current {check.current_version} (latest), "- f"path {path_detail}, running {running}"- )+ detail = f"current {check.current_version} (latest), path {path_detail}, running {running}"table = Table(show_header=False, box=None, pad_edge=False)table.add_column(style="cyan")@@ -71,9 +68,7 @@ def _print_cli_version_status() -> None:if check.update_available:console.print(f" [yellow]Update available:[/yellow] {check.suggested_command}")- console.print(- " [dim]Restart Claude/Codex/Cursor or any MCP client after updating.[/dim]"- )+ console.print(" [dim]Restart Claude/Codex/Cursor or any MCP client after updating.[/dim]")def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:@@ -287,7 +282,6 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:coord_drift: float | None = Nonecoord_sql_pages: int | None = Nonecoord_vector_count: int | None = None- coord_graph_nodes: int | None = Noneif db_ok:try:@@ -321,17 +315,14 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:result = await coord.health_check()if vector_store is not None:- try:+ with contextlib.suppress(Exception):await vector_store.close()- except Exception:- passawait engine.dispose()return resultcoord_result = run_async(_check_coordinator())coord_sql_pages = coord_result.get("sql_pages")coord_vector_count = coord_result.get("vector_count")- coord_graph_nodes = coord_result.get("graph_nodes")coord_drift = coord_result.get("drift")drift_pct = f"{coord_drift * 100:.1f}%" if coord_drift is not None else "N/A"@@ -344,7 +335,11 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:else:drift_color = "red"- vec_display = str(coord_vector_count) if coord_vector_count != -1 and coord_vector_count is not None else "unknown"+ vec_display = (+ str(coord_vector_count)+ if coord_vector_count != -1 and coord_vector_count is not None+ else "unknown"+ )drift_detail = (f"SQL={coord_sql_pages}, Vector={vec_display}, "f"Drift=[{drift_color}]{drift_pct}[/{drift_color}]"@@ -354,6 +349,9 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:except Exception as exc:checks.append(_check("Coordinator drift", True, f"Could not check: {exc}"))+ # 11. Distill — config block, omission store, rewrite hook (advisory)+ checks.extend(_distill_checks(repo_path))+# Displaytable = Table(title=f"repowise Doctor — {repo_path.name}")table.add_column("Check", style="cyan")@@ -461,6 +459,74 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:return all_ok+def _distill_checks(repo_path: _DoctorPath) -> list[tuple[str, str, str]]:+ """Distill feature health: config validity, store sizing, rewrite hook.++ The rewrite hook is opt-in, so its absence is informational, never a+ failure. Any unexpected error degrades to an advisory OK row — distill+ problems must not break doctor.+ """+ checks: list[tuple[str, str, str]] = []++ # Config block valid?+ distill_cfg = None+ try:+ from repowise.core.repo_config import load_repo_config++ distill_cfg = load_repo_config(repo_path).get("distill")+ from repowise.core.distill.config import validate_distill_config++ problems = validate_distill_config(distill_cfg)+ if problems:+ checks.append(_check("Distill config", False, "; ".join(problems)))+ else:+ checks.append(+ _check("Distill config", True, "valid" if distill_cfg else "defaults (no block)")+ )+ except Exception as exc:+ checks.append(_check("Distill config", True, f"Could not check: {exc}"))++ # Omission store sizing (TTL + cap are pruned opportunistically on write,+ # so a store far past its cap means pruning is not keeping up).+ try:+ from repowise.core.distill.config import omission_store_settings++ _ttl_days, max_mb = omission_store_settings(distill_cfg)+ db_path = repo_path / ".repowise" / "omissions" / "omissions.db"+ if not db_path.is_file():+ checks.append(_check("Omission store", True, "not created yet"))+ else:+ size_bytes = db_path.stat().st_size+ wal = db_path.with_name(db_path.name + "-wal")+ if wal.is_file():+ size_bytes += wal.stat().st_size+ size_mb = size_bytes / (1024 * 1024)+ ok = size_mb <= max_mb * 1.5 # WAL slack before checkpointing+ detail = f"{size_mb:.1f} MB (cap {max_mb:g} MB)"+ if not ok:+ detail += " — over cap; pruning happens on the next distill write"+ checks.append(_check("Omission store", ok, detail))+ except Exception as exc:+ checks.append(_check("Omission store", True, f"Could not check: {exc}"))++ # Rewrite hook (advisory: strictly opt-in).+ try:+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ installed = ClaudeCodeAdapter().rewrite_hook_installed()+ if installed:+ commands_cfg = distill_cfg.get("commands") if isinstance(distill_cfg, dict) else None+ opted_out = isinstance(commands_cfg, dict) and commands_cfg.get("enabled") is False+ detail = "installed (this repo opted out)" if opted_out else "installed"+ else:+ detail = "not installed (opt-in: repowise hook rewrite install)"+ checks.append(_check("Distill rewrite hook", True, detail))+ except Exception as exc:+ checks.append(_check("Distill rewrite hook", True, f"Could not check: {exc}"))++ return checks++@click.command("doctor")@click.argument("path", required=False, default=None)@click.option("--repair", is_flag=True, default=False, help="Attempt to fix detected mismatches.")@@ -526,19 +592,19 @@ def doctor_command(console.print(f"[bold]── {entry.alias}[/bold] "f"[dim]({entry.path})[/dim]"- + (" [bold cyan](primary)[/bold cyan]" if entry.alias == ws_config.default_repo else "")+ + (+ " [bold cyan](primary)[/bold cyan]"+ if entry.alias == ws_config.default_repo+ else ""+ ))ok = _run_repo_checks(abs_path, repair)overall_ok = overall_ok and okconsole.print()if not_indexed:- console.print(- f"[yellow]Not indexed:[/yellow] {', '.join(not_indexed)}"- )- console.print(- " Run [bold]repowise update --workspace[/bold] to index them."- )+ console.print(f"[yellow]Not indexed:[/yellow] {', '.join(not_indexed)}")+ console.print(" Run [bold]repowise update --workspace[/bold] to index them.")if ws_issues and not repair:console.print(f"[yellow]{len(ws_issues)} workspace-level issue(s); "@@ -596,24 +662,31 @@ def _run_workspace_checks(disk_commit = read_state_commit(abs_path)cfg_commit = entry.last_commit_at_indexif disk_commit and cfg_commit and disk_commit != cfg_commit:- rows.append((- entry.alias,- "[yellow]DRIFT[/yellow]",- f"config={cfg_commit[:8]}, state.json={disk_commit[:8]}",- ))+ rows.append(+ (+ entry.alias,+ "[yellow]DRIFT[/yellow]",+ f"config={cfg_commit[:8]}, state.json={disk_commit[:8]}",+ )+ )issues.append(f"{entry.alias}: workspace config / state.json drift")elif disk_commit and not cfg_commit:- rows.append((- entry.alias,- "[yellow]DRIFT[/yellow]",- f"workspace config missing last_commit_at_index (state.json has {disk_commit[:8]})",- ))+ rows.append(+ (+ entry.alias,+ "[yellow]DRIFT[/yellow]",+ f"workspace config missing last_commit_at_index (state.json has {disk_commit[:8]})",+ )+ )issues.append(f"{entry.alias}: workspace config missing commit pointer")elif (abs_path / ".repowise").is_dir() and not disk_commit:- rows.append((- entry.alias, "[yellow]WARN[/yellow]",- "state.json missing or empty (run `repowise update`)",- ))+ rows.append(+ (+ entry.alias,+ "[yellow]WARN[/yellow]",+ "state.json missing or empty (run `repowise update`)",+ )+ )issues.append(f"{entry.alias}: missing state.json")else:rows.append((entry.alias, "[green]OK[/green]", entry.path))@@ -634,13 +707,11 @@ def _run_workspace_checks(changed = sync_workspace_state_from_disk(ws_root, ws_config)if changed:console.print(- f"[green]Repaired workspace config from disk for:[/green] "- f"{', '.join(changed)}"+ f"[green]Repaired workspace config from disk for:[/green] {', '.join(changed)}")if dead_entries:console.print(- f"[yellow]Removing dead workspace entries:[/yellow] "- f"{', '.join(dead_entries)}"+ f"[yellow]Removing dead workspace entries:[/yellow] {', '.join(dead_entries)}")for alias in dead_entries:ws_config.remove_repo(alias)@@ -667,11 +738,13 @@ def _check_mcp_registered(ws_root: _DoctorPath) -> None:if appdata:candidates.append(_DoctorPath(appdata) / "Claude" / "claude_desktop_config.json")home = _DoctorPath.home()- candidates.extend([- home / ".claude" / "claude_desktop_config.json",- home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",- home / ".config" / "Claude" / "claude_desktop_config.json",- ])+ candidates.extend(+ [+ home / ".claude" / "claude_desktop_config.json",+ home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",+ home / ".config" / "Claude" / "claude_desktop_config.json",+ ]+ )found_paths: list[str] = []for cfg in candidates:@@ -689,9 +762,7 @@ def _check_mcp_registered(ws_root: _DoctorPath) -> None:found_paths.append(f"{cfg.name}:{name}")if found_paths:- console.print(- f" [dim]MCP: registered ({', '.join(found_paths)})[/dim]"- )+ console.print(f" [dim]MCP: registered ({', '.join(found_paths)})[/dim]")else:console.print(" [dim]MCP: no claude_desktop_config.json entry found — run "diff --git a/packages/cli/src/repowise/cli/commands/expand_cmd.py b/packages/cli/src/repowise/cli/commands/expand_cmd.pynew file mode 100644index 000000000..4937b8e31--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/expand_cmd.py@@ -0,0 +1,81 @@+"""``repowise expand`` — restore content behind an omission marker."""++from __future__ import annotations++import sys+from pathlib import Path++import click++from repowise.cli.helpers import find_repowise_repo_root+++ "expand",+ short_help="Print the full content behind a [repowise#<ref>] omission marker.",+)[email protected]("ref")+ "--query",+ "-q",+ default=None,+ help="Return only the lines matching this regex (or substring).",+)+def expand_command(ref: str, query: str | None) -> None:+ """Restore the original output referenced by an omission marker.++ REF is the 12-hex id from a ``[repowise#<ref>: ...]`` marker emitted by+ ``repowise distill``. Looks in the current repo's store first, then the+ user-level fallback store.+ """+ from repowise.core.distill.markers import MARKER_RE, is_valid_ref+ from repowise.core.distill.store import OmissionStore++ # Accept a pasted whole marker, not just the bare ref.+ if not is_valid_ref(ref):+ match = MARKER_RE.search(ref)+ if match:+ ref = match.group("ref")+ if not is_valid_ref(ref):+ click.echo(f"Not a valid omission ref: {ref!r} (expected 12 hex chars)", err=True)+ sys.exit(2)++ for db_path in _candidate_stores():+ if not db_path.exists():+ continue+ store = OmissionStore(db_path)+ try:+ content = store.get(ref, query=query)+ finally:+ store.close()+ if content is not None:+ _echo_safely(content)+ return++ click.echo(f"No stored content for {ref} (expired, pruned, or never stored here).", err=True)+ sys.exit(1)+++def _candidate_stores() -> list[Path]:+ """Repo-local store first, then the home fallback, deduplicated."""+ paths = []+ repo_root = find_repowise_repo_root()+ if repo_root is not None:+ paths.append(default_store_path_for(repo_root))+ home_store = default_store_path_for(Path.home())+ if home_store not in paths:+ paths.append(home_store)+ return paths+++def default_store_path_for(root: Path) -> Path:+ from repowise.core.distill.store import OMISSIONS_DB_FILENAME, OMISSIONS_DIRNAME++ return root / ".repowise" / OMISSIONS_DIRNAME / OMISSIONS_DB_FILENAME+++def _echo_safely(text: str) -> None:+ try:+ click.echo(text)+ except UnicodeEncodeError:+ sys.stdout.buffer.write(text.encode("utf-8", errors="replace") + b"\n")diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.pyindex ac8f65eed..c003728f0 100644--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py@@ -1,4 +1,4 @@-"""``repowise hook`` — manage git post-commit hooks for auto-sync."""+"""``repowise hook`` — manage git post-commit hooks and agent hooks."""from __future__ import annotations@@ -6,15 +6,13 @@ import clickfrom repowise.cli.helpers import (console,- find_workspace_root,resolve_command_target,- resolve_repo_path,)@click.group("hook")def hook_group() -> None:- """Manage git hooks for automatic wiki sync."""+ """Manage git hooks for auto-sync and agent hooks for distill."""def _hook_target(@@ -98,6 +96,64 @@ def hook_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> Nonconsole.print(f"Post-commit hook: {result}")+@hook_group.group("rewrite")+def rewrite_group() -> None:+ """Manage the distill command-rewrite hook (Claude Code PreToolUse).++ When installed, noisy commands an agent runs (tests, builds, git+ status/log/diff, searches, listings) are rewritten to+ ``repowise distill <command>`` — pending your approval — so the agent+ sees a compact, errors-first rendering. Raw output stays recoverable+ via ``repowise expand <ref>``.+ """+++@rewrite_group.command("install")+def rewrite_install() -> None:+ """Install the rewrite hook into ~/.claude/settings.json."""+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ path = ClaudeCodeAdapter().install_rewrite_hook()+ if path:+ console.print(f"Rewrite hook: [green]installed[/green] ({path})")+ console.print(+ " [dim]Per-repo behavior is configured under `distill.commands` "+ "in .repowise/config.yaml (permission: ask | allow).[/dim]"+ )+ # A prior init opt-out may have gated this repo off; installing+ # explicitly re-enables it here.+ from pathlib import Path++ from repowise.cli.helpers import save_distill_commands_enabled++ cwd = Path.cwd()+ if (cwd / ".repowise").is_dir():+ save_distill_commands_enabled(cwd, enabled=True)+ else:+ console.print("Rewrite hook: [red]install failed[/red]")+++@rewrite_group.command("uninstall")+def rewrite_uninstall() -> None:+ """Remove the rewrite hook from ~/.claude/settings.json."""+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ removed = ClaudeCodeAdapter().uninstall_rewrite_hook()+ console.print(f"Rewrite hook: {'[green]removed[/green]' if removed else 'not installed'}")+++@rewrite_group.command("status")+def rewrite_status() -> None:+ """Check whether the rewrite hook is installed."""+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ installed = ClaudeCodeAdapter().rewrite_hook_installed()+ icon = "[green]✓[/green]" if installed else "[dim]✗[/dim]"+ console.print(+ f" {icon} claude-code rewrite hook: {'installed' if installed else 'not installed'}"+ )++@hook_group.command("status")@click.argument("path", required=False, default=None)@click.option(diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.pyindex e453ea57c..eb0f06c05 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py@@ -9,6 +9,63 @@ from typing import Anyimport click+def offer_distill_rewrite_hook(+ console_obj: Any,+ repo_path: Path,+ flag: bool | None,+) -> None:+ """Opt-in install of the distill command-rewrite hook (Claude Code).++ ``flag`` is the resolved ``--distill-hook/--no-distill-hook`` value:+ True installs without prompting, False skips AND gates this repo off in+ config (so a hook installed globally from another repo stays inert+ here), None prompts when interactive and does nothing otherwise —+ strictly opt-in.+ """+ import os++ if os.environ.get("REPOWISE_SKIP_EDITOR_SETUP", "").strip().lower() not in (+ "",+ "0",+ "false",+ "no",+ ):+ return+ if flag is None and not sys.stdin.isatty():+ return++ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter+ from repowise.cli.helpers import save_distill_commands_enabled as _save_distill_enabled++ adapter = ClaudeCodeAdapter()+ if flag is None:+ if not adapter.detect():+ return+ console_obj.print()+ console_obj.print(+ "[bold]Distill:[/bold] rewrite noisy agent commands (tests, builds, "+ "git, searches) to `repowise distill ...` for compact output?"+ )+ console_obj.print(+ " [dim]Each rewrite is shown for approval; raw output stays "+ "recoverable via `repowise expand`.[/dim]"+ )+ flag = click.confirm(" Install the Claude Code rewrite hook?", default=False)++ if flag:+ path = adapter.install_rewrite_hook()+ if path:+ console_obj.print(f" [green]✓[/green] Rewrite hook installed ({path})")+ else:+ console_obj.print(" [yellow]Rewrite hook install failed.[/yellow]")+ _save_distill_enabled(repo_path, enabled=True)+ else:+ console_obj.print(+ " [dim]Skipped. Run 'repowise hook rewrite install' later to set up.[/dim]"+ )+ _save_distill_enabled(repo_path, enabled=False)++def offer_hook_install(console_obj: Any,repo_paths: list[Path],diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex f33de34b2..c1e902813 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -65,7 +65,7 @@ from repowise.cli.ui import ()from repowise.core.reasoning import REASONING_MODES-from ._interactive import offer_hook_install+from ._interactive import offer_distill_rewrite_hook, offer_hook_installfrom .generation import cost_gate_declined, format_cost, run_repo_generation, select_coveragefrom .persistence import (build_resume_controller,@@ -299,6 +299,16 @@ def _run_generation_phase(default=None,help="Generate or skip project-local Codex MCP config and hooks.",)+ "--distill-hook/--no-distill-hook",+ "distill_hook",+ default=None,+ help=(+ "Install the Claude Code command-rewrite hook that routes noisy "+ "commands (tests, builds, git, searches) through `repowise distill` "+ "for compact output. Default: ask when interactive; skip otherwise."+ ),+)@click.option("--include-submodules",is_flag=True,@@ -368,6 +378,7 @@ def init_command(no_claude_md: bool,agents_md: bool | None,codex_setup: bool | None,+ distill_hook: bool | None,include_submodules: bool,init_all: bool,onboarding: bool,@@ -838,3 +849,7 @@ def init_command(# Offer to install post-commit hook (both index-only and full modes)offer_hook_install(console, [repo_path])++ # Opt-in distill command-rewrite hook for Claude Code (single-repo only;+ # workspace repos can enable it later via `repowise hook rewrite install`).+ offer_distill_rewrite_hook(console, repo_path, distill_hook)diff --git a/packages/cli/src/repowise/cli/commands/saved_cmd.py b/packages/cli/src/repowise/cli/commands/saved_cmd.pynew file mode 100644index 000000000..833b71c71--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/saved_cmd.py@@ -0,0 +1,153 @@+"""``repowise saved`` — report tokens saved by output distillation.++Reads the savings ledger in the omissions sidecar+(``.repowise/omissions/omissions.db``). The ledger covers the+``repowise distill`` path only — both direct invocations and hook rewrites.+MCP response truncation is deliberately not recorded: those responses were+always budget-capped, so nothing was "saved" relative to before.++Named ``saved`` rather than ``distill --stats`` because ``repowise distill``+captures everything after it as the command to run (``ignore_unknown_options``)+— a ``--stats`` flag there would be indistinguishable from a command named+``--stats``.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import click+from rich.table import Table++from repowise.cli.helpers import console++#: Pricing model used for the dollar estimate. Saved tokens are input-side+#: tokens the coding agent never had to read, so the input rate applies.+DEFAULT_PRICING_MODEL = "claude-sonnet-4-6"++[email protected]("saved")[email protected]("path", required=False, default=None)+ "--by",+ "group_by",+ type=click.Choice(["filter", "day", "source"]),+ default="filter",+ show_default=True,+ help="Group savings by filter, day, or source surface.",+)+ "--since",+ default=None,+ metavar="DATE",+ help="Only count savings since this date (ISO format, e.g. 2026-01-01).",+)+ "--model",+ "pricing_model",+ default=DEFAULT_PRICING_MODEL,+ show_default=True,+ metavar="MODEL",+ help="Pricing model for the dollar estimate (input-token rate).",+)+def saved_command(+ path: str | None,+ group_by: str,+ since: str | None,+ pricing_model: str,+) -> None:+ """Show tokens (and estimated dollars) saved by ``repowise distill``.++ PATH defaults to the current directory; the report covers that repo's+ omission store (or the user-level fallback store when the repo has no+ ``.repowise/``). Covers the distill command/hook path only — MCP response+ truncation is not part of this ledger.+ """+ from repowise.core.distill.store import OmissionStore, default_store_path++ since_ts = _parse_since(since)++ start = Path(path).resolve() if path else Path.cwd()+ db_path = default_store_path(start)+ if not db_path.exists():+ console.print(+ "[yellow]No savings recorded yet.[/yellow] Run commands through "+ "'repowise distill <cmd>' (or install the rewrite hook with "+ "'repowise hook rewrite install') to start saving tokens."+ )+ return++ store = OmissionStore(db_path)+ try:+ summary = store.savings_summary(since=since_ts)+ rows = store.savings_rollup(by=group_by, since=since_ts)+ finally:+ store.close()++ if summary["events"] == 0:+ msg = "No distillation events recorded"+ if since_ts is not None:+ msg += f" since {since}"+ console.print(f"[yellow]{msg}.[/yellow]")+ return++ saved = summary["saved_tokens"]+ pct = 100.0 * saved / summary["raw_tokens"] if summary["raw_tokens"] else 0.0+ usd, rate = _estimate_usd(saved, pricing_model)++ table = Table(+ title=f"Distill savings - grouped by {group_by}",+ border_style="dim",+ show_footer=True,+ caption=(+ "Covers the 'repowise distill' command/hook path only; "+ "MCP response truncation is not counted."+ ),+ )+ table.add_column(group_by.capitalize(), style="cyan", footer="[bold]TOTAL[/bold]")+ table.add_column("Events", justify="right", footer=str(summary["events"]))+ table.add_column("Raw Tokens", justify="right", footer=f"{summary['raw_tokens']:,}")+ table.add_column("Distilled Tokens", justify="right", footer=f"{summary['distilled_tokens']:,}")+ table.add_column(+ "Saved Tokens",+ justify="right",+ footer=f"[bold green]{saved:,} ({pct:.0f}%)[/bold green]",+ )+ for row in rows:+ row_pct = 100.0 * row["saved_tokens"] / row["raw_tokens"] if row["raw_tokens"] else 0.0+ table.add_row(+ str(row["group"] or "-"),+ str(row["events"]),+ f"{row['raw_tokens']:,}",+ f"{row['distilled_tokens']:,}",+ f"[green]{row['saved_tokens']:,} ({row_pct:.0f}%)[/green]",+ )++ console.print()+ console.print(table)+ console.print(+ f" Estimated saved: [bold green]${usd:.4f}[/bold green] "+ f"[dim](at ${rate:.2f}/M input tokens, {pricing_model}; "+ f"tokens are chars/4 estimates)[/dim]"+ )+ console.print(f" [dim]Ledger: {db_path}[/dim]")+ console.print()+++def _parse_since(value: str | None) -> float | None:+ """ISO date string -> Unix timestamp, or None."""+ if value is None:+ return None+ try:+ return datetime.fromisoformat(value).timestamp()+ except ValueError as exc:+ raise click.BadParameter(f"Cannot parse date '{value}': {exc}") from exc+++def _estimate_usd(saved_tokens: int, model: str) -> tuple[float, float]:+ """Dollar estimate for *saved_tokens* at *model*'s input rate."""+ from repowise.core.generation.cost_tracker import get_model_pricing++ rate = get_model_pricing(model)["input"]+ return saved_tokens * rate / 1_000_000, ratediff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.pyindex 12efc15ad..c88b1434f 100644--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py@@ -90,16 +90,23 @@ def register_with_claude_code(repo_path: Path) -> Path | None:return settings_path if merge_mcp_entry(settings_path, entry) else None+# Current augment PostToolUse matcher. Read/Edit/Write power the distill+# read-intelligence layer (skeleton nudges + per-file stale-read notices);+# legacy installs with the narrower matchers below are widened in place.+_AUGMENT_MATCHER = "Bash|Grep|Glob|Read|Edit|Write"+_LEGACY_AUGMENT_MATCHERS = ("Bash", "Bash|Grep|Glob")++def install_claude_code_hooks() -> Path | None:"""Register PostToolUse hooks in ~/.claude/settings.json.- PostToolUse detects git staleness and can enrich Grep/Glob results when- the hook output has useful extra context. Existing user hooks are preserved.+ PostToolUse detects git staleness, enriches Grep/Glob results, and emits+ Read-intelligence notices. Existing user hooks are preserved."""settings_path = _claude_code_settings_path()post_hook_entry = {- "matcher": "Bash|Grep|Glob",+ "matcher": _AUGMENT_MATCHER,"hooks": [{"type": "command",@@ -119,8 +126,10 @@ def install_claude_code_hooks() -> Path | None:hooks = existing.setdefault("hooks", {})- # Drop any pre-existing repowise PreToolUse entry; the current design- # routes everything through PostToolUse.+ # Drop any pre-existing legacy *augment* PreToolUse entry; augment+ # routes everything through PostToolUse. The distill rewrite hook+ # (`repowise-rewrite`) is a separate, opt-in PreToolUse entry managed+ # by install/uninstall_claude_code_rewrite_hook and must be preserved.pre_hooks = hooks.setdefault("PreToolUse", [])_strip_repowise_pretool(pre_hooks)if not pre_hooks:@@ -138,6 +147,113 @@ def install_claude_code_hooks() -> Path | None:return None+_REWRITE_HOOK_COMMAND = "repowise-rewrite"+++def install_claude_code_rewrite_hook() -> Path | None:+ """Register the opt-in distill PreToolUse rewrite hook (Bash matcher).++ Idempotent; preserves user hooks and the augment PostToolUse entry.+ Returns the settings path on success, None on failure.+ """+ settings_path = _claude_code_settings_path()+ pre_hook_entry = {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": _REWRITE_HOOK_COMMAND,+ "timeout": 5,+ "statusMessage": "Distilling command output...",+ }+ ],+ }++ try:+ if settings_path.exists():+ existing = load_existing_config(settings_path)+ else:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ existing = {}++ hooks = existing.setdefault("hooks", {})+ pre_hooks = hooks.setdefault("PreToolUse", [])+ if not _has_rewrite_hook(pre_hooks):+ pre_hooks.append(pre_hook_entry)+ settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")+ return settings_path+ except OSError:+ return None+++def uninstall_claude_code_rewrite_hook() -> bool:+ """Remove the distill rewrite hook; True when something was removed."""+ settings_path = _claude_code_settings_path()+ if not settings_path.exists():+ return False+ try:+ existing = load_existing_config(settings_path)+ except Exception:+ return False++ hooks = existing.get("hooks")+ if not isinstance(hooks, dict):+ return False+ pre_hooks = hooks.get("PreToolUse")+ if not isinstance(pre_hooks, list):+ return False++ changed = _strip_hooks(pre_hooks, _is_rewrite_hook)+ if not changed:+ return False+ if not pre_hooks:+ hooks.pop("PreToolUse", None)++ try:+ settings_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")+ except OSError:+ return False+ return True+++def claude_code_rewrite_hook_installed() -> bool:+ """True when the distill rewrite hook is registered in settings.json."""+ settings_path = _claude_code_settings_path()+ if not settings_path.exists():+ return False+ try:+ existing = load_existing_config(settings_path)+ except Exception:+ return False+ hooks = existing.get("hooks")+ if not isinstance(hooks, dict):+ return False+ pre_hooks = hooks.get("PreToolUse")+ return isinstance(pre_hooks, list) and _has_rewrite_hook(pre_hooks)+++def _is_rewrite_hook(hook: dict) -> bool:+ return _REWRITE_HOOK_COMMAND in hook.get("command", "")+++def _has_rewrite_hook(hook_list: list) -> bool:+ return any(_is_rewrite_hook(h) for entry in hook_list for h in entry.get("hooks", []))+++def _strip_hooks(hook_list: list, predicate) -> bool:+ """Remove hooks matching *predicate* from a hook bucket in place."""+ changed = False+ for entry in list(hook_list):+ kept = [h for h in entry.get("hooks", []) if not predicate(h)]+ if len(kept) != len(entry.get("hooks", [])):+ changed = True+ if kept:+ entry["hooks"] = kept+ else:+ hook_list.remove(entry)+ return changed++def _has_repowise_hook(hook_list: list) -> bool:"""Check if a repowise hook is already registered, current or legacy."""for entry in hook_list:@@ -154,17 +270,12 @@ def _is_repowise_hook(hook: dict) -> bool:def _strip_repowise_pretool(hook_list: list) -> bool:- """Remove repowise's PreToolUse entry from a hook bucket in place."""- changed = False- for entry in list(hook_list):- kept = [h for h in entry.get("hooks", []) if not _is_repowise_hook(h)]- if len(kept) != len(entry.get("hooks", [])):- changed = True- if kept:- entry["hooks"] = kept- else:- hook_list.remove(entry)- return changed+ """Remove legacy *augment* PreToolUse entries from a hook bucket in place.++ Matches only the augment command names — the opt-in ``repowise-rewrite``+ PreToolUse hook is intentionally untouched.+ """+ return _strip_hooks(hook_list, _is_repowise_hook)def _migrate_legacy_hook(hook_list: list) -> bool:@@ -178,8 +289,8 @@ def _migrate_legacy_hook(hook_list: list) -> bool:changed = Truematcher = entry.get("matcher", "")only_repowise = entry.get("hooks") and all(_is_repowise_hook(h) for h in entry["hooks"])- if only_repowise and matcher == "Bash":- entry["matcher"] = "Bash|Grep|Glob"+ if only_repowise and matcher in _LEGACY_AUGMENT_MATCHERS:+ entry["matcher"] = _AUGMENT_MATCHERchanged = Truereturn changeddiff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex e99ef8ac5..4356aff62 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -550,6 +550,21 @@ def save_config_partial()+def save_distill_commands_enabled(repo_path: Path, *, enabled: bool) -> None:+ """Deep-merge ``distill.commands.enabled`` into ``.repowise/config.yaml``.++ :func:`save_config_partial` merges shallowly at the top level, so the+ ``distill`` block is merged here first to avoid clobbering sibling keys+ like ``disabled_filters``.+ """+ cfg = load_config(repo_path)+ distill = dict(cfg.get("distill") or {})+ commands = dict(distill.get("commands") or {})+ commands["enabled"] = enabled+ distill["commands"] = commands+ save_config_partial(repo_path, distill=distill)++def config_fingerprint(repo_path: Path) -> str:"""SHA-256 hex of ``.repowise/config.yaml`` + ``health-rules.json`` content.diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 5392cf306..cd60db17a 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -11,7 +11,9 @@ from repowise.cli.commands.costs_cmd import costs_commandfrom repowise.cli.commands.dead_code_cmd import dead_code_commandfrom repowise.cli.commands.decision_cmd import decision_groupfrom repowise.cli.commands.delete_cmd import delete_command+from repowise.cli.commands.distill_cmd import distill_commandfrom repowise.cli.commands.doctor_cmd import doctor_command+from repowise.cli.commands.expand_cmd import expand_commandfrom repowise.cli.commands.export_cmd import export_commandfrom repowise.cli.commands.health_cmd import health_commandfrom repowise.cli.commands.hook_cmd import hook_group@@ -19,6 +21,7 @@ from repowise.cli.commands.init_cmd import init_commandfrom repowise.cli.commands.mcp_cmd import mcp_commandfrom repowise.cli.commands.reindex_cmd import reindex_commandfrom repowise.cli.commands.risk_cmd import risk_command+from repowise.cli.commands.saved_cmd import saved_commandfrom repowise.cli.commands.search_cmd import search_commandfrom repowise.cli.commands.serve_cmd import serve_commandfrom repowise.cli.commands.status_cmd import status_command@@ -61,6 +64,9 @@ register_command(health_command)register_command(risk_command)register_command(decision_group)register_command(search_command)+register_command(distill_command)+register_command(expand_command)+register_command(saved_command)register_command(export_command)register_command(hook_group)register_command(status_command)diff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.pynew file mode 100644index 000000000..017617475--- /dev/null+++ b/packages/cli/src/repowise/cli/rewrite_hook.py@@ -0,0 +1,305 @@+"""Standalone entry point for the ``repowise-rewrite`` PreToolUse hook.++Fires before every shell command an AI agent runs and decides whether to+rewrite it to ``repowise distill <command>`` so the agent sees a compact,+errors-first rendering instead of the raw flood. The hook only *proposes*+the rewrite — the default permission posture is ``ask``, so the user+approves the modified command unless they opted into auto-allow per+command family in ``.repowise/config.yaml``.++Hot-path discipline (this fires on EVERY Bash tool call):++ - Module scope imports nothing beyond the stdlib; the adapter modules it+ pulls in are stdlib-only too. No click, no repowise.core, no DB.+ - Classification is a static regex table plus an ignore-list — the+ expensive routing (content sniffing, store writes) happens later inside+ ``repowise distill``, whose latency hides behind the wrapped command.+ - Any failure, any unrecognized payload, any ambiguity → exit 0 with no+ output, which the agent treats as "run the command unchanged".++Bailouts — commands never rewritten:++ - pipes / redirections / compound commands (``| > < && || ; &``),+ substitution (backticks, ``$(``), multi-line commands: the wrapper+ would change shell semantics;+ - watch/follow modes (``--watch``, ``tail -f``): long-running,+ interactive by design;+ - the ignore-list of trivial or interactive commands (cd, echo, vim, …);+ - anything already invoking ``repowise``.+"""++from __future__ import annotations++import os.path+import re+import sys++# Stdlib-only module by design (see hot-path discipline above) — safe to+# import at module scope. (No pathlib: it costs double-digit milliseconds+# of interpreter startup, which this hook pays on every Bash call.)+from repowise.cli.agent_adapters.base import RewriteResult++# ---------------------------------------------------------------------------+# Command normalization — a hot-path mirror of+# ``repowise.core.distill.router.normalize_command``. Duplicated on purpose:+# importing the core router would pull the package __init__ (structlog, the+# engine) into every Bash call. ``test_rewrite_hook.py`` asserts the two stay+# behaviorally identical over a command table; update both together.+# ---------------------------------------------------------------------------++_WRAPPER_RE = re.compile(+ r"^(?:"+ r"uv run|uvx|npx|pnpm exec|pnpm dlx|yarn dlx|poetry run|pipenv run|hatch run|"+ r"python3? -m|py -m"+ r")\s+",+ re.IGNORECASE,+)+_ENV_ASSIGN_RE = re.compile(r"^\w+=\S+\s+")+_EXE_PATH_RE = re.compile(r'^(?:"[^"]*[\\/]|\S*[\\/])(?P<exe>[\w.-]+?)(?:\.exe)?(?:")?(?=\s|$)')+++def _normalize(command: str) -> str:+ cmd = command.strip()+ for _ in range(4):+ previous = cmd+ cmd = _ENV_ASSIGN_RE.sub("", cmd)+ cmd = _WRAPPER_RE.sub("", cmd)+ if cmd == previous:+ break+ cmd = _EXE_PATH_RE.sub(lambda m: m.group("exe"), cmd)+ return cmd.lower()+++# ---------------------------------------------------------------------------+# Classification table. Family names MUST match the registered filter names+# in ``repowise.core.distill`` — the per-family permission config keys off+# them, and ``repowise distill`` routes by the same families.+# ---------------------------------------------------------------------------++FAMILY_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (+ (+ "test_output",+ re.compile(+ r"^(pytest\b|py\.test\b|jest\b|vitest\b|cargo (?:test|nextest)\b|"+ r"go test\b|npm (?:test|run test)\b|pnpm (?:test|run test)\b|"+ r"yarn (?:test|run test)\b)"+ ),+ ),+ (+ "build_output",+ re.compile(+ r"^(npm run b|npm run-script b|pnpm (?:run )?b|yarn (?:run )?b|"+ r"tsc\b|cargo (?:build|check|clippy)\b|go (?:build|vet)\b|"+ r"make\b|vite build|webpack\b|next build|dotnet build\b|"+ r"npm run (?:type-check|typecheck|lint|compile)\b|gradle|mvn\b)"+ ),+ ),+ ("git_status", re.compile(r"^git status\b(?!.*--porcelain)")),+ ("git_log", re.compile(r"^git log\b")),+ ("git_diff", re.compile(r"^git (?:diff|show)\b(?!.*--stat)")),+ ("search_results", re.compile(r"^(rg\b|grep\b|egrep\b|fgrep\b|git grep\b)")),+ ("file_listing", re.compile(r"^(ls\b|tree\b|find\b|fd\b|git ls-files\b)")),+ ("logs", re.compile(r"^(tail\b|journalctl\b|docker logs\b|kubectl logs\b|cat\b.*\.log\b)")),+)++#: First tokens that are never worth wrapping: trivial, mutating, or+#: interactive. Checked before the regex table as a fast bail.+IGNORED_FIRST_TOKENS = frozenset(+ {+ # trivial / mutating+ "cd",+ "echo",+ "printf",+ "mkdir",+ "rmdir",+ "rm",+ "mv",+ "cp",+ "touch",+ "pwd",+ "which",+ "where",+ "whoami",+ "hostname",+ "date",+ "env",+ "set",+ "export",+ "unset",+ "source",+ "alias",+ "exit",+ "true",+ "false",+ "sleep",+ "kill",+ "chmod",+ "chown",+ "ln",+ "test",+ # interactive / fullscreen+ "vim",+ "vi",+ "nvim",+ "nano",+ "emacs",+ "less",+ "more",+ "top",+ "htop",+ "ssh",+ "man",+ "watch",+ "python",+ "python3",+ "node",+ "irb",+ }+)++# Shell syntax that changes meaning if the command is wrapped: pipes,+# redirections, chaining, backgrounding, substitution, heredocs, newlines.+_SHELL_SYNTAX_RE = re.compile(r"[|&;<>`\n]|\$\(")++# Watch/follow modes are long-running; wrapping them buffers forever.+_WATCH_RE = re.compile(r"--watch(?:all)?\b|--looponfail\b|(?:^|\s)-f\b.*\.log\b|--follow\b")+++def classify(command: str) -> str | None:+ """Return the distill family for *command*, or None to pass through."""+ if not command or _SHELL_SYNTAX_RE.search(command):+ return None+ normalized = _normalize(command)+ if not normalized or normalized.startswith("repowise"):+ return None+ first = normalized.split(None, 1)[0]+ if first in IGNORED_FIRST_TOKENS:+ return None+ if _WATCH_RE.search(normalized):+ return None+ for family, pattern in FAMILY_PATTERNS:+ if pattern.match(normalized):+ return family+ return None+++# ---------------------------------------------------------------------------+# Per-repo config — ``distill.commands`` block in .repowise/config.yaml+# ---------------------------------------------------------------------------++_VALID_PERMISSIONS = ("ask", "allow")+_OFF_VALUES = ("off", "deny", "disable", "disabled", "none", False)+++def _find_repo_root(cwd: str) -> str | None:+ try:+ current = os.path.realpath(cwd or ".")+ home = os.path.realpath(os.path.expanduser("~"))+ except OSError:+ return None+ for _ in range(20):+ # ~/.repowise is the *user-level* config dir, not a repo opt-in —+ # without this guard every directory under $HOME would classify as+ # a repowise repo and get its commands rewritten.+ if current != home and os.path.isdir(os.path.join(current, ".repowise")):+ return current+ parent = os.path.dirname(current)+ if parent == current:+ break+ current = parent+ return None+++def _load_commands_config(repo_root: str) -> tuple[bool, str, dict]:+ """Return (enabled, default_permission, per-family overrides).++ Missing file, missing yaml, malformed yaml → permissive defaults with+ ``ask`` (the hook is only installed for users who opted in).+ """+ enabled, permission, families = True, "ask", {}+ config_path = os.path.join(repo_root, ".repowise", "config.yaml")+ try:+ with open(config_path, encoding="utf-8") as fh:+ text = fh.read()+ except OSError:+ return enabled, permission, families+ try:+ import yaml # type: ignore[import-untyped]++ data = yaml.safe_load(text) or {}+ except Exception:+ return enabled, permission, families+ if not isinstance(data, dict):+ return enabled, permission, families+ distill = data.get("distill")+ if not isinstance(distill, dict):+ return enabled, permission, families+ if distill.get("enabled") is False:+ enabled = False+ commands = distill.get("commands")+ if isinstance(commands, dict):+ if commands.get("enabled") is False:+ enabled = False+ raw_permission = commands.get("permission")+ if raw_permission in _OFF_VALUES:+ enabled = False+ elif raw_permission in _VALID_PERMISSIONS:+ permission = raw_permission+ raw_families = commands.get("families")+ if isinstance(raw_families, dict):+ families = raw_families+ return enabled, permission, families+++def decide(command: str, cwd: str) -> RewriteResult | None:+ """Full decision: classification + bailouts + per-repo permission config."""+ family = classify(command)+ if family is None:+ return None++ # Only act inside repos that opted into repowise; the hook is installed+ # globally, but a repo without .repowise/ gets untouched commands.+ repo_root = _find_repo_root(cwd)+ if repo_root is None:+ return None++ enabled, permission, families = _load_commands_config(repo_root)+ if not enabled:+ return None+ family_setting = families.get(family)+ if family_setting in _OFF_VALUES:+ return None+ if family_setting in _VALID_PERMISSIONS:+ permission = family_setting++ return RewriteResult(+ command=f"repowise distill {command.strip()}",+ permission=permission,+ reason=(+ f"repowise distill: compact {family} rendering; full output stays "+ f"recoverable via `repowise expand <ref>`"+ ),+ )+++def main() -> None:+ try:+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ adapter = ClaudeCodeAdapter()+ request = adapter.parse_hook_payload(sys.stdin.read())+ if request is not None:+ result = decide(request.command, request.cwd)+ if result is not None:+ sys.stdout.write(adapter.render_response(result))+ sys.stdout.flush()+ except (SystemExit, KeyboardInterrupt):+ raise+ except BaseException:+ # A hook failure must never surface in the agent transcript.+ pass+ sys.exit(0)+++if __name__ == "__main__":+ main()diff --git a/packages/core/src/repowise/core/distill/__init__.py b/packages/core/src/repowise/core/distill/__init__.pynew file mode 100644index 000000000..75fae76b1--- /dev/null+++ b/packages/core/src/repowise/core/distill/__init__.py@@ -0,0 +1,148 @@+"""Distill — index-aware compaction of noisy command output.++The engine orchestrates the pure pieces (router -> filter) around the+stateful ones (omission store, savings ledger) and owns the safety+guarantees the filters rely on:++- **fallback-to-raw**: any filter exception, storage failure, or+ non-improvement returns the original output untouched;+- **reversibility**: the full raw output is persisted before a marker is+ emitted, so ``repowise expand <ref>`` always round-trips;+- **net-positive only**: distilled text (marker included) must actually be+ smaller than the raw output, with a small floor so trivial wins don't+ litter markers everywhere.+"""++from __future__ import annotations++import contextlib+from dataclasses import dataclass+from pathlib import Path++import structlog++from repowise.core.distill.budget import estimate_tokens, savings_pct+from repowise.core.distill.markers import parse_marker_refs, render_marker+from repowise.core.distill.registry import filter_registry+from repowise.core.distill.router import normalize_command, select_filter+from repowise.core.distill.store import OmissionStore++__all__ = [+ "DistillResult",+ "OmissionStore",+ "distill_output",+ "estimate_tokens",+ "filter_registry",+ "normalize_command",+ "parse_marker_refs",+ "render_marker",+ "savings_pct",+ "select_filter",+]++logger = structlog.get_logger(__name__)++#: Distillation must save at least this many tokens to be worth a marker.+MIN_SAVED_TOKENS = 40+++@dataclass(frozen=True)+class DistillResult:+ """Outcome of one distillation attempt."""++ text: str+ distilled: bool+ filter_name: str | None+ ref: str | None+ raw_tokens: int+ distilled_tokens: int++ @property+ def savings_pct(self) -> float:+ return savings_pct(self.raw_tokens, self.distilled_tokens)+++def distill_output(+ output: str,+ *,+ command: str = "",+ exit_code: int = 0,+ source: str = "cli",+ store: OmissionStore | None = None,+ store_start: Path | None = None,+ disabled_filters: tuple[str, ...] = (),+) -> DistillResult:+ """Distill *output*, falling back to the raw text on any failure.++ When *store* is None one is opened at the default sidecar location for+ *store_start* (default: cwd) and closed before returning.+ """+ raw_tokens = estimate_tokens(output)+ raw = DistillResult(+ text=output,+ distilled=False,+ filter_name=None,+ ref=None,+ raw_tokens=raw_tokens,+ distilled_tokens=raw_tokens,+ )++ try:+ chosen = select_filter(command, output, disabled=disabled_filters)+ except Exception:+ logger.debug("distill filter selection failed", exc_info=True)+ return raw+ if chosen is None:+ return raw+ if len(output.splitlines()) < chosen.min_lines:+ return raw++ try:+ kept = chosen.distill(output, command=command, exit_code=exit_code)+ except Exception:+ logger.debug("distill filter failed; falling back to raw", filter=chosen.name)+ return raw++ kept_tokens = estimate_tokens(kept)+ omitted_lines = max(0, len(output.splitlines()) - len(kept.splitlines()))++ owns_store = store is None+ try:+ if owns_store:+ store = OmissionStore.open_default(store_start)+ ref = store.put(+ output,+ source=f"{source}:{chosen.name}",+ original_tokens=raw_tokens,+ kept_tokens=kept_tokens,+ )+ marker = render_marker(ref, omitted_lines, max(0, raw_tokens - kept_tokens))+ text = kept.rstrip("\n") + "\n\n" + marker + "\n"+ distilled_tokens = estimate_tokens(text)+ # Net-positive guarantee, marker included.+ if distilled_tokens >= raw_tokens - MIN_SAVED_TOKENS:+ return raw+ store.record_saving(+ filter_name=chosen.name,+ source=source,+ command=command or None,+ raw_tokens=raw_tokens,+ distilled_tokens=distilled_tokens,+ )+ return DistillResult(+ text=text,+ distilled=True,+ filter_name=chosen.name,+ ref=ref,+ raw_tokens=raw_tokens,+ distilled_tokens=distilled_tokens,+ )+ except Exception:+ # Raw output is never recoverable without a successful store write,+ # so a storage failure means we must not drop anything.+ logger.debug("omission store unavailable; falling back to raw", exc_info=True)+ return raw+ finally:+ if owns_store and store is not None:+ with contextlib.suppress(Exception):+ store.close()diff --git a/packages/core/src/repowise/core/distill/budget.py b/packages/core/src/repowise/core/distill/budget.pynew file mode 100644index 000000000..41a55f344--- /dev/null+++ b/packages/core/src/repowise/core/distill/budget.py@@ -0,0 +1,18 @@+"""Token estimation for distill — thin façade over the shared heuristic.++Reuses the generation-side 4-chars-per-token estimator so every repowise+subsystem reports savings on the same scale. No tiktoken dependency.+"""++from __future__ import annotations++from repowise.core.generation.context.token_budget import estimate_tokens++__all__ = ["estimate_tokens", "savings_pct"]+++def savings_pct(raw_tokens: int, distilled_tokens: int) -> float:+ """Percentage of tokens saved by distillation (0.0 when nothing saved)."""+ if raw_tokens <= 0:+ return 0.0+ return max(0.0, (raw_tokens - distilled_tokens) / raw_tokens * 100.0)diff --git a/packages/core/src/repowise/core/distill/config.py b/packages/core/src/repowise/core/distill/config.pynew file mode 100644index 000000000..ca13ebc9f--- /dev/null+++ b/packages/core/src/repowise/core/distill/config.py@@ -0,0 +1,141 @@+"""Validation and typed access for the ``distill:`` config block.++The hot-path consumers (``repowise-rewrite``) keep their own minimal,+stdlib-only readers and tolerate anything; this module is for the surfaces+that should *complain* about a malformed block (``repowise doctor``) or need+typed store settings (``repowise distill``).+"""++from __future__ import annotations++from typing import Any++from repowise.core.distill.store import DEFAULT_MAX_MB, DEFAULT_TTL_DAYS++#: Valid values for ``distill.commands.permission``.+VALID_PERMISSIONS = ("ask", "allow", "off")+#: Valid values for a per-family override (``deny`` blocks the command).+VALID_FAMILY_PERMISSIONS = ("ask", "allow", "off", "deny")++_KNOWN_TOP_KEYS = ("enabled", "commands", "omission_store")+_KNOWN_COMMANDS_KEYS = ("enabled", "permission", "families", "disabled_filters")+_KNOWN_STORE_KEYS = ("ttl_days", "max_mb")+++def validate_distill_config(distill: Any) -> list[str]:+ """Return a list of problems with a ``distill:`` config block.++ An empty list means the block is valid (or absent). Problems are+ human-readable strings suitable for ``repowise doctor`` output. Unknown+ filter names are checked against the live filter registry.+ """+ if distill is None:+ return []+ if not isinstance(distill, dict):+ return ["distill: must be a mapping"]++ problems: list[str] = []+ for key in distill:+ if key not in _KNOWN_TOP_KEYS:+ problems.append(f"distill.{key}: unknown key")+ if "enabled" in distill and not isinstance(distill["enabled"], bool):+ problems.append("distill.enabled: must be true or false")++ commands = distill.get("commands")+ if commands is not None:+ if not isinstance(commands, dict):+ problems.append("distill.commands: must be a mapping")+ else:+ problems.extend(_validate_commands(commands))++ store = distill.get("omission_store")+ if store is not None:+ if not isinstance(store, dict):+ problems.append("distill.omission_store: must be a mapping")+ else:+ problems.extend(_validate_store(store))++ return problems+++def _validate_commands(commands: dict) -> list[str]:+ problems: list[str] = []+ for key in commands:+ if key not in _KNOWN_COMMANDS_KEYS:+ problems.append(f"distill.commands.{key}: unknown key")+ if "enabled" in commands and not isinstance(commands["enabled"], bool):+ problems.append("distill.commands.enabled: must be true or false")++ permission = commands.get("permission")+ if permission is not None and permission not in VALID_PERMISSIONS:+ problems.append(+ f"distill.commands.permission: {permission!r} is not one of {VALID_PERMISSIONS}"+ )++ known_filters = _filter_names()++ families = commands.get("families")+ if families is not None:+ if not isinstance(families, dict):+ problems.append("distill.commands.families: must be a mapping")+ else:+ for name, value in families.items():+ if name not in known_filters:+ problems.append(+ f"distill.commands.families.{name}: unknown filter "+ f"(known: {', '.join(sorted(known_filters))})"+ )+ if value not in VALID_FAMILY_PERMISSIONS:+ problems.append(+ f"distill.commands.families.{name}: {value!r} is not one of "+ f"{VALID_FAMILY_PERMISSIONS}"+ )++ disabled = commands.get("disabled_filters")+ if disabled is not None:+ if not isinstance(disabled, list):+ problems.append("distill.commands.disabled_filters: must be a list")+ else:+ for name in disabled:+ if name not in known_filters:+ problems.append(f"distill.commands.disabled_filters: unknown filter {name!r}")+ return problems+++def _validate_store(store: dict) -> list[str]:+ problems: list[str] = []+ for key in store:+ if key not in _KNOWN_STORE_KEYS:+ problems.append(f"distill.omission_store.{key}: unknown key")+ for key in _KNOWN_STORE_KEYS:+ if key in store:+ value = store[key]+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:+ problems.append(f"distill.omission_store.{key}: must be a positive number")+ return problems+++def omission_store_settings(distill: Any) -> tuple[float, float]:+ """``(ttl_days, max_mb)`` from a ``distill:`` block, defaulting safely.++ Invalid values fall back to the defaults — store sizing must never make+ distillation fail.+ """+ ttl_days: float = DEFAULT_TTL_DAYS+ max_mb: float = DEFAULT_MAX_MB+ if isinstance(distill, dict):+ store = distill.get("omission_store")+ if isinstance(store, dict):+ ttl = store.get("ttl_days")+ if isinstance(ttl, (int, float)) and not isinstance(ttl, bool) and ttl > 0:+ ttl_days = float(ttl)+ cap = store.get("max_mb")+ if isinstance(cap, (int, float)) and not isinstance(cap, bool) and cap > 0:+ max_mb = float(cap)+ return ttl_days, max_mb+++def _filter_names() -> tuple[str, ...]:+ from repowise.core.distill.registry import filter_registry++ return tuple(f.name for f in filter_registry.filters())diff --git a/packages/core/src/repowise/core/distill/filters/__init__.py b/packages/core/src/repowise/core/distill/filters/__init__.pynew file mode 100644index 000000000..b47592412--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/__init__.py@@ -0,0 +1,22 @@+"""Distill output filters.++Importing this package registers every built-in filter with the shared+``filter_registry``. Adding a filter = new module here + the decorator;+the router and engine never change.+"""++from __future__ import annotations++from repowise.core.distill.filters import ( # noqa: F401 (registration side effect)+ build_output,+ file_listing,+ git_diff,+ git_log,+ git_status,+ logs,+ search_results,+ test_output,+)+from repowise.core.distill.filters.base import ERROR_LINE_RE, OutputFilter, is_error_line++__all__ = ["ERROR_LINE_RE", "OutputFilter", "is_error_line"]diff --git a/packages/core/src/repowise/core/distill/filters/base.py b/packages/core/src/repowise/core/distill/filters/base.pynew file mode 100644index 000000000..5af8391a0--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/base.py@@ -0,0 +1,81 @@+"""Output-filter base class and shared line-classification helpers.++Filters are pure: they receive raw command output and return a compact+rendering. They never touch the omission store or markers — the engine in+``repowise.core.distill`` owns persistence, marker rendering, savings+accounting, and the fallback-to-raw guarantee.++The cardinal invariant for every filter: **no error line is ever dropped.**+``is_error_line`` is deliberately greedy — keeping a few extra lines is+cheap, losing the one line that explains a failure is not.+"""++from __future__ import annotations++import re+from abc import ABC, abstractmethod+from typing import ClassVar++# Lines that must survive every filter. Greedy on purpose.+ERROR_LINE_RE = re.compile(+ r"(?i)("+ r"\b(error|errors|failed|failure|failures|fatal|panic|panicked|exception|"+ r"traceback|assert|assertion|assertionerror|denied|refused|unreachable)\b"+ r"|error\[E\d+\]"+ r"|--- FAIL"+ r"|\bFAIL\b"+ r"|^\s*[✗✕×✘]" # jest/vitest failed-test glyphs # noqa: RUF001+ r")"+)+++def is_error_line(line: str) -> bool:+ """True when *line* carries failure information and must never be dropped."""+ return bool(ERROR_LINE_RE.search(line))+++def cap_block(lines: list[str], head: int, tail: int) -> list[str]:+ """Cap *lines* to roughly *head* + *tail*, never dropping error lines.++ Middle lines classified as errors are retained between the anchors, and an+ inline ellipsis notes how many lines were elided. Returns the input+ unchanged when it already fits.+ """+ if len(lines) <= head + tail:+ return list(lines)+ middle = lines[head : len(lines) - tail]+ kept_middle = [ln for ln in middle if is_error_line(ln)]+ elided = len(middle) - len(kept_middle)+ capped = lines[:head]+ capped.extend(kept_middle)+ if elided > 0:+ capped.append(f" ... ({elided} lines elided) ...")+ capped.extend(lines[len(lines) - tail :])+ return capped+++class OutputFilter(ABC):+ """One self-contained compaction strategy for a family of command output."""++ #: Registry name; also used as the savings-ledger / store source label.+ name: ClassVar[str]+ #: Lower runs first when several filters match (content sniffing order).+ priority: ClassVar[int] = 100+ #: Outputs shorter than this many lines are never worth distilling.+ min_lines: ClassVar[int] = 8++ def matches_command(self, command: str) -> bool:+ """True when *command* (normalized, lowercase) is in this family."""+ return False++ def matches_content(self, output: str) -> bool:+ """Content sniff for when the command string is absent or ambiguous."""+ return False++ @abstractmethod+ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ """Return the compact rendering of *output*.++ May raise on unrecognized input — the engine falls back to raw.+ Must preserve every line for which :func:`is_error_line` is true.+ """diff --git a/packages/core/src/repowise/core/distill/filters/build_output.py b/packages/core/src/repowise/core/distill/filters/build_output.pynew file mode 100644index 000000000..9f7a07fbf--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/build_output.py@@ -0,0 +1,119 @@+"""Compaction of build/compile output (npm, tsc, cargo, go, bundlers).++One line-classifying pass works across toolchains: errors and warnings are+kept verbatim (with file-location lines), progress spam collapses to verb+counts, asset/route tables are capped, and the head/tail anchors preserve+the banner and the summary. Errors-first, same as test output.+"""++from __future__ import annotations++import re+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter, is_error_line+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(+ r"^(npm(?:\.cmd)? run b|npm(?:\.cmd)? run-script b|pnpm (?:run )?b|yarn (?:run )?b|"+ r"tsc\b|cargo(?:\.exe)? (?:build|check|clippy)\b|go(?:\.exe)? (?:build|vet)\b|"+ r"make\b|vite build|webpack\b|next(?:\.cmd)? build|dotnet(?:\.exe)? build\b|"+ r"npm(?:\.cmd)? run (?:type-check|typecheck|lint|compile)\b|gradle|mvn\b)"+)++# Progress verbs collapsed to "<verb> ... (xN)".+_PROGRESS_RE = re.compile(+ r"^\s*(?P<verb>Compiling|Downloading|Downloaded|Fetching|Fetched|Installing|"+ r"Resolving|Resolved|Checking|Building|Bundling|Documenting|Generating|"+ r"Creating|transforming|rendering chunks|computing gzip size|Linting)\b"+)++# Warnings are kept (deduped); is_error_line covers errors.+_WARNING_RE = re.compile(r"(?i)\bwarn(ing)?\b")++# file(line,col) / file:line:col locations attached to diagnostics.+_LOCATION_RE = re.compile(r"^\s*\S+\.\w{1,4}[(:]\d+[,:)]")++# Asset/route table rows (bundler output): sizes, tree glyphs, pipes.+_TABLE_RE = re.compile(r"(│|├|└|┌|\|\s*$|\d+(\.\d+)?\s*(B|kB|KB|MB|kb)\b)")++_MAX_TABLE_ROWS = 10+_HEAD_ANCHOR = 4+_TAIL_ANCHOR = 12+++@filter_registry.register+class BuildOutputFilter(OutputFilter):+ name: ClassVar[str] = "build_output"+ priority: ClassVar[int] = 30+ min_lines: ClassVar[int] = 15++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command))++ def matches_content(self, output: str) -> bool:+ sample = output.splitlines()[:50]+ progress = sum(1 for ln in sample if _PROGRESS_RE.match(ln))+ return progress >= 5++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ lines = output.splitlines()+ n = len(lines)+ head_end = min(_HEAD_ANCHOR, n)+ tail_start = max(head_end, n - _TAIL_ANCHOR)++ out: list[str] = []+ repeats = 0 # consecutive duplicates of the last emitted line+ last_emitted: str | None = None+ progress_counts: dict[str, int] = {}+ progress_first: dict[str, int] = {}+ table_rows = 0+ dropped = 0++ def emit(line: str) -> None:+ """Append, collapsing consecutive duplicate lines into one + count."""+ nonlocal repeats, last_emitted+ if line.strip() and line.strip() == last_emitted:+ repeats += 1+ return+ flush_repeats()+ last_emitted = line.strip()+ out.append(line)++ def flush_repeats() -> None:+ nonlocal repeats+ if repeats:+ out[-1] = f"{out[-1]} (x{repeats + 1})"+ repeats = 0++ for i, line in enumerate(lines):+ anchored = i < head_end or i >= tail_start+ if is_error_line(line) or _WARNING_RE.search(line) or _LOCATION_RE.match(line):+ emit(line)+ elif m := _PROGRESS_RE.match(line):+ verb = m.group("verb")+ progress_counts[verb] = progress_counts.get(verb, 0) + 1+ if verb not in progress_first:+ flush_repeats()+ last_emitted = None+ progress_first[verb] = len(out)+ out.append(line) # placeholder; annotated with count below+ elif _TABLE_RE.search(line) and line.strip():+ table_rows += 1+ if table_rows <= _MAX_TABLE_ROWS or anchored:+ emit(line)+ elif anchored:+ emit(line)+ elif line.strip():+ dropped += 1+ flush_repeats()++ for verb, idx in progress_first.items():+ count = progress_counts[verb]+ if count > 1:+ out[idx] = f"{out[idx]} (x{count}, further {verb} lines collapsed)"+ if table_rows > _MAX_TABLE_ROWS:+ out.append(f"({table_rows - _MAX_TABLE_ROWS} table rows omitted)")+ if dropped:+ out.append(f"({dropped} build-output lines omitted)")+ return "\n".join(out)diff --git a/packages/core/src/repowise/core/distill/filters/file_listing.py b/packages/core/src/repowise/core/distill/filters/file_listing.pynew file mode 100644index 000000000..49bc34ff5--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/file_listing.py@@ -0,0 +1,92 @@+"""Grouped-tree compaction of file listings (find, ls, dir, tree, fd).++A 500-line ``find`` dump becomes one line per directory with a file count and+a few example names — the structure survives, the bulk does not.+"""++from __future__ import annotations++import re+from collections import OrderedDict+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(r"^(ls\b|dir\b|tree\b|find\b|fd\b|get-childitem\b|gci\b|git ls-files\b)")++# A bare path: no spaces (or escaped ones), with directory separators or an extension.+_PATH_LINE_RE = re.compile(r"^[\w.@~-]+(?:[\\/][\w.@\[\]-]+)*[\\/]?$")++# ls -l style: permission bits then columns ending in the name.+_LS_LONG_RE = re.compile(r"^[-dlbcps][-rwxsStT]{9}[\s+@]")++_EXAMPLES_PER_DIR = 4+_MAX_DIRS = 60+_MAX_FLAT_ENTRIES = 50+++@filter_registry.register+class FileListingFilter(OutputFilter):+ name: ClassVar[str] = "file_listing"+ priority: ClassVar[int] = 40+ min_lines: ClassVar[int] = 40++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command))++ def matches_content(self, output: str) -> bool:+ lines = [ln for ln in output.splitlines() if ln.strip()]+ if len(lines) < self.min_lines:+ return False+ pathish = sum(1 for ln in lines if _PATH_LINE_RE.match(ln.strip()))+ return pathish / len(lines) > 0.8++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ lines = [ln for ln in output.splitlines() if ln.strip()]+ if sum(1 for ln in lines if _LS_LONG_RE.match(ln)) > len(lines) * 0.5:+ return _distill_ls_long(lines)+ paths = [ln.strip() for ln in lines if _PATH_LINE_RE.match(ln.strip())]+ if len(paths) < len(lines) * 0.8:+ raise ValueError("not a recognizable file listing")+ return _distill_paths(paths)+++def _distill_paths(paths: list[str]) -> str:+ groups: OrderedDict[str, list[str]] = OrderedDict()+ for p in paths:+ normalized = p.replace("\\", "/").rstrip("/")+ parent, _, name = normalized.rpartition("/")+ groups.setdefault(parent or ".", []).append(name)++ out = [f"{len(paths)} entries in {len(groups)} directories:"]+ for i, (parent, names) in enumerate(groups.items()):+ if i >= _MAX_DIRS:+ remaining = len(groups) - _MAX_DIRS+ files_left = sum(len(v) for v in list(groups.values())[_MAX_DIRS:])+ out.append(f" ... ({remaining} more directories, {files_left} entries)")+ break+ examples = ", ".join(names[:_EXAMPLES_PER_DIR])+ more = f", +{len(names) - _EXAMPLES_PER_DIR} more" if len(names) > _EXAMPLES_PER_DIR else ""+ out.append(f" {parent}/ ({len(names)}: {examples}{more})")+ return "\n".join(out)+++def _distill_ls_long(lines: list[str]) -> str:+ entries: list[str] = []+ for ln in lines:+ if not _LS_LONG_RE.match(ln):+ continue+ fields = ln.split()+ if len(fields) < 9:+ continue+ name = " ".join(fields[8:])+ suffix = "/" if ln.startswith("d") else ""+ entries.append(f"{name}{suffix} ({fields[4]})")+ if not entries:+ raise ValueError("not ls -l output")+ out = [f"{len(entries)} entries:"]+ out.extend(entries[:_MAX_FLAT_ENTRIES])+ if len(entries) > _MAX_FLAT_ENTRIES:+ out.append(f" ... ({len(entries) - _MAX_FLAT_ENTRIES} more entries)")+ return "\n".join(out)diff --git a/packages/core/src/repowise/core/distill/filters/git_diff.py b/packages/core/src/repowise/core/distill/filters/git_diff.pynew file mode 100644index 000000000..3cbbec2e7--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/git_diff.py@@ -0,0 +1,91 @@+"""Compact rendering of ``git diff`` output.++Diffstat-style summary first, then full hunks for the few files carrying most+of the change; the long tail is listed with counts only. Per-file hunks are+additionally capped with error-line-safe anchoring so one giant lockfile+rewrite cannot dominate the rendering.+"""++from __future__ import annotations++import re+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter, cap_block+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(r"^git(?:\.exe)? (?:diff|show)\b")+_FILE_HEADER_RE = re.compile(r"^diff --git a/(?P<a>.+?) b/(?P<b>.+)$")++#: Files whose hunks are kept in full (the rest are summarized).+KEEP_FILES = 5+#: Per-file line cap for kept hunk blocks.+MAX_BLOCK_LINES = 160+++@filter_registry.register+class GitDiffFilter(OutputFilter):+ name: ClassVar[str] = "git_diff"+ priority: ClassVar[int] = 10+ min_lines: ClassVar[int] = 40++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command)) and "--stat" not in command++ def matches_content(self, output: str) -> bool:+ head = output.splitlines()[:5]+ return any(_FILE_HEADER_RE.match(ln) for ln in head)++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ blocks = _split_file_blocks(output)+ if not blocks:+ raise ValueError("not a recognizable unified diff")++ total_add = sum(b.added for b in blocks)+ total_del = sum(b.deleted for b in blocks)+ # Rank by change volume; render in original order for readability.+ keep_paths = {+ b.path+ for b in sorted(blocks, key=lambda b: b.added + b.deleted, reverse=True)[:KEEP_FILES]+ }++ lines = [f"diff: {len(blocks)} files changed, +{total_add} -{total_del}"]+ summarized: list[str] = []+ for block in blocks:+ if block.path in keep_paths:+ lines.append("")+ lines.extend(cap_block(block.lines, head=30, tail=MAX_BLOCK_LINES - 30))+ else:+ summarized.append(f" {block.path} | +{block.added} -{block.deleted}")+ if summarized:+ lines.append("")+ lines.append(f"hunks omitted for {len(summarized)} smaller files:")+ lines.extend(summarized)+ return "\n".join(lines)+++class _FileBlock:+ __slots__ = ("added", "deleted", "lines", "path")++ def __init__(self, path: str) -> None:+ self.path = path+ self.lines: list[str] = []+ self.added = 0+ self.deleted = 0+++def _split_file_blocks(output: str) -> list[_FileBlock]:+ blocks: list[_FileBlock] = []+ current: _FileBlock | None = None+ for line in output.splitlines():+ if m := _FILE_HEADER_RE.match(line):+ current = _FileBlock(m.group("b"))+ blocks.append(current)+ if current is None:+ continue+ current.lines.append(line)+ if line.startswith("+") and not line.startswith("+++"):+ current.added += 1+ elif line.startswith("-") and not line.startswith("---"):+ current.deleted += 1+ return blocksdiff --git a/packages/core/src/repowise/core/distill/filters/git_log.py b/packages/core/src/repowise/core/distill/filters/git_log.pynew file mode 100644index 000000000..3f8bd5b1c--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/git_log.py@@ -0,0 +1,87 @@+"""Compact rendering of ``git log`` output — subjects only, capped count.++Full-format logs (commit/Author/Date/body) collapse to one line per commit;+already-oneline logs are simply capped. Commit bodies rarely matter for+orientation, and when they do the marker round-trips the full log.+"""++from __future__ import annotations++import re+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(r"^git(?:\.exe)? log\b")+_COMMIT_RE = re.compile(r"^commit (?P<sha>[0-9a-f]{7,40})")+_ONELINE_RE = re.compile(r"^[0-9a-f]{7,12} \S")+_DATE_RE = re.compile(r"^Date:\s+(?P<date>.+)$")++#: Most-recent subjects kept in the compact rendering.+MAX_COMMITS = 20+#: Cap for logs that are already oneline-formatted.+MAX_ONELINE = 40+++@filter_registry.register+class GitLogFilter(OutputFilter):+ name: ClassVar[str] = "git_log"+ priority: ClassVar[int] = 10+ min_lines: ClassVar[int] = 12++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command))++ def matches_content(self, output: str) -> bool:+ lines = output.splitlines()+ if not lines:+ return False+ commit_lines = sum(1 for ln in lines[:200] if _COMMIT_RE.match(ln))+ return commit_lines >= 3 and "Author:" in output++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ lines = output.splitlines()+ commits = _parse_full_format(lines)+ if commits:+ return _render(commits)+ oneline = [ln for ln in lines if _ONELINE_RE.match(ln)]+ if len(oneline) >= self.min_lines:+ kept = oneline[:MAX_ONELINE]+ header = f"{len(oneline)} commits (showing {len(kept)} most recent)"+ return "\n".join([header, *kept])+ raise ValueError("not a recognizable git log format")+++def _parse_full_format(lines: list[str]) -> list[tuple[str, str, str]]:+ """Extract (sha, date, subject) triples from full-format git log."""+ commits: list[tuple[str, str, str]] = []+ sha = date = ""+ subject: str | None = None+ for line in lines:+ if m := _COMMIT_RE.match(line):+ if sha:+ commits.append((sha, date, subject or ""))+ sha, date, subject = m.group("sha"), "", None+ elif m := _DATE_RE.match(line):+ date = _short_date(m.group("date"))+ elif sha and subject is None and line.startswith(" ") and line.strip():+ subject = line.strip()+ if sha:+ commits.append((sha, date, subject or ""))+ return commits+++def _short_date(date: str) -> str:+ """'Thu Jun 5 10:12:01 2026 +0530' -> 'Jun 5 2026' (best effort)."""+ parts = date.split()+ if len(parts) >= 5:+ return f"{parts[1]} {parts[2]} {parts[4]}"+ return date+++def _render(commits: list[tuple[str, str, str]]) -> str:+ kept = commits[:MAX_COMMITS]+ header = f"{len(commits)} commits (showing {len(kept)} most recent; subjects only)"+ body = [f"{sha[:8]} {date:<12} {subject}".rstrip() for sha, date, subject in kept]+ return "\n".join([header, *body])diff --git a/packages/core/src/repowise/core/distill/filters/git_status.py b/packages/core/src/repowise/core/distill/filters/git_status.pynew file mode 100644index 000000000..d74da1201--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/git_status.py@@ -0,0 +1,142 @@+"""Compact rendering of long-format ``git status`` output.++Turns the verbose hint-laden long format into a porcelain-style listing:+one branch line, one status-coded line per path, one totals line.+"""++from __future__ import annotations++import re+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(r"^git(?:\.exe)? status\b")++_BRANCH_RE = re.compile(r"^On branch (?P<branch>\S+)")+_DETACHED_RE = re.compile(r"^HEAD detached at (?P<at>\S+)")+_AHEAD_RE = re.compile(r"ahead of '(?P<remote>[^']+)' by (?P<n>\d+) commit")+_BEHIND_RE = re.compile(r"behind '(?P<remote>[^']+)' by (?P<n>\d+) commit")+_DIVERGED_RE = re.compile(r"have (?P<a>\d+) and (?P<b>\d+) different commits")+_UP_TO_DATE_RE = re.compile(r"up to date with '(?P<remote>[^']+)'")++_SECTIONS = {+ "Changes to be committed:": "staged",+ "Changes not staged for commit:": "unstaged",+ "Untracked files:": "untracked",+ "Unmerged paths:": "conflict",+}++_ENTRY_RE = re.compile(+ r"^(?:\t| {4,8})"+ r"(?:(?P<verb>modified|new file|deleted|renamed|copied|typechange|"+ r"both modified|both added|both deleted|added by us|added by them|"+ r"deleted by us|deleted by them):\s+)?"+ r"(?P<path>\S.*)$"+)++_CODES = {+ "modified": "M",+ "new file": "A",+ "deleted": "D",+ "renamed": "R",+ "copied": "C",+ "typechange": "T",+ "both modified": "UU",+ "both added": "AA",+ "both deleted": "DD",+ "added by us": "AU",+ "added by them": "UA",+ "deleted by us": "DU",+ "deleted by them": "UD",+}+++@filter_registry.register+class GitStatusFilter(OutputFilter):+ name: ClassVar[str] = "git_status"+ priority: ClassVar[int] = 10+ min_lines: ClassVar[int] = 6++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command)) and "--porcelain" not in command++ def matches_content(self, output: str) -> bool:+ head = output[:400]+ return ("On branch " in head or "HEAD detached at" in head) and (+ "git add" in output or "working tree clean" in output+ )++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ branch_line = _render_branch_line(output)+ entries, counts = _parse_entries(output)+ if branch_line is None and not entries:+ raise ValueError("not a recognizable git status long format")++ lines: list[str] = []+ if branch_line:+ lines.append(branch_line)+ if "working tree clean" in output:+ lines.append("clean: nothing to commit")+ return "\n".join(lines)+ lines.extend(entries)+ totals = ", ".join(f"{n} {section}" for section, n in counts.items() if n)+ if totals:+ lines.append(f"({totals})")+ return "\n".join(lines)+++def _render_branch_line(output: str) -> str | None:+ branch = None+ m = _BRANCH_RE.search(output)+ if m:+ branch = m.group("branch")+ else:+ m = _DETACHED_RE.search(output)+ if m:+ branch = f"HEAD detached at {m.group('at')}"+ if branch is None:+ return None+ line = f"## {branch}"+ if m2 := _DIVERGED_RE.search(output):+ line += f" [ahead {m2.group('a')}, behind {m2.group('b')}]"+ elif m2 := _AHEAD_RE.search(output):+ line += f"...{m2.group('remote')} [ahead {m2.group('n')}]"+ elif m2 := _BEHIND_RE.search(output):+ line += f"...{m2.group('remote')} [behind {m2.group('n')}]"+ elif m2 := _UP_TO_DATE_RE.search(output):+ line += f"...{m2.group('remote')}"+ return line+++def _parse_entries(output: str) -> tuple[list[str], dict[str, int]]:+ entries: list[str] = []+ counts: dict[str, int] = {}+ section: str | None = None+ for line in output.splitlines():+ stripped = line.strip()+ if stripped in _SECTIONS:+ section = _SECTIONS[stripped]+ continue+ if section is None:+ continue+ if stripped == "" or stripped.startswith("("):+ # Blank line or hint text ends/annotates a section; hints are+ # parenthesized ("use git add ..."), blank ends the block.+ if stripped == "":+ section = None+ continue+ m = _ENTRY_RE.match(line)+ if m is None:+ continue+ verb, path = m.group("verb"), m.group("path")+ if section == "untracked":+ entries.append(f"?? {path}")+ else:+ code = _CODES.get(verb or "modified", "M")+ # Porcelain-style column: staged in column 1, unstaged in column 2.+ prefix = f"{code} " if section in ("staged", "conflict") else f" {code}"+ entries.append(f"{prefix} {path}")+ counts[section] = counts.get(section, 0) + 1+ return entries, countsdiff --git a/packages/core/src/repowise/core/distill/filters/logs.py b/packages/core/src/repowise/core/distill/filters/logs.pynew file mode 100644index 000000000..24429fd04--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/logs.py@@ -0,0 +1,117 @@+"""Generic log compaction via template collapse.++Lines are normalized (timestamps, numbers, hex ids -> placeholders) into+templates; repeats keep their first occurrence annotated with a count.+Errors are sacred: every ERROR/FATAL/CRITICAL line survives verbatim.+Deliberately the lowest-priority filter — it only sniffs content that+really looks like logs, so it never shadows the structured filters.+"""++from __future__ import annotations++import re+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(+ r"^(tail\b|journalctl\b|docker(?:\.exe)? logs\b|kubectl(?:\.exe)? logs\b|"+ r"(?:cat|type|gc|get-content)\b.*\.log\b)"+)++_LEVEL_RE = re.compile(r"\b(CRITICAL|FATAL|ERROR|ERR|WARNING|WARN|INFO|DEBUG|TRACE)\b")+_SEVERE_RE = re.compile(r"\b(CRITICAL|FATAL|ERROR|ERR)\b")+_TS_RE = re.compile(+ r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?"+ r"|\d{2}:\d{2}:\d{2}(?:[.,]\d+)?"+ r"|\[\d{4}-\d{2}-\d{2}[^\]]*\]"+)+_HEX_RE = re.compile(r"\b[0-9a-fA-F]{8,}\b")+_NUM_RE = re.compile(r"\b\d+(?:\.\d+)?\b")++_MAX_LINES = 100+++@filter_registry.register+class LogsFilter(OutputFilter):+ name: ClassVar[str] = "logs"+ priority: ClassVar[int] = 90+ min_lines: ClassVar[int] = 40++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command))++ def matches_content(self, output: str) -> bool:+ lines = [ln for ln in output.splitlines() if ln.strip()]+ if len(lines) < self.min_lines:+ return False+ loggy = sum(1 for ln in lines if _LEVEL_RE.search(ln) or _TS_RE.search(ln))+ return loggy / len(lines) > 0.6++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ lines = output.splitlines()+ kept: list[tuple[int, str]] = [] # (original index, line)+ counts: dict[str, int] = {}+ first_idx: dict[str, int] = {} # template -> position in kept+ severe = 0++ for i, line in enumerate(lines):+ if not line.strip():+ continue+ if _SEVERE_RE.search(line):+ severe += 1+ kept.append((i, line))+ continue+ template = _template(line)+ if template in counts:+ counts[template] += 1+ else:+ counts[template] = 1+ first_idx[template] = len(kept)+ kept.append((i, line))++ if severe == 0 and len(counts) == len([ln for ln in lines if ln.strip()]):+ # Nothing collapsed and nothing severe: not actually repetitive logs.+ raise ValueError("log output with no repetition to collapse")++ rendered: list[str] = []+ for pos, (_, line) in enumerate(kept):+ template_hits = [t for t, p in first_idx.items() if p == pos]+ if template_hits and counts[template_hits[0]] > 1:+ rendered.append(f"{line} (x{counts[template_hits[0]]} similar)")+ else:+ rendered.append(line)++ if len(rendered) > _MAX_LINES:+ # Keep head/tail plus every severe line in between.+ head, tail = 30, 40+ middle = rendered[head:-tail]+ severe_middle = [ln for ln in middle if _SEVERE_RE.search(ln)]+ elided = len(middle) - len(severe_middle)+ rendered = (+ rendered[:head]+ + severe_middle+ + [f" ... ({elided} distinct log lines elided) ..."]+ + rendered[-tail:]+ )+ return "\n".join(rendered)+++_KV_RE = re.compile(r"(?<==)[^\s,;\]]+")+_QUOTED_RE = re.compile(r'"[^"]*"|\'[^\']*\'')+++def _template(line: str) -> str:+ """Normalize volatile fields so repeated events share one template.++ Timestamps, numbers, hex ids, quoted strings, and ``key=value`` values all+ become placeholders — "parsed file path=a.py took_ms=3" and+ "parsed file path=b.py took_ms=9" collapse into one event template.+ """+ t = _TS_RE.sub("<ts>", line)+ t = _QUOTED_RE.sub("<q>", t)+ t = _KV_RE.sub("<v>", t)+ t = _HEX_RE.sub("<hex>", t)+ t = _NUM_RE.sub("<n>", t)+ return tdiff --git a/packages/core/src/repowise/core/distill/filters/search_results.py b/packages/core/src/repowise/core/distill/filters/search_results.pynew file mode 100644index 000000000..884f8a51a--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/search_results.py@@ -0,0 +1,135 @@+"""Grouped-by-file compaction of search results (grep, rg, git grep).++A 400-line match flood becomes one block per file: match count plus the+first and last matching lines as anchors. Files are ordered by match count;+relevance ranking against the index (PageRank) is the *caller's* job — the+augment hook reorders the same groups when a graph is available, this+filter stays pure and index-free.++Deviation from the error-line invariant: search matches are *matches*, not+diagnostics. A grep for "error" would classify every line as an error line+and defeat compaction entirely, so this filter keeps anchors + counts and+relies on the omission marker for full recovery.+"""++from __future__ import annotations++import re+from collections import OrderedDict+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(+ r"^(rg\b|grep\b|egrep\b|fgrep\b|git(?:\.exe)? grep\b|findstr\b|select-string\b|sls\b)"+)++# path:line:content — tolerates a Windows drive prefix in the path.+_MATCH_LINE_RE = re.compile(r"^(?P<path>(?:[A-Za-z]:)?[^:\n]+?):(?P<line>\d+)[:-](?P<text>.*)$")++# rg "heading" layout: a bare path line followed by `LINE:content` lines.+_HEADED_MATCH_RE = re.compile(r"^(?P<line>\d+)[:-](?P<text>.*)$")+_BARE_PATH_RE = re.compile(r"^(?:[A-Za-z]:)?[\w./\\@~-]+$")++_MAX_FILES = 15+_ANCHORS_PER_FILE = 2+_MAX_TEXT_CHARS = 160+++@filter_registry.register+class SearchResultsFilter(OutputFilter):+ name: ClassVar[str] = "search_results"+ priority: ClassVar[int] = 25+ min_lines: ClassVar[int] = 30++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command))++ def matches_content(self, output: str) -> bool:+ lines = [ln for ln in output.splitlines() if ln.strip()]+ if len(lines) < self.min_lines:+ return False+ matchish = sum(1 for ln in lines if _MATCH_LINE_RE.match(ln))+ return matchish / len(lines) > 0.7++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ groups = group_search_matches(output)+ if groups is None:+ raise ValueError("not recognizable search output")+ return render_search_digest(groups)+++def group_search_matches(output: str) -> OrderedDict[str, list[tuple[int, str]]] | None:+ """Group ``path:line:content`` search output by file, preserving order.++ Handles both the flat ``path:line:content`` layout (rg/grep piped, the+ Claude Code Grep tool) and rg's headed layout (bare path line, then+ ``line:content`` rows). Returns None when fewer than 70% of non-empty+ lines parse as matches — the caller should fall back to raw output.+ """+ groups: OrderedDict[str, list[tuple[int, str]]] = OrderedDict()+ lines = [ln for ln in output.splitlines() if ln.strip()]+ if not lines:+ return None++ current_head: str | None = None+ parsed = 0+ for ln in lines:+ flat = _MATCH_LINE_RE.match(ln)+ if flat:+ current_head = None+ groups.setdefault(flat.group("path"), []).append(+ (int(flat.group("line")), flat.group("text"))+ )+ parsed += 1+ continue+ headed = _HEADED_MATCH_RE.match(ln)+ if headed and current_head is not None:+ groups.setdefault(current_head, []).append(+ (int(headed.group("line")), headed.group("text"))+ )+ parsed += 1+ continue+ if _BARE_PATH_RE.match(ln.strip()) and ("/" in ln or "\\" in ln or "." in ln):+ current_head = ln.strip()+ parsed += 1+ continue+ current_head = None++ if not groups or parsed / len(lines) <= 0.7:+ return None+ return groups+++def render_search_digest(+ groups: OrderedDict[str, list[tuple[int, str]]],+ *,+ file_order: list[str] | None = None,+ max_files: int = _MAX_FILES,+) -> str:+ """Render grouped matches as a compact per-file digest.++ *file_order* lets an index-aware caller put high-centrality files first;+ default order is by match count (descending), input order on ties.+ """+ total = sum(len(v) for v in groups.values())+ if file_order is None:+ ordered = sorted(groups, key=lambda p: -len(groups[p]))+ else:+ known = [p for p in file_order if p in groups]+ ordered = known + [p for p in groups if p not in set(known)]++ out = [f"{total} matches in {len(groups)} files:"]+ for path in ordered[:max_files]:+ matches = groups[path]+ anchors = matches[:1] + (matches[-1:] if len(matches) > 1 else [])+ out.append(f" {path} ({len(matches)} matches)")+ for line_no, text in anchors[:_ANCHORS_PER_FILE]:+ snippet = text.strip()[:_MAX_TEXT_CHARS]+ out.append(f" L{line_no}: {snippet}")+ if len(groups) > max_files:+ hidden_files = len(groups) - max_files+ hidden_matches = sum(len(groups[p]) for p in ordered[max_files:])+ out.append(f" ... ({hidden_files} more files, {hidden_matches} matches)")+ return "\n".join(out)diff --git a/packages/core/src/repowise/core/distill/filters/test_output.py b/packages/core/src/repowise/core/distill/filters/test_output.pynew file mode 100644index 000000000..75586a9ac--- /dev/null+++ b/packages/core/src/repowise/core/distill/filters/test_output.py@@ -0,0 +1,291 @@+"""Errors-first compaction of test-runner output.++Handles pytest, go test, cargo test, and jest/vitest natively, with a+generic errors-plus-anchors fallback for anything else that smells like a+test run. The contract in every mode: all failure information survives+(failure blocks, FAILED/ERROR lines, final summary); what gets dropped is+the pass parade — dots, PASSED lines, ok lines — which is replaced by counts.+"""++from __future__ import annotations++import re+from typing import ClassVar++from repowise.core.distill.filters.base import OutputFilter, cap_block, is_error_line+from repowise.core.distill.registry import filter_registry++_COMMAND_RE = re.compile(+ r"^(pytest\b|py\.test\b|jest\b|vitest\b|cargo(?:\.exe)? (?:test|nextest)\b|"+ r"go(?:\.exe)? test\b|npm(?:\.cmd)? (?:test|run test)\b|pnpm (?:test|run test)\b|"+ r"yarn (?:test|run test)\b)"+)++# pytest --------------------------------------------------------------------+_PYTEST_SEP_RE = re.compile(r"^=+ (?P<title>.+?) =+$")+_PYTEST_SUBSEP_RE = re.compile(r"^_+ .+ _+$")+_PYTEST_FINAL_RE = re.compile(r"^=+ .*\b(passed|failed|error|errors|skipped|no tests ran)\b.* =+$")+_PYTEST_PROGRESS_FAIL_RE = re.compile(r"\b(FAILED|ERROR)\b")++# go test -------------------------------------------------------------------+_GO_RUN_RE = re.compile(r"^=== (?:RUN|PAUSE|CONT|NAME)\b")+_GO_PASS_RE = re.compile(r"^\s*--- PASS:|^PASS$|^ok\s+\S+")+_GO_FAIL_RE = re.compile(r"^\s*--- FAIL:|^FAIL\b")++# cargo test ----------------------------------------------------------------+_CARGO_OK_RE = re.compile(r"^test \S+ \.\.\. ok$")+_CARGO_RESULT_RE = re.compile(r"^test result:")++# jest / vitest -------------------------------------------------------------+_JEST_PASS_SUITE_RE = re.compile(r"^\s*(PASS|√|✓)\s")+_JEST_SUMMARY_RE = re.compile(+ r"^\s*(Tests?(?: Suites)?|Test Files|Snapshots|Time|Duration|Ran all)\b"+)++#: Per-failure-block cap (head keeps the test id, tail keeps the assertion).+_BLOCK_HEAD = 10+_BLOCK_TAIL = 30+++@filter_registry.register+class TestOutputFilter(OutputFilter):+ name: ClassVar[str] = "test_output"+ priority: ClassVar[int] = 20+ min_lines: ClassVar[int] = 10++ def matches_command(self, command: str) -> bool:+ return bool(_COMMAND_RE.match(command))++ def matches_content(self, output: str) -> bool:+ return _detect_format(output) is not None++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ fmt = _detect_format(output)+ lines = output.splitlines()+ if fmt == "pytest":+ return _distill_pytest(lines)+ if fmt == "go":+ return _distill_go(lines)+ if fmt == "cargo":+ return _distill_cargo(lines)+ if fmt == "jest":+ return _distill_jest(lines)+ return _distill_generic(lines)+++def _detect_format(output: str) -> str | None:+ if "test session starts" in output:+ return "pytest"+ if re.search(r"^test result:", output, re.MULTILINE):+ return "cargo"+ if re.search(r"^(=== RUN|--- (PASS|FAIL):|ok\s+\S+\s+[\d.]+s)", output, re.MULTILINE):+ return "go"+ # jest/vitest: the summary block always counts "N total"; prose that merely+ # mentions "Tests:" (e.g. commit bodies) must not sniff as a test run.+ if re.search(r"^\s*(Tests?(?: Suites)?|Test Files):.*\btotal\b", output, re.MULTILINE) or (+ re.search(r"^\s*(PASS|FAIL)\s+\S+\.(test|spec)\.[jt]sx?", output, re.MULTILINE)+ ):+ return "jest"+ return None+++# -- pytest ------------------------------------------------------------------+++def _distill_pytest(lines: list[str]) -> str:+ out: list[str] = []+ section = "header"+ section_buf: list[str] = []+ dropped_progress = 0+ warning_lines = 0++ def flush_failure_section() -> None:+ """Emit buffered FAILURES/ERRORS sub-blocks, individually capped."""+ block: list[str] = []+ for ln in section_buf:+ if _PYTEST_SUBSEP_RE.match(ln) and block:+ out.extend(cap_block(block, _BLOCK_HEAD, _BLOCK_TAIL))+ block = [ln]+ else:+ block.append(ln)+ if block:+ out.extend(cap_block(block, _BLOCK_HEAD, _BLOCK_TAIL))++ for line in lines:+ sep = _PYTEST_SEP_RE.match(line)+ if sep:+ if section in ("failures", "errors"):+ flush_failure_section()+ elif section == "warnings" and warning_lines:+ out.append(f"(warnings summary omitted: {warning_lines} lines)")+ section_buf = []+ title = sep.group("title").lower()+ if "test session starts" in title:+ section = "header"+ out.append(line)+ elif title in ("failures", "errors"):+ section = title+ out.append(line)+ elif "warnings summary" in title:+ section = "warnings"+ elif "short test summary info" in title:+ section = "summary"+ out.append(line)+ elif _PYTEST_FINAL_RE.match(line):+ section = "done"+ if dropped_progress:+ out.append(f"({dropped_progress} progress lines omitted)")+ dropped_progress = 0+ out.append(line)+ else:+ section = "other"+ continue++ if section == "header":+ if (+ line.startswith(("platform ", "collected ", "rootdir:"))+ or _PYTEST_PROGRESS_FAIL_RE.search(line)+ or is_error_line(line)+ ):+ out.append(line)+ elif line.strip():+ dropped_progress += 1+ elif section in ("failures", "errors"):+ section_buf.append(line)+ elif section == "warnings":+ if line.strip():+ warning_lines += 1+ elif section == "summary" or (section in ("other", "done") and is_error_line(line)):+ out.append(line)++ if section in ("failures", "errors"):+ flush_failure_section()+ if not any(_PYTEST_SEP_RE.match(ln) for ln in out):+ raise ValueError("pytest output without recognizable sections")+ return "\n".join(out)+++# -- go test -----------------------------------------------------------------+++def _distill_go(lines: list[str]) -> str:+ out: list[str] = []+ passes = 0+ runs = 0+ in_fail_block = False+ for line in lines:+ if _GO_RUN_RE.match(line):+ runs += 1+ in_fail_block = False+ elif _GO_FAIL_RE.match(line):+ in_fail_block = line.lstrip().startswith("--- FAIL")+ out.append(line)+ elif _GO_PASS_RE.match(line):+ in_fail_block = False+ if line.startswith(("ok", "PASS")):+ out.append(line)+ else:+ passes += 1+ elif line.startswith("exit status ") or in_fail_block or is_error_line(line):+ out.append(line)+ if not out and passes == 0 and runs == 0:+ raise ValueError("not go test output")+ if passes or runs:+ out.insert(0, f"({passes or runs} passing tests omitted)")+ return "\n".join(out)+++# -- cargo test --------------------------------------------------------------+++def _distill_cargo(lines: list[str]) -> str:+ out: list[str] = []+ ok_count = 0+ in_failures = False+ for line in lines:+ if _CARGO_OK_RE.match(line):+ ok_count += 1+ elif line.strip() == "failures:":+ in_failures = True+ out.append(line)+ elif _CARGO_RESULT_RE.match(line):+ in_failures = False+ out.append(line)+ elif (+ (line.startswith("running ") and line.endswith(("tests", "test")))+ or in_failures+ or is_error_line(line)+ ):+ out.append(line)+ if ok_count:+ out.insert(0, f"({ok_count} passing tests omitted)")+ if not any(_CARGO_RESULT_RE.match(ln) for ln in out):+ raise ValueError("cargo test output without a result line")+ return "\n".join(out)+++# -- jest / vitest -----------------------------------------------------------+++def _distill_jest(lines: list[str]) -> str:+ out: list[str] = []+ passing = 0+ pass_suites = 0+ in_failure_block = False+ block: list[str] = []++ def flush() -> None:+ nonlocal block+ if block:+ out.extend(cap_block(block, _BLOCK_HEAD, _BLOCK_TAIL))+ block = []++ for line in lines:+ stripped = line.strip()+ if stripped.startswith("●") or stripped.startswith("⎯") or is_error_line(line):+ in_failure_block = True+ block.append(line)+ elif _JEST_SUMMARY_RE.match(line):+ in_failure_block = False+ flush()+ out.append(line)+ elif _JEST_PASS_SUITE_RE.match(line):+ in_failure_block = False+ flush()+ if stripped.startswith("PASS"):+ pass_suites += 1+ else:+ passing += 1+ elif in_failure_block:+ block.append(line)+ flush()+ if passing or pass_suites:+ parts = []+ if pass_suites:+ parts.append(f"{pass_suites} passing suites")+ if passing:+ parts.append(f"{passing} passing tests")+ out.insert(0, f"({' and '.join(parts)} omitted)")+ if not out:+ raise ValueError("not jest/vitest output")+ return "\n".join(out)+++# -- generic -----------------------------------------------------------------+++def _distill_generic(lines: list[str]) -> str:+ """Errors + anchors: head, tail, and every error line with light context."""+ keep = set(range(min(5, len(lines))))+ keep.update(range(max(0, len(lines) - 10), len(lines)))+ for i, line in enumerate(lines):+ if is_error_line(line):+ keep.update((max(0, i - 1), i, min(len(lines) - 1, i + 1)))+ out: list[str] = []+ last = -1+ for i in sorted(keep):+ if i != last + 1:+ out.append(f" ... ({i - last - 1} lines elided) ...")+ out.append(lines[i])+ last = i+ return "\n".join(out)diff --git a/packages/core/src/repowise/core/distill/markers.py b/packages/core/src/repowise/core/distill/markers.pynew file mode 100644index 000000000..3a3079772--- /dev/null+++ b/packages/core/src/repowise/core/distill/markers.py@@ -0,0 +1,46 @@+"""Omission-marker rendering and parsing — ONE format everywhere.++Every distill surface (CLI executor, hooks, MCP truncation) renders dropped+content as the same marker so a single ``expand`` implementation can resolve+any ref it encounters. The marker is deliberately ASCII-only: distilled output+is echoed to consoles that may not be UTF-8 (Windows cp1252), and a marker+that crashes the terminal would violate the never-make-things-worse rule.+"""++from __future__ import annotations++import re++REF_LENGTH = 12++_MARKER_TEMPLATE = (+ "[repowise#{ref}: {lines} lines omitted (~{tokens} tokens); restore: repowise expand {ref}]"+)++MARKER_RE = re.compile(r"\[repowise#(?P<ref>[0-9a-f]{12}):[^\]]*\]")+++def render_marker(ref: str, lines_omitted: int, tokens_omitted: int) -> str:+ """Render the omission marker for *ref*."""+ if not is_valid_ref(ref):+ raise ValueError(f"invalid omission ref: {ref!r}")+ return _MARKER_TEMPLATE.format(+ ref=ref, lines=max(lines_omitted, 0), tokens=max(tokens_omitted, 0)+ )+++def parse_marker_refs(text: str) -> list[str]:+ """Return every omission ref embedded in *text*, in order, deduplicated."""+ seen: set[str] = set()+ refs: list[str] = []+ for match in MARKER_RE.finditer(text):+ ref = match.group("ref")+ if ref not in seen:+ seen.add(ref)+ refs.append(ref)+ return refs+++def is_valid_ref(ref: str) -> bool:+ """True when *ref* looks like a store key (12 lowercase hex chars)."""+ return bool(re.fullmatch(r"[0-9a-f]{12}", ref))diff --git a/packages/core/src/repowise/core/distill/registry.py b/packages/core/src/repowise/core/distill/registry.pynew file mode 100644index 000000000..067000f95--- /dev/null+++ b/packages/core/src/repowise/core/distill/registry.py@@ -0,0 +1,47 @@+"""Filter registry — adding a filter is a new file + decorator, zero router edits.++Mirrors the ``mcp_tool_registry`` / ``external_systems`` patterns: filter+modules self-register at import time and the router consumes the registry,+so third-party or future filters slot in without touching dispatch code.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, TypeVar++if TYPE_CHECKING:+ from repowise.core.distill.filters.base import OutputFilter++F = TypeVar("F", bound="type[OutputFilter]")+++class FilterRegistry:+ """Ordered registry of output-filter instances."""++ def __init__(self) -> None:+ self._filters: list[OutputFilter] = []++ def register(self, filter_cls: F) -> F:+ """Class decorator: instantiate and register *filter_cls*."""+ self._filters.append(filter_cls())+ return filter_cls++ def filters(self) -> tuple[OutputFilter, ...]:+ """All registered filters, lowest ``priority`` first."""+ self._ensure_loaded()+ return tuple(sorted(self._filters, key=lambda f: f.priority))++ def get(self, name: str) -> OutputFilter | None:+ """Look up a filter by its registered name."""+ for f in self.filters():+ if f.name == name:+ return f+ return None++ @staticmethod+ def _ensure_loaded() -> None:+ # Importing the package triggers each filter module's decorator.+ import repowise.core.distill.filters # noqa: F401+++filter_registry = FilterRegistry()diff --git a/packages/core/src/repowise/core/distill/router.py b/packages/core/src/repowise/core/distill/router.pynew file mode 100644index 000000000..1a41419df--- /dev/null+++ b/packages/core/src/repowise/core/distill/router.py@@ -0,0 +1,63 @@+"""Filter selection — pure functions mapping (command, output) to a filter.++Command matching wins over content sniffing: when the caller knows what ran,+trust it. Content sniffing is the fallback for surfaces that only see bytes.+"""++from __future__ import annotations++import re+from collections.abc import Iterable++from repowise.core.distill.filters.base import OutputFilter+from repowise.core.distill.registry import filter_registry++# Wrapper prefixes that mask the real command. Stripped repeatedly so+# "uv run python -m pytest" normalizes down to "pytest ...".+_WRAPPER_RE = re.compile(+ r"^(?:"+ r"uv run|uvx|npx|pnpm exec|pnpm dlx|yarn dlx|poetry run|pipenv run|hatch run|"+ r"python3? -m|py -m"+ r")\s+",+ re.IGNORECASE,+)++# Leading POSIX-style env assignments: FOO=bar BAZ=1 cmd ...+_ENV_ASSIGN_RE = re.compile(r"^\w+=\S+\s+")++# Path prefix on the executable: .venv\Scripts\pytest.exe → pytest+_EXE_PATH_RE = re.compile(r'^(?:"[^"]*[\\/]|\S*[\\/])(?P<exe>[\w.-]+?)(?:\.exe)?(?:")?(?=\s|$)')+++def normalize_command(command: str) -> str:+ """Lowercased command with wrappers, env assignments, and exe paths stripped."""+ cmd = command.strip()+ for _ in range(4):+ previous = cmd+ cmd = _ENV_ASSIGN_RE.sub("", cmd)+ cmd = _WRAPPER_RE.sub("", cmd)+ if cmd == previous:+ break+ cmd = _EXE_PATH_RE.sub(lambda m: m.group("exe"), cmd)+ return cmd.lower()+++def select_filter(+ command: str = "",+ output: str = "",+ *,+ disabled: Iterable[str] = (),+) -> OutputFilter | None:+ """Pick the filter for *command*/*output*, or None when nothing applies."""+ disabled_set = set(disabled)+ candidates = [f for f in filter_registry.filters() if f.name not in disabled_set]+ normalized = normalize_command(command) if command else ""+ if normalized:+ for f in candidates:+ if f.matches_command(normalized):+ return f+ if output:+ for f in candidates:+ if f.matches_content(output):+ return f+ return Nonediff --git a/packages/core/src/repowise/core/distill/skeleton.py b/packages/core/src/repowise/core/distill/skeleton.pynew file mode 100644index 000000000..1c90e2bfe--- /dev/null+++ b/packages/core/src/repowise/core/distill/skeleton.py@@ -0,0 +1,456 @@+"""Index-backed file skeletonization — slice on persisted symbol bounds.++A skeleton is the file with symbol *bodies* elided: imports and module+docstring kept, every signature kept, bodies replaced by one-line elision+markers carrying the omitted line range. Because ``WikiSymbol`` rows persist+``start_line``/``end_line`` at index time, the skeleton is produced by pure+line slicing — **no parser runs at query time** (~1 ms for a large file).++Two modes:++- ``"signatures"`` — structure only. Every signature present, all bodies+ elided. The cheapest faithful map of a file. Docstrings are NOT kept here+ (they push a typical Python file from ~15% to ~20% of full tokens, and the+ index already serves them via get_context symbol cards).+- ``"smart"`` — signatures plus docstring summary lines plus the bodies of+ the most *important* symbols,+ ranked by caller-provided importance (PageRank), query-name match, with a+ per-symbol line budget proportional to importance, all under a total token+ budget. A hotspot file gets a larger budget — high-churn code is where+ body-level context pays off.++This module is pure: it sees source text and symbol records, never a+database. Callers (MCP tools, hooks, tests) fetch the rows and pass them in.+Degradation is graceful by construction — no usable symbols means the source+is returned untouched (``mode="raw"``), never an error.+"""++from __future__ import annotations++import re+from collections.abc import Sequence+from dataclasses import dataclass, field++from repowise.core.distill.budget import estimate_tokens++__all__ = [+ "DEFAULT_TOKEN_BUDGET",+ "SkeletonResult",+ "SkeletonSymbol",+ "build_skeleton",+ "estimate_skeleton_tokens",+]++#: Default total token budget for smart mode (signatures + kept bodies).+DEFAULT_TOKEN_BUDGET = 1800++#: Hotspot files get proportionally more body context.+_HOTSPOT_BUDGET_FACTOR = 1.25++#: Max lines scanned past a symbol's start to find the end of its signature.+_SIG_SCAN_MAX = 12++#: Docstring lines kept directly under a signature before eliding the rest.+#: One line = the summary; the elision marker right after it signals more.+_DOCSTRING_KEEP_LINES = 1++#: Module-level gaps (constants, registrations) up to this size are kept+#: verbatim — an elision marker would not be shorter.+_GAP_KEEP_LINES = 4++#: Preambles up to this size are kept whole; longer ones are filtered down+#: to the leading docstring/comment block plus import-shaped lines.+_PREAMBLE_KEEP_LINES = 60++#: Smart mode keeps at most this many symbol bodies.+_SMART_MAX_BODIES = 5++#: A kept body always gets at least this many lines (below that, the head+#: of a function is rarely worth more than its signature).+_SMART_MIN_BODY_LINES = 4++_IMPORT_RE = re.compile(+ r"^\s*(import\s|from\s+\S+\s+import\s|use\s|require\s*\(|#include\s|using\s|package\s)"+)++#: Decorative comment rules (``# ----``, ``// ====``) carry zero information;+#: they are dropped from the skeleton without a marker.+_DECOR_RE = re.compile(r"^\s*(?:#|//)\s*[-=~*#_]{4,}\s*$")++_DOCSTRING_DELIMS = ('"""', "'''")+++@dataclass(frozen=True)+class SkeletonSymbol:+ """One indexed symbol, as persisted on a ``WikiSymbol`` row.++ ``importance`` is whatever ranking signal the caller has — symbol-node+ PageRank in the indexed case, 0.0 when the graph has nothing. The+ skeleton only compares importances relative to each other.+ """++ name: str+ kind: str+ start_line: int # 1-indexed, inclusive+ end_line: int # 1-indexed, inclusive+ signature: str = ""+ importance: float = 0.0+++@dataclass(frozen=True)+class SkeletonResult:+ """Outcome of one skeletonization."""++ text: str+ mode: str # "smart" | "signatures" | "raw"+ full_tokens: int+ skeleton_tokens: int+ symbol_count: int+ bodies_kept: tuple[str, ...] = field(default=())++ @property+ def pct_of_full(self) -> float:+ if self.full_tokens <= 0:+ return 100.0+ return self.skeleton_tokens / self.full_tokens * 100.0+++def build_skeleton(+ source: str,+ symbols: Sequence[SkeletonSymbol],+ *,+ mode: str = "smart",+ token_budget: int = DEFAULT_TOKEN_BUDGET,+ query: str | None = None,+ hotspot: bool = False,+) -> SkeletonResult:+ """Skeletonize *source* by slicing on the persisted bounds in *symbols*.++ Pure line arithmetic — no parsing. When *symbols* is empty or none of the+ bounds are usable, the source is returned untouched with ``mode="raw"``+ (the caller's signal that the index could not help here).+ """+ full_tokens = estimate_tokens(source)+ lines = source.splitlines()+ total = len(lines)++ usable = _sanitize(symbols, total)+ if not usable:+ return SkeletonResult(+ text=source,+ mode="raw",+ full_tokens=full_tokens,+ skeleton_tokens=full_tokens,+ symbol_count=0,+ )++ keep = [False] * total++ # Preamble: module docstring + imports + leading module code.+ first_start = usable[0].start_line - 1 # 0-indexed+ _keep_preamble(lines, first_start, keep)++ # Signatures; smart mode also keeps the docstring summary line under each.+ smart = mode == "smart"+ sig_ends: dict[int, int] = {} # symbol index -> 0-indexed signature end+ for idx, sym in enumerate(usable):+ s = sym.start_line - 1+ e = _signature_end(lines, s, sym.end_line - 1)+ sig_ends[idx] = e+ for i in range(s, e + 1):+ keep[i] = True+ if smart:+ for i in _docstring_lines(lines, e + 1, sym.end_line - 1):+ keep[i] = True++ # Small module-level gaps between symbols stay verbatim.+ _keep_small_gaps(lines, usable, total, keep)++ bodies_kept: tuple[str, ...] = ()+ if smart:+ budget = int(token_budget * (_HOTSPOT_BUDGET_FACTOR if hotspot else 1.0))+ bodies_kept = _keep_smart_bodies(lines, usable, sig_ends, keep, budget, query)++ # Decorative banner comments add bytes, not structure.+ for i in range(total):+ if keep[i] and _DECOR_RE.match(lines[i]):+ keep[i] = False++ text = _render(lines, keep)+ return SkeletonResult(+ text=text,+ mode=mode if mode in ("smart", "signatures") else "signatures",+ full_tokens=full_tokens,+ skeleton_tokens=estimate_tokens(text),+ symbol_count=len(usable),+ bodies_kept=bodies_kept,+ )+++def estimate_skeleton_tokens(+ symbol_bounds: Sequence[tuple[int, int]],+ *,+ file_size_bytes: int,+ total_lines: int | None = None,+) -> int:+ """Cheap skeleton-size estimate from bounds arithmetic alone.++ For hook paths that must not render anything: approximates the kept+ fraction (preamble + ~2 signature lines + 1 elision line per symbol)+ and scales the file's chars/4 token count by it. Within ~2x of the real+ skeleton size, which is all a "~M tokens vs K" nudge needs.+ """+ if not symbol_bounds or file_size_bytes <= 0:+ return max(0, file_size_bytes // 4)+ starts = [s for s, _ in symbol_bounds if s > 0]+ if not starts:+ return file_size_bytes // 4+ lines_total = total_lines or max(e for _, e in symbol_bounds)+ if lines_total <= 0:+ return file_size_bytes // 4+ preamble = min(min(starts) - 1, _PREAMBLE_KEEP_LINES)+ kept_lines = preamble + 3 * len(symbol_bounds) # ~2 sig lines + 1 marker+ fraction = min(1.0, kept_lines / lines_total)+ return max(1, int(file_size_bytes // 4 * fraction))+++# ---------------------------------------------------------------------------+# Internals — all 0-indexed line arithmetic from here down+# ---------------------------------------------------------------------------+++def _sanitize(symbols: Sequence[SkeletonSymbol], total: int) -> list[SkeletonSymbol]:+ """Drop synthetic/out-of-range rows; clamp and sort by start line."""+ out: list[SkeletonSymbol] = []+ for sym in symbols:+ if sym.name == "__module__" or sym.kind == "module":+ continue # synthetic module-level node, spans nothing real+ if sym.start_line < 1 or sym.start_line > total:+ continue+ end = max(sym.start_line, min(sym.end_line, total))+ if end != sym.end_line:+ sym = SkeletonSymbol(+ name=sym.name,+ kind=sym.kind,+ start_line=sym.start_line,+ end_line=end,+ signature=sym.signature,+ importance=sym.importance,+ )+ out.append(sym)+ out.sort(key=lambda s: (s.start_line, -(s.end_line - s.start_line)))+ return out+++def _keep_preamble(lines: list[str], first_start: int, keep: list[bool]) -> None:+ """Mark the pre-symbol region: whole if small, docstring+imports if not."""+ if first_start <= 0:+ return+ if first_start <= _PREAMBLE_KEEP_LINES:+ for i in range(first_start):+ keep[i] = True+ return+ # Long preamble: leading docstring/comment block, then import-shaped lines.+ i = 0+ in_docstring = False+ while i < first_start:+ stripped = lines[i].strip()+ if i == 0 or in_docstring or stripped.startswith("#") or (not stripped and i < 3):+ keep[i] = True+ opens = sum(stripped.count(d) for d in _DOCSTRING_DELIMS)+ if not in_docstring and any(stripped.startswith(d) for d in _DOCSTRING_DELIMS):+ in_docstring = opens == 1+ elif in_docstring and opens:+ in_docstring = False+ i += 1+ continue+ break+ for j in range(i, first_start):+ if _IMPORT_RE.match(lines[j]):+ keep[j] = True+++def _signature_end(lines: list[str], start: int, end: int) -> int:+ """Last 0-indexed line of the signature starting at *start*.++ Bracket-balance scan, language-agnostic: the signature ends on the first+ line where parens/brackets are balanced and the line closes with a body+ opener (``:``/``{``), a terminator (``;``), or the param list itself.+ Allman-style braces (``{`` alone on the next line) are folded in. Falls+ back to the start line when nothing matches within the scan window.+ """+ depth = 0+ last = min(start + _SIG_SCAN_MAX - 1, end)+ for i in range(start, last + 1):+ line = lines[i]+ depth += line.count("(") - line.count(")")+ depth += line.count("[") - line.count("]")+ if depth > 0:+ continue+ stripped = line.strip()+ if not stripped:+ continue+ if stripped.endswith((":", "{", ";", "=>")):+ return i+ # Signature closed without a body opener — check for an Allman brace.+ j = i + 1+ if j <= end and lines[j].strip().startswith("{"):+ return j+ return i+ return start+++def _docstring_lines(lines: list[str], start: int, end: int) -> list[int]:+ """Indices of a docstring block directly under a signature, capped.++ Only triggers when the first non-blank line after the signature opens a+ triple-quoted string — pure Python convention, harmless elsewhere. Keeps+ at most ``_DOCSTRING_KEEP_LINES`` lines; the closing delimiter line is+ always included when within the cap so the skeleton stays well-formed.+ """+ i = start+ while i <= end and not lines[i].strip():+ i += 1+ if i > end:+ return []+ stripped = lines[i].strip()+ delim = next((d for d in _DOCSTRING_DELIMS if stripped.startswith(d)), None)+ if delim is None:+ return []+ # Single-line docstring: opener and closer on the same line.+ if stripped.count(delim) >= 2:+ return [i]+ kept = [i]+ j = i + 1+ while j <= end and len(kept) < _DOCSTRING_KEEP_LINES:+ kept.append(j)+ if delim in lines[j]:+ return kept+ j += 1+ return kept+++def _keep_small_gaps(+ lines: list[str],+ symbols: list[SkeletonSymbol],+ total: int,+ keep: list[bool],+) -> None:+ """Keep short module-level runs between symbols (constants, registrations)."""+ # Gap candidates: between each symbol end and the next symbol start; the+ # last symbol's "next start" is EOF, which covers the trailing region.+ spans: list[tuple[int, int]] = []+ starts = sorted(s.start_line - 1 for s in symbols)+ ends = sorted(s.end_line for s in symbols) # 0-indexed exclusive+ for e in ends:+ nxt = next((st for st in starts if st >= e), total)+ if e < nxt:+ spans.append((e, nxt))+ for a, b in spans:+ unkept = [i for i in range(a, min(b, total)) if not keep[i]]+ if 0 < len(unkept) <= _GAP_KEEP_LINES:+ for i in unkept:+ keep[i] = True+++def _query_bonus(name: str, query: str | None) -> float:+ if not query:+ return 0.0+ name_l = name.lower()+ tokens = [t for t in re.split(r"[^a-z0-9]+", query.lower()) if len(t) >= 3]+ return 0.75 if any(t in name_l for t in tokens) else 0.0+++def _keep_smart_bodies(+ lines: list[str],+ symbols: list[SkeletonSymbol],+ sig_ends: dict[int, int],+ keep: list[bool],+ token_budget: int,+ query: str | None,+) -> tuple[str, ...]:+ """Mark the bodies of the top-ranked leaf symbols, budget-proportionally."""+ starts = sorted(s.start_line - 1 for s in symbols)++ # Leaf symbols only: a class body is its methods' signatures, which the+ # skeleton already shows — keeping it whole would re-inline everything.+ candidates: list[tuple[float, int]] = [] # (score, symbol index)+ max_importance = max((s.importance for s in symbols), default=0.0)+ for idx, sym in enumerate(symbols):+ body_start = sig_ends[idx] + 1+ body_end = sym.end_line - 1+ if body_end - body_start + 1 <= _GAP_KEEP_LINES:+ continue # tiny body — render rule keeps short runs anyway+ if any(body_start <= st <= body_end for st in starts):+ continue # contains another symbol — not a leaf+ norm = sym.importance / max_importance if max_importance > 0 else 0.0+ score = norm + _query_bonus(sym.name, query)+ if score <= 0.0:+ continue+ candidates.append((score, idx))++ if not candidates:+ return ()++ candidates.sort(key=lambda t: (-t[0], symbols[t[1]].start_line))+ top = candidates[:_SMART_MAX_BODIES]++ base_tokens = estimate_tokens(_render(lines, keep))+ body_budget = max(0, token_budget - base_tokens)+ if body_budget <= 0:+ return ()+ avg_line_tokens = max(1.0, estimate_tokens("\n".join(lines)) / max(1, len(lines)))+ budget_lines = int(body_budget / avg_line_tokens)+ if budget_lines < _SMART_MIN_BODY_LINES:+ return ()++ score_sum = sum(score for score, _ in top) or 1.0+ kept_names: list[str] = []+ remaining = budget_lines+ for score, idx in top:+ if remaining < _SMART_MIN_BODY_LINES:+ break+ sym = symbols[idx]+ body_start = sig_ends[idx] + 1+ body_end = sym.end_line - 1+ body_len = body_end - body_start + 1+ # Per-symbol line budget proportional to importance share.+ share = max(_SMART_MIN_BODY_LINES, int(budget_lines * score / score_sum))+ take = min(body_len, share, remaining)+ if take < _SMART_MIN_BODY_LINES:+ continue+ for i in range(body_start, body_start + take):+ keep[i] = True+ remaining -= take+ kept_names.append(sym.name)+ return tuple(kept_names)+++def _render(lines: list[str], keep: list[bool]) -> str:+ """Emit kept lines verbatim; collapse omitted runs to one marker line.++ Runs of one or two omitted lines are kept verbatim — a marker would not+ be shorter — unless they are pure blank/decoration, which is dropped+ silently. The marker carries the 1-indexed range so an agent can jump+ straight back with a ranged Read.+ """+ out: list[str] = []+ i = 0+ total = len(lines)+ while i < total:+ if keep[i]:+ out.append(lines[i])+ i += 1+ continue+ j = i+ while j < total and not keep[j]:+ j += 1+ if j - i <= 2:+ run = lines[i:j]+ if not all(not ln.strip() or _DECOR_RE.match(ln) for ln in run):+ out.extend(run)+ else:+ indent = re.match(r"[ \t]*", lines[i]).group(0)+ out.append(f"{indent}... {j - i} lines ({i + 1}-{j})")+ i = j+ return "\n".join(out) + ("\n" if out else "")diff --git a/packages/core/src/repowise/core/distill/store.py b/packages/core/src/repowise/core/distill/store.pynew file mode 100644index 000000000..e5d25586c--- /dev/null+++ b/packages/core/src/repowise/core/distill/store.py@@ -0,0 +1,252 @@+"""OmissionStore — durable stash of content dropped by distillation.++Lives in its own SQLite sidecar (``.repowise/omissions/omissions.db``, WAL)+rather than wiki.db so hook-time writes never contend with indexing. Rows are+keyed by a 12-hex truncated SHA-256 of the content, the same ref embedded in+omission markers, so ``expand`` resolves markers from any surface against one+store. Durable across sessions by design (an agent resuming work can still+expand yesterday's markers); pruning is TTL + size-cap based, applied+opportunistically on write.+"""++from __future__ import annotations++import hashlib+import sqlite3+import time+import zlib+from pathlib import Path++import structlog++from repowise.core.distill import tracking+from repowise.core.distill.markers import REF_LENGTH, is_valid_ref++logger = structlog.get_logger(__name__)++OMISSIONS_DIRNAME = "omissions"+OMISSIONS_DB_FILENAME = "omissions.db"++#: Rows older than this are pruned.+DEFAULT_TTL_DAYS = 7+#: Compressed-content size cap; oldest rows pruned first when exceeded.+DEFAULT_MAX_MB = 50++_SCHEMA = """+CREATE TABLE IF NOT EXISTS omissions (+ ref TEXT PRIMARY KEY,+ content BLOB NOT NULL,+ source TEXT NOT NULL,+ created_at REAL NOT NULL,+ original_tokens INTEGER NOT NULL,+ kept_tokens INTEGER NOT NULL,+ access_count INTEGER NOT NULL DEFAULT 0+);+CREATE TABLE IF NOT EXISTS savings (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ created_at REAL NOT NULL,+ filter TEXT NOT NULL,+ source TEXT NOT NULL,+ command TEXT,+ raw_tokens INTEGER NOT NULL,+ distilled_tokens INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_omissions_created ON omissions(created_at);+CREATE INDEX IF NOT EXISTS idx_savings_created ON savings(created_at);+"""+++def default_store_path(start: Path | None = None) -> Path:+ """Resolve the omissions DB path for the repo containing *start*.++ Walks upward looking for an existing ``.repowise/`` directory (stopping at+ the user's home directory) and falls back to ``~/.repowise/`` — the same+ fallback convention as the wiki database. Never creates ``.repowise/`` in+ a repo that has not opted in via ``repowise init``.+ """+ current = (start or Path.cwd()).resolve()+ home = Path.home().resolve()+ for candidate in (current, *current.parents):+ if candidate == home:+ break+ if (candidate / ".repowise").is_dir():+ return candidate / ".repowise" / OMISSIONS_DIRNAME / OMISSIONS_DB_FILENAME+ return home / ".repowise" / OMISSIONS_DIRNAME / OMISSIONS_DB_FILENAME+++def content_ref(content: str) -> str:+ """Stable 12-hex ref for *content* (truncated SHA-256)."""+ return hashlib.sha256(content.encode("utf-8")).hexdigest()[:REF_LENGTH]+++class OmissionStore:+ """Synchronous SQLite store for omitted content and the savings ledger.++ Synchronous on purpose: callers are CLI commands and (later) hook scripts+ where an asyncio loop is pure overhead.+ """++ def __init__(+ self,+ db_path: Path,+ *,+ ttl_days: float = DEFAULT_TTL_DAYS,+ max_mb: float = DEFAULT_MAX_MB,+ ) -> None:+ self.db_path = db_path+ self.ttl_days = ttl_days+ self.max_mb = max_mb+ db_path.parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(db_path)+ self._conn.execute("PRAGMA journal_mode=WAL")+ self._conn.execute("PRAGMA synchronous=NORMAL")+ self._conn.execute("PRAGMA busy_timeout=5000")+ self._conn.executescript(_SCHEMA)+ self._conn.commit()++ @classmethod+ def open_default(cls, start: Path | None = None) -> OmissionStore:+ """Open the store for the repo containing *start* (default: cwd)."""+ return cls(default_store_path(start))++ # -- omissions ---------------------------------------------------------++ def put(+ self,+ content: str,+ *,+ source: str,+ original_tokens: int,+ kept_tokens: int,+ ) -> str:+ """Store *content* and return its marker ref. Idempotent per content."""+ ref = content_ref(content)+ blob = zlib.compress(content.encode("utf-8"))+ self._conn.execute(+ """+ INSERT INTO omissions+ (ref, content, source, created_at, original_tokens, kept_tokens)+ VALUES (?, ?, ?, ?, ?, ?)+ ON CONFLICT(ref) DO UPDATE SET created_at = excluded.created_at+ """,+ (ref, blob, source, time.time(), original_tokens, kept_tokens),+ )+ self._conn.commit()+ self.prune()+ return ref++ def get(self, ref: str, *, query: str | None = None) -> str | None:+ """Return the stored content for *ref*, or None when unknown/expired.++ With *query*, returns only the lines matching it (regex when it+ compiles, plain substring otherwise) — cheap search-within-original.+ """+ record = self.get_record(ref, query=query)+ return record["content"] if record is not None else None++ def get_record(self, ref: str, *, query: str | None = None) -> dict | None:+ """Like :meth:`get` but with the row's provenance metadata.++ Returns ``{content, source, created_at, original_tokens, kept_tokens}``+ or ``None`` when the ref is unknown/expired. *query* filters the+ content lines exactly as in :meth:`get`.+ """+ if not is_valid_ref(ref):+ return None+ row = self._conn.execute(+ "SELECT content, source, created_at, original_tokens, kept_tokens "+ "FROM omissions WHERE ref = ?",+ (ref,),+ ).fetchone()+ if row is None:+ return None+ self._conn.execute(+ "UPDATE omissions SET access_count = access_count + 1 WHERE ref = ?", (ref,)+ )+ self._conn.commit()+ content = zlib.decompress(row[0]).decode("utf-8")+ if query is not None:+ content = _filter_lines(content, query)+ return {+ "content": content,+ "source": row[1],+ "created_at": row[2],+ "original_tokens": row[3],+ "kept_tokens": row[4],+ }++ def prune(self) -> None:+ """Drop rows past TTL, then oldest-first until under the size cap."""+ cutoff = time.time() - self.ttl_days * 86400+ self._conn.execute("DELETE FROM omissions WHERE created_at < ?", (cutoff,))+ max_bytes = int(self.max_mb * 1024 * 1024)+ while True:+ total, rows = self._conn.execute(+ "SELECT COALESCE(SUM(LENGTH(content)), 0), COUNT(*) FROM omissions"+ ).fetchone()+ # Never evict the last row: it may be the one just written, and a+ # marker must not dangle the moment it is rendered.+ if total <= max_bytes or rows <= 1:+ break+ self._conn.execute(+ """+ DELETE FROM omissions WHERE ref IN (+ SELECT ref FROM omissions ORDER BY created_at ASC+ LIMIT MIN(16, (SELECT COUNT(*) - 1 FROM omissions))+ )+ """+ )+ self._conn.commit()++ # -- savings ledger ----------------------------------------------------++ def record_saving(+ self,+ *,+ filter_name: str,+ source: str,+ command: str | None,+ raw_tokens: int,+ distilled_tokens: int,+ ) -> None:+ """Append one distillation event to the savings ledger."""+ tracking.record_saving(+ self._conn,+ filter_name=filter_name,+ source=source,+ command=command,+ raw_tokens=raw_tokens,+ distilled_tokens=distilled_tokens,+ )++ def savings_summary(self, *, since: float | None = None) -> dict:+ """Aggregate ledger totals, overall and per filter."""+ return tracking.savings_summary(self._conn, since=since)++ def savings_rollup(self, *, by: str = "filter", since: float | None = None) -> list[dict]:+ """Grouped ledger totals (see :func:`tracking.savings_rollup`)."""+ return tracking.savings_rollup(self._conn, by=by, since=since)++ # -- lifecycle ---------------------------------------------------------++ def close(self) -> None:+ self._conn.close()++ def __enter__(self) -> OmissionStore:+ return self++ def __exit__(self, *exc: object) -> None:+ self.close()+++def _filter_lines(content: str, query: str) -> str:+ """Lines of *content* matching *query* (regex if valid, else substring)."""+ import re++ try:+ pattern = re.compile(query)+ matcher = pattern.search+ except re.error:+ matcher = lambda line: query in line # noqa: E731+ matched = [line for line in content.splitlines() if matcher(line)]+ return "\n".join(matched)diff --git a/packages/core/src/repowise/core/distill/tracking.py b/packages/core/src/repowise/core/distill/tracking.pynew file mode 100644index 000000000..cad8e040d--- /dev/null+++ b/packages/core/src/repowise/core/distill/tracking.py@@ -0,0 +1,117 @@+"""Savings ledger — SQL for recording and summarizing distillation events.++Operates on the omissions sidecar connection (see ``store.py``); kept as free+functions so future surfaces (hook script, MCP budgeter) can record savings+without instantiating a full :class:`~repowise.core.distill.store.OmissionStore`.+"""++from __future__ import annotations++import sqlite3+import time+from typing import Any+++def record_saving(+ conn: sqlite3.Connection,+ *,+ filter_name: str,+ source: str,+ command: str | None,+ raw_tokens: int,+ distilled_tokens: int,+) -> None:+ """Append one distillation event to the savings ledger."""+ conn.execute(+ """+ INSERT INTO savings+ (created_at, filter, source, command, raw_tokens, distilled_tokens)+ VALUES (?, ?, ?, ?, ?, ?)+ """,+ (time.time(), filter_name, source, command, raw_tokens, distilled_tokens),+ )+ conn.commit()+++def savings_summary(+ conn: sqlite3.Connection, *, since: float | None = None+) -> dict[str, Any]:+ """Aggregate ledger totals, overall and per filter.++ *since* is a Unix timestamp; only events at or after it are counted.+ """+ where = " WHERE created_at >= ?" if since is not None else ""+ params: tuple[float, ...] = (since,) if since is not None else ()+ total_raw, total_distilled, events = conn.execute(+ "SELECT COALESCE(SUM(raw_tokens),0), COALESCE(SUM(distilled_tokens),0),"+ f" COUNT(*) FROM savings{where}",+ params,+ ).fetchone()+ per_filter = {+ row[0]: {+ "events": row[1],+ "raw_tokens": row[2],+ "distilled_tokens": row[3],+ "saved_tokens": row[2] - row[3],+ }+ for row in conn.execute(+ "SELECT filter, COUNT(*), SUM(raw_tokens), SUM(distilled_tokens)"+ f" FROM savings{where} GROUP BY filter ORDER BY SUM(raw_tokens) DESC",+ params,+ )+ }+ return {+ "events": events,+ "raw_tokens": total_raw,+ "distilled_tokens": total_distilled,+ "saved_tokens": total_raw - total_distilled,+ "per_filter": per_filter,+ }+++#: Grouping dimensions accepted by :func:`savings_rollup`. ``day`` buckets by+#: the event's local calendar date; ``filter``/``source`` group on the raw+#: ledger columns.+ROLLUP_DIMENSIONS: tuple[str, ...] = ("filter", "day", "source")++_ROLLUP_COLUMNS = {+ "filter": "filter",+ "source": "source",+ "day": "date(created_at, 'unixepoch', 'localtime')",+}+++def savings_rollup(+ conn: sqlite3.Connection,+ *,+ by: str = "filter",+ since: float | None = None,+) -> list[dict[str, Any]]:+ """Grouped ledger totals — one row per *by* bucket.++ *by* is one of :data:`ROLLUP_DIMENSIONS`. Rows carry ``group``,+ ``events``, ``raw_tokens``, ``distilled_tokens``, ``saved_tokens``.+ ``day`` rollups are ordered chronologically; the rest by tokens saved,+ descending. *since* is a Unix timestamp lower bound.+ """+ if by not in _ROLLUP_COLUMNS:+ raise ValueError(f"Unknown rollup dimension {by!r}; expected one of {ROLLUP_DIMENSIONS}")+ group_col = _ROLLUP_COLUMNS[by]+ where = " WHERE created_at >= ?" if since is not None else ""+ params: tuple[float, ...] = (since,) if since is not None else ()+ order = "1 ASC" if by == "day" else "SUM(raw_tokens - distilled_tokens) DESC"+ rows = conn.execute(+ f"SELECT {group_col}, COUNT(*), SUM(raw_tokens), SUM(distilled_tokens)"+ f" FROM savings{where} GROUP BY 1 ORDER BY {order}",+ params,+ ).fetchall()+ return [+ {+ "group": row[0],+ "events": row[1],+ "raw_tokens": row[2],+ "distilled_tokens": row[3],+ "saved_tokens": row[2] - row[3],+ }+ for row in rows+ ]diff --git a/packages/core/src/repowise/core/generation/cost_tracker.py b/packages/core/src/repowise/core/generation/cost_tracker.pyindex 80c9b2378..ebf357d9e 100644--- a/packages/core/src/repowise/core/generation/cost_tracker.py+++ b/packages/core/src/repowise/core/generation/cost_tracker.py@@ -59,6 +59,16 @@ def _get_pricing(model: str) -> dict[str, float]:return _FALLBACK_PRICING+def get_model_pricing(model: str) -> dict[str, float]:+ """Public pricing lookup — USD per 1M tokens, ``{"input": ..., "output": ...}``.++ Unknown models fall back to the default tier (with a one-time warning).+ Used outside generation (e.g. ``repowise saved``) to turn token counts+ into dollar estimates with the same table the cost ledger uses.+ """+ return _get_pricing(model)++# ---------------------------------------------------------------------------# CostTracker# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index c1d8140b1..4086316ec 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -112,6 +112,13 @@ This repo has the Repowise MCP server configured. The tools below answer questio- PR review → `get_risk(targets=[...], changed_files=[...])`; read the `directive` block first.**Verify when:** `_meta.stale_warning` is present, or `retrieval_quality` is `partial`/`weak`, or `search_method` is `bm25`. Otherwise trust the response and act on it.++### Output Distillation++- Prefer `repowise distill <cmd>` for noisy commands — test runs, builds, `git status`/`log`/`diff`, searches, file listings. It runs the command unchanged (exit code preserved) and prints a compact, errors-first rendering; every error line survives.+- Output may contain a marker like `[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]`. The omitted content is fully preserved — run `repowise expand <ref>` to retrieve it, or `repowise expand <ref> -q <regex>` for just the matching lines.+- Never re-run a command to see omitted output; expand the marker instead.+- For structure-level questions about a large indexed file ("what's in here", "which function handles X"), `get_context(["path"], include=["skeleton"])` returns the file with bodies elided — every signature plus the bodies of the most central symbols — at a fraction of the cost of a full Read.{% if data.build_commands %}### Codebase Conventionsdiff --git a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py b/packages/server/src/repowise/server/mcp_server/_budget/__init__.pynew file mode 100644index 000000000..ae50f99de--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_budget/__init__.py@@ -0,0 +1,35 @@+"""Shared output-budget enforcement for MCP tools.++Every MCP tool that trims its response to fit the transport token cap goes+through this package instead of rolling its own silent drop. Two pieces:++* :func:`truncate_to_budget` — the staged whole-response truncation strategy+ (originally built for ``get_context``), now the reference implementation.+* :class:`OmissionCollector` — captures whatever a tool drops, persists it to+ the durable omission store, and stamps the response with a+ ``[repowise#<ref>]`` marker plus ``_meta.omitted`` so the content stays+ recoverable via ``repowise expand <ref>`` or ``get_symbol("repowise#<ref>")``.++Tools that don't use the staged truncator (fixed per-list caps) use the+collector directly at their cap sites.+"""++from __future__ import annotations++from repowise.server.mcp_server._budget.budgeter import (+ CHAR_BUDGET,+ CHARS_PER_TOKEN,+ TOKEN_BUDGET,+ estimate_response_tokens,+ truncate_to_budget,+)+from repowise.server.mcp_server._budget.collector import OmissionCollector++__all__ = [+ "CHARS_PER_TOKEN",+ "CHAR_BUDGET",+ "TOKEN_BUDGET",+ "OmissionCollector",+ "estimate_response_tokens",+ "truncate_to_budget",+]diff --git a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.pynew file mode 100644index 000000000..96c4fb64f--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py@@ -0,0 +1,318 @@+"""Staged whole-response truncation — the shared budgeter.++Ported from ``tool_context/truncation.py`` (which now re-exports from here)+so every tool shares one budget strategy instead of ad-hoc caps. The+keep/drop decisions are byte-identical to the original implementation; the+only additions are (a) an optional :class:`OmissionCollector` that makes+every drop recoverable, and (b) a skeleton-stripping stage for the+``include=["skeleton"]`` blocks that did not exist when the original was+written.++The Claude Code harness rejects MCP tool results whose stringified form+exceeds ~10k tokens (it refuses to inline them and then refuses to Read the+spilled file). When that happens the agent falls back to multiple get_symbol+calls, each of which re-plays the cached system prompt — a significant cost+driver on dense files in long multi-turn agent sessions. We therefore cap+responses well below that ceiling: 8000 tokens leaves headroom for the+wrapping JSON envelope and the ``_meta`` fields the harness adds on top.++The estimator is intentionally dependency-free: 4 chars/token is the+widely-quoted average for English + code on BPE tokenizers and is within+~20% of tiktoken for typical wiki content. Precise counting is unnecessary+because we only need to stay comfortably under the hard limit.+"""++from __future__ import annotations++import json+import logging+from typing import Any++from repowise.server.mcp_server._budget.collector import OmissionCollector++logger = logging.getLogger(__name__)++TOKEN_BUDGET = 8000+CHARS_PER_TOKEN = 4+CHAR_BUDGET = TOKEN_BUDGET * CHARS_PER_TOKEN+++def estimate_response_tokens(obj: Any) -> int:+ """Cheap upper-bound token estimate for an arbitrary JSON-serialisable object.++ Serialises to compact JSON (the wire format the MCP layer eventually emits)+ and divides by ``CHARS_PER_TOKEN``. We use the serialised form — not just+ raw text fields — because structural JSON overhead (quotes, braces, field+ names) is non-trivial and is what the downstream tokenizer actually sees.+ """+ return len(json.dumps(obj, separators=(",", ":"), default=str)) // CHARS_PER_TOKEN+++# Heavy optional fields we can strip from a target's docs block without losing+# its identity. Ordering matters: earlier entries are dropped first because they+# carry the most bytes per unit of navigational value.+HEAVY_DOC_FIELDS: tuple[str, ...] = ("content_md", "documentation", "file_summary")+++def symbol_priority(sym: dict[str, Any], query_terms: set[str]) -> tuple[int, int, int]:+ """Return a sort key (higher = keep) for a symbol within a target.++ Priority order (language-agnostic — no Python-specific heuristics):+ 1. Exact name match against any user query term.+ 2. Substring / case-insensitive match against query terms.+ 3. Kind rank: classes/types outrank functions/methods which outrank the+ rest. This mirrors navigational usefulness across Python, TS, Go,+ Rust, C++, etc. where a type anchors a module more than a helper fn.+ 4. PageRank / centrality if present on the dict (forward-compatible —+ ``get_context`` doesn't currently populate it but ``_resolve_one_target``+ may in the future).+ """+ name = (sym.get("name") or "").lower()+ exact = 1 if name and name in query_terms else 0+ fuzzy = 1 if any(t and t in name for t in query_terms) else 0+ kind = (sym.get("kind") or "").lower()+ kind_rank = {+ "class": 3,+ "interface": 3,+ "struct": 3,+ "trait": 3,+ "type": 3,+ "enum": 3,+ "function": 2,+ "method": 2,+ }.get(kind, 1)+ centrality = int((sym.get("pagerank") or sym.get("centrality") or 0) * 1000)+ return (exact * 10 + fuzzy * 5 + kind_rank, centrality, -len(json.dumps(sym, default=str)))+++def query_terms_for(target: str) -> set[str]:+ """Derive cheap query terms from a target string for symbol prioritisation.++ ``get_context`` has no explicit query argument, so we fall back to the+ target identifier itself — the tail of a file path, or the raw symbol name.+ This is deliberately coarse: it just nudges symbol retention toward the+ thing the caller asked about.+ """+ tail = target.rsplit("/", 1)[-1].lower()+ # Strip common extension if present (language-agnostic: split once on '.').+ if "." in tail:+ tail = tail.rsplit(".", 1)[0]+ return {t for t in (tail, target.lower()) if t}+++def truncate_to_budget(+ result: dict[str, Any],+ char_budget: int = CHAR_BUDGET,+ *,+ collector: OmissionCollector | None = None,+) -> dict[str, Any]:+ """Cap a targets-shaped response at roughly ``TOKEN_BUDGET`` tokens.++ Strategy (applied in order, stopping as soon as the budget is met):++ 1. **Strip heavy optional doc fields** (``content_md``, ``documentation``,+ ``file_summary``) from each target. These are 1-2k tokens apiece and+ duplicate information the agent can re-request via ``full_doc``.+ 1.5. **Strip skeleton texts**, largest first. A skeleton block can be ~2k+ tokens per target; its text is replaced in-place by an omission+ marker (when a collector is present) so it stays one call away.+ 2. **Shrink symbol lists within each target**, keeping the highest-priority+ symbols per ``symbol_priority``. This preserves the navigational index+ (names, signatures, line numbers) while dropping bulk docstrings.+ 3. **Drop whole targets** from the tail of the list. Per spec we prefer+ keeping fewer full-fidelity targets over many stubs, so once symbols+ can't shrink further we evict entire targets rather than gutting them.++ Adds ``truncated: bool``, ``dropped_targets: list[str]``, and+ ``dropped_symbols: dict[target, list[name]]`` top-level fields — additive+ only, existing callers are unaffected.++ With a *collector*, every dropped piece of content is also captured and+ persisted, and the response gains ``omission_marker`` + ``_meta.omitted``+ (see :class:`OmissionCollector`). Without one, behaviour is byte-identical+ to the original silent-drop implementation.++ Edge cases:+ * Empty ``targets`` → returns unchanged with ``truncated=False``.+ * A single target whose symbol list alone busts the budget → we reduce+ symbols down to 1 and accept the overshoot rather than returning an+ empty response. The ``truncated`` flag still fires.+ * Targets that carry an ``error`` field (not-found) are cheap and are+ preserved unless literally nothing else fits.+ """+ try:+ result = _run_stages(result, char_budget, collector)+ finally:+ if collector is not None:+ collector.attach(result)++ if result.get("truncated"):+ logger.info(+ "response truncated to budget",+ extra={+ "char_budget": char_budget,+ "token_budget": TOKEN_BUDGET,+ "final_chars": len(json.dumps(result, separators=(",", ":"), default=str)),+ "dropped_targets": result["dropped_targets"],+ "dropped_symbol_counts": {k: len(v) for k, v in result["dropped_symbols"].items()},+ },+ )+ return result+++def _run_stages(+ result: dict[str, Any],+ char_budget: int,+ collector: OmissionCollector | None,+) -> dict[str, Any]:+ result.setdefault("truncated", False)+ result.setdefault("dropped_targets", [])+ result.setdefault("dropped_symbols", {})++ targets: dict[str, Any] = result.get("targets") or {}+ if not targets:+ return result++ def _size() -> int:+ return len(json.dumps(result, separators=(",", ":"), default=str))++ if _size() <= char_budget:+ return result++ # Stage 1: strip heavy optional doc fields across all targets.+ for name, tgt in targets.items():+ docs = tgt.get("docs") if isinstance(tgt, dict) else None+ if not isinstance(docs, dict):+ continue+ for field in HEAVY_DOC_FIELDS:+ if field in docs:+ value = docs.pop(field, None)+ if collector is not None and value:+ collector.add(f"{name} :: {field}", value)+ result["truncated"] = True+ if _size() <= char_budget:+ return result++ # Stage 1.5: strip skeleton texts, largest first. The skeleton block's+ # metadata (token counts, bodies_kept) survives; only the bulky text is+ # swapped for its marker so the agent knows exactly what it lost and how+ # to get it back without re-running the whole call.+ def _skeleton_cost(item: tuple[str, Any]) -> int:+ tgt = item[1]+ skel = tgt.get("skeleton") if isinstance(tgt, dict) else None+ text = skel.get("text") if isinstance(skel, dict) else None+ return len(text) if isinstance(text, str) else 0++ for tgt_name, tgt in sorted(targets.items(), key=_skeleton_cost, reverse=True):+ skel = tgt.get("skeleton") if isinstance(tgt, dict) else None+ if not isinstance(skel, dict):+ continue+ text = skel.get("text")+ if not isinstance(text, str) or not text:+ continue+ marker = collector.add_inline(f"skeleton of {tgt_name}", text) if collector else None+ if marker:+ skel["text"] = marker+ else:+ skel.pop("text", None)+ skel["note"] = (+ "Skeleton text dropped to fit the response budget; re-request with fewer targets."+ )+ skel["omitted"] = True+ result["truncated"] = True+ if _size() <= char_budget:+ return result++ # Stage 2: prioritise symbols within each target. We iterate from the+ # largest target down so the biggest offenders shrink first.+ def _target_cost(item: tuple[str, Any]) -> int:+ return len(json.dumps(item[1], default=str))++ for tgt_name, tgt in sorted(targets.items(), key=_target_cost, reverse=True):+ docs = tgt.get("docs") if isinstance(tgt, dict) else None+ if not isinstance(docs, dict):+ continue+ symbols = docs.get("symbols")+ if not isinstance(symbols, list) or not symbols:+ continue+ query_terms = query_terms_for(tgt_name)+ ordered = sorted(symbols, key=lambda s: symbol_priority(s, query_terms), reverse=True)++ # Per-symbol greedy fit. The cost of the whole response with a symbol+ # list ``S`` is exactly:+ # base + sum(cost(s) for s in S) + max(0, len(S) - 1)+ # where ``base`` is the response size with this target's ``symbols``+ # emptied and ``cost(s)`` is the symbol's compact-JSON length. Both are+ # context-independent under the compact separators we serialise with,+ # so we precompute each symbol's cost ONCE and track a running sum+ # instead of re-serialising the entire response per candidate symbol+ # (the old O(targets x symbols^2) behaviour). The keep/drop decision is+ # byte-for-byte identical to the previous ``_size()``-per-symbol loop.+ costs = [len(json.dumps(s, separators=(",", ":"), default=str)) for s in ordered]+ docs["symbols"] = []+ base = _size()+ kept: list[dict[str, Any]] = []+ dropped: list[str] = []+ dropped_syms: list[dict[str, Any]] = []+ sum_kept = 0+ for sym, cost in zip(ordered, costs, strict=True):+ # Tentative size if we add this symbol to the current kept set:+ # the +len(kept) term is the comma separators for kept+1 entries.+ tentative = base + sum_kept + cost + len(kept)+ if tentative <= char_budget:+ kept.append(sym)+ sum_kept += cost+ else:+ dropped.append(sym.get("name") or "<anonymous>")+ dropped_syms.append(sym)+ if not kept and ordered:+ # Edge case: a single symbol is larger than the budget. Keep one+ # (truncating its docstring) rather than returning zero symbols —+ # the caller at least learns the target resolved.+ head = dict(ordered[0])+ if isinstance(head.get("docstring"), str):+ head["docstring"] = head["docstring"][:200]+ kept = [head]+ dropped = [s.get("name") or "<anonymous>" for s in ordered[1:]]+ # The kept head lost its docstring tail too — capture the full+ # original alongside the genuinely dropped tail.+ dropped_syms = list(ordered)+ docs["symbols"] = kept+ if dropped:+ result["dropped_symbols"][tgt_name] = dropped+ result["truncated"] = True+ if collector is not None and dropped_syms:+ collector.add(+ f"{tgt_name} :: symbols dropped from response",+ "\n".join(+ json.dumps(s, separators=(",", ":"), default=str) for s in dropped_syms+ ),+ )+ if _size() <= char_budget:+ return result++ # Stage 3: drop whole targets, largest first, until we fit. Prefer to keep+ # error-only targets (they're tiny and signal "not found" to the caller).+ def _evictable_order() -> list[str]:+ items = list(targets.items())+ items.sort(+ key=lambda kv: (+ 0 if isinstance(kv[1], dict) and "error" in kv[1] else 1,+ len(json.dumps(kv[1], default=str)),+ ),+ reverse=True,+ )+ return [k for k, _ in items]++ for name in _evictable_order():+ if len(targets) <= 1:+ break+ evicted = targets.pop(name, None)+ if collector is not None and evicted is not None:+ collector.add(f"dropped target {name}", evicted)+ result["dropped_targets"].append(name)+ result["truncated"] = True+ if _size() <= char_budget:+ break++ return resultdiff --git a/packages/server/src/repowise/server/mcp_server/_budget/collector.py b/packages/server/src/repowise/server/mcp_server/_budget/collector.pynew file mode 100644index 000000000..09184ec68--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_budget/collector.py@@ -0,0 +1,196 @@+"""OmissionCollector — reversible drops for MCP tool responses.++When a tool trims its response to fit the transport budget, the dropped+content is handed to a collector instead of vanishing. The collector persists+it to the same durable omission store the CLI/hook surfaces use+(``.repowise/omissions/omissions.db``) and stamps the response with the+standard ``[repowise#<ref>]`` marker plus a ``_meta.omitted`` block, so any+truncation an agent sees is recoverable:++* ``repowise expand <ref>`` from a shell, or+* ``get_symbol("repowise#<ref>")`` for shell-less MCP clients.++Failure posture mirrors the distill engine: the store is best-effort. If a+write fails, the tool falls back to the pre-existing silent-drop behaviour —+a degraded response is always preferred over a failed one. Content is stored+BEFORE any marker is rendered, so a marker can never dangle.++Lifecycle: the underlying SQLite handle is opened lazily on the first drop+and closed in :meth:`attach`. The MCP server is long-running, but truncation+events are rare and writes are small, so open-per-event avoids holding a WAL+handle that would contend with hook-side writers between events.+"""++from __future__ import annotations++import contextlib+import json+import logging+from pathlib import Path+from typing import Any++from repowise.core.distill.budget import estimate_tokens+from repowise.core.distill.markers import render_marker+from repowise.core.distill.store import OmissionStore, default_store_path++logger = logging.getLogger(__name__)++#: One sentence, repeated verbatim in every ``_meta.omitted`` block, telling+#: shell-less clients (e.g. Claude Desktop) how to recover without a CLI.+_RESTORE_HINT = (+ "Run `repowise expand <ref>` from the repo, or call "+ 'get_symbol("repowise#<ref>", query=...) to retrieve the omitted content.'+)++_DOC_SECTION_RULE = "==== {label} ===="+++def render_chunk(label: str, value: Any) -> str:+ """Render one dropped value as line-oriented text for the omission doc.++ Strings pass through verbatim; everything else becomes indented JSON so+ ``expand --query`` line filtering stays useful on structured drops.+ """+ if isinstance(value, str):+ return value+ return json.dumps(value, indent=1, default=str)+++class OmissionCollector:+ """Collects content dropped from one MCP tool response.++ Two capture modes:++ * :meth:`add` — queue a chunk into a single combined omission document,+ stored at :meth:`attach` time with one marker for the whole response.+ * :meth:`add_inline` — store a chunk immediately as its own row and+ return its marker, for drops whose marker must replace the content+ in-place (e.g. a stripped skeleton text).++ ``store_path`` overrides the resolved store location (tests). Otherwise+ the store is resolved from ``repo_root`` exactly like the CLI: the repo's+ own ``.repowise/`` when present, the user-level fallback otherwise.+ """++ def __init__(+ self,+ tool: str,+ repo_root: str | Path | None = None,+ *,+ store_path: str | Path | None = None,+ ) -> None:+ self.tool = tool+ if store_path is not None:+ self._store_path = Path(store_path)+ else:+ self._store_path = default_store_path(Path(repo_root) if repo_root else None)+ self._chunks: list[tuple[str, str]] = []+ self._refs: list[str] = []+ self._omitted_tokens = 0+ self._store: OmissionStore | None = None+ self._store_failed = False++ # -- capture -------------------------------------------------------------++ def add(self, label: str, value: Any) -> None:+ """Queue a dropped chunk for the combined omission document."""+ text = render_chunk(label, value)+ if text:+ self._chunks.append((label, text))++ def add_inline(self, label: str, content: str) -> str | None:+ """Store *content* as its own row and return its marker.++ Returns ``None`` when the store is unavailable — the caller must then+ fall back to its pre-collector drop behaviour (content stored before+ marker rendered; no row, no marker).+ """+ if not content:+ return None+ ref = self._put(content)+ if ref is None:+ return None+ tokens = estimate_tokens(content)+ self._omitted_tokens += tokens+ return render_marker(ref, content.count("\n") + 1, tokens)++ @property+ def empty(self) -> bool:+ """True when nothing has been captured (queued or stored)."""+ return not self._chunks and not self._refs++ # -- finalisation ----------------------------------------------------------++ def attach(self, response: dict[str, Any]) -> None:+ """Persist queued chunks and stamp *response* with refs and markers.++ Adds (only when something was captured AND stored successfully):+ * ``response["omission_marker"]`` — marker for the combined document+ of queued chunks, if any;+ * ``response["_meta"]["omitted"]`` — ``{refs, tokens, restore}``+ covering every ref this collector produced.++ Never raises; always closes the store handle.+ """+ try:+ if self._chunks:+ doc = self._render_doc()+ ref = self._put(doc)+ if ref is not None:+ tokens = sum(estimate_tokens(text) for _, text in self._chunks)+ self._omitted_tokens += tokens+ response["omission_marker"] = render_marker(ref, doc.count("\n") + 1, tokens)+ if self._refs:+ meta = response.setdefault("_meta", {})+ meta["omitted"] = {+ "refs": list(self._refs),+ "tokens": self._omitted_tokens,+ "restore": _RESTORE_HINT,+ }+ except Exception: # pragma: no cover - defensive+ logger.warning("omission collector attach failed", exc_info=True)+ finally:+ self.close()++ def close(self) -> None:+ if self._store is not None:+ with contextlib.suppress(Exception):+ self._store.close()+ self._store = None++ # -- internals -------------------------------------------------------------++ def _render_doc(self) -> str:+ head = (+ f"[repowise omissions] tool={self.tool}\n"+ "Content below was dropped from an MCP response to fit the "+ "transport budget; sections are verbatim.\n"+ )+ parts = [head]+ for label, text in self._chunks:+ parts.append(_DOC_SECTION_RULE.format(label=label))+ parts.append(text)+ return "\n".join(parts)++ def _put(self, content: str) -> str | None:+ """Write *content* to the store; None on any failure (degrade silently)."""+ if self._store_failed:+ return None+ try:+ if self._store is None:+ self._store = OmissionStore(self._store_path)+ ref = self._store.put(+ content,+ source=f"mcp:{self.tool}",+ original_tokens=estimate_tokens(content),+ kept_tokens=0,+ )+ except Exception:+ logger.warning(+ "omission store write failed; falling back to silent drop",+ exc_info=True,+ )+ self._store_failed = True+ return None+ self._refs.append(ref)+ return refdiff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex bb81b0b45..da037b11f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -16,6 +16,7 @@ Optional ``include`` parameter widens the response:- include=["metrics"] → PageRank, betweenness, percentile ranks- include=["community"] → community membership + neighbors- include=["decisions"] → full decision records (default returns titles only)+ - include=["skeleton"] → body-elided file rendering (signatures + top-PageRank bodies)This module is the orchestrator; single-target resolution lives in``targets`` and the budget cap in ``truncation``.@@ -29,6 +30,7 @@ from typing import Anyfrom repowise.core.persistence.database import get_sessionfrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._budget import OmissionCollector, truncate_to_budgetfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -38,7 +40,6 @@ from repowise.server.mcp_server._helpers import (from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import context_hint as _context_hintfrom repowise.server.mcp_server.tool_context.targets import _resolve_one_target-from repowise.server.mcp_server.tool_context.truncation import _truncate_to_budget@mcp.tool()@@ -68,6 +69,10 @@ async def get_context(- "metrics": PageRank, betweenness centrality, percentile ranks- "community": architectural community membership + neighbors- "decisions": full decision records (default returns titles only)+ - "skeleton": the file with bodies elided — every signature kept, the+ bodies of the highest-PageRank symbols inlined under a+ token budget. A fraction of the cost of Read for+ structure-level questions (file targets only).Example: get_context(["src/auth/service.py", "src/auth/middleware.py"])Example: get_context(["src/auth/service.py::verify_token"], include=["callers"])@@ -84,7 +89,7 @@ async def get_context(# Default to docs + freshness when include is omitted. Freshness is# critical for the agent to detect stale index data. The other blocks- # (ownership/last_change/decisions) are 200–500 bytes each and bloat+ # (ownership/last_change/decisions) are 200-500 bytes each and bloat# every subsequent agent turn via cache replay. Callers that want them# must pass include explicitly.include_set = set(include) if include else {"docs", "freshness"}@@ -106,6 +111,7 @@ async def get_context(include_set,compact,exclude_spec=exclude_spec,+ repo_root=ctx.path,)for t in targets]@@ -164,5 +170,8 @@ async def get_context(if cross_repo:target_data["cross_repo"] = cross_repo- # Enforce the global token cap. See ``_truncate_to_budget`` for strategy.- return _truncate_to_budget(response)+ # Enforce the global token cap. Anything dropped is persisted via the+ # collector so a truncated response always carries expandable+ # ``[repowise#<ref>]`` markers instead of silently losing content.+ collector = OmissionCollector("get_context", repo_root=ctx.path)+ return truncate_to_budget(response, collector=collector)diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.pyindex 7d1155a86..5fef6ef4b 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py@@ -341,3 +341,93 @@ async def _resolve_health("branch_coverage_pct": metric.branch_coverage_pct,}result_data["health"] = health+++async def _resolve_skeleton(+ session: AsyncSession,+ repository: Repository,+ target: str,+ target_type: str | None,+ result_data: dict[str, Any],+ *,+ repo_root: Any = None,+) -> None:+ """Resolve ``include=["skeleton"]`` — a body-elided rendering of one file.++ Slices the on-disk source on the line bounds persisted at index time+ (zero parsing), keeping every signature and the bodies of the+ highest-PageRank symbols under a token budget. File targets only —+ a symbol's "skeleton" is just its signature, which the triage card+ already carries.+ """+ if target_type != "file":+ result_data["skeleton"] = {"error": "skeleton requires a file target; pass the file path."}+ return+ if not repo_root:+ result_data["skeleton"] = {"error": "MCP server has no repo path configured."}+ return++ from pathlib import Path++ from repowise.core.distill.skeleton import SkeletonSymbol, build_skeleton+ from repowise.core.persistence.models import WikiSymbol++ repo_id = repository.id+ res = await session.execute(+ select(WikiSymbol).where(+ WikiSymbol.repository_id == repo_id,+ WikiSymbol.file_path == target,+ )+ )+ rows = list(res.scalars().all())++ # Symbol-node PageRank is the importance signal for smart body retention.+ pr_res = await session.execute(+ select(GraphNode.name, GraphNode.pagerank).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "symbol",+ GraphNode.file_path == target,+ )+ )+ pagerank = {name: pr or 0.0 for name, pr in pr_res.all() if name}++ repo_path = Path(str(repo_root))+ abs_path = (repo_path / target).resolve()+ try:+ abs_path.relative_to(repo_path.resolve())+ source = abs_path.read_text(encoding="utf-8", errors="replace")+ except (OSError, ValueError):+ result_data["skeleton"] = {+ "error": "Source file could not be read; it may have moved since indexing."+ }+ return++ symbols = [+ SkeletonSymbol(+ name=r.name,+ kind=r.kind,+ start_line=r.start_line,+ end_line=r.end_line,+ signature=r.signature,+ importance=pagerank.get(r.name, 0.0),+ )+ for r in rows+ ]+ result = build_skeleton(+ source,+ symbols,+ mode="smart",+ hotspot=bool(result_data.get("hotspot")),+ )+ result_data["skeleton"] = {+ "mode": result.mode,+ "tokens": result.skeleton_tokens,+ "full_tokens": result.full_tokens,+ "pct_of_full": round(result.pct_of_full, 1),+ "bodies_kept": list(result.bodies_kept),+ "text": result.text,+ }+ if result.mode == "raw":+ result_data["skeleton"]["note"] = (+ "No usable symbol bounds for this file — returned source as-is."+ )diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.pyindex 17901ea70..bd793b8ce 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py@@ -36,6 +36,7 @@ from repowise.server.mcp_server.tool_context.enrichment import (_resolve_community,_resolve_health,_resolve_metrics,+ _resolve_skeleton,)from repowise.server.mcp_server.tool_context.kg import (_classify_file_role,@@ -74,6 +75,7 @@ async def _resolve_one_target(compact: bool = False,*,exclude_spec: Any = None,+ repo_root: Any = None,) -> dict:"""Resolve a single target and return its full context."""repo_id = repository.id@@ -349,10 +351,8 @@ async def _resolve_one_target(gn = res.scalar_one_or_none()if gn and gn.community_id is not None:_cmeta: dict[str, Any] = {}- try:+ with contextlib.suppress(json.JSONDecodeError, TypeError):_cmeta = json.loads(gn.community_meta_json or "{}")- except (json.JSONDecodeError, TypeError):- passdocs["community"] = {"id": gn.community_id,"label": _cmeta.get("label", ""),@@ -670,4 +670,10 @@ async def _resolve_one_target(if include and "health" in include:await _resolve_health(session, repository, target, target_type, result_data)+ # --- Skeleton (distill) ---+ if include and "skeleton" in include:+ await _resolve_skeleton(+ session, repository, target, target_type, result_data, repo_root=repo_root+ )+return result_datadiff --git a/packages/server/src/repowise/server/mcp_server/tool_context/truncation.py b/packages/server/src/repowise/server/mcp_server/tool_context/truncation.pyindex 33103077e..0136b76c2 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/truncation.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/truncation.py@@ -1,242 +1,46 @@-"""Output-size budgeting for get_context.+"""Output-size budgeting for get_context — thin shim over the shared budgeter.-The Claude Code harness rejects MCP tool results whose stringified form exceeds-~10k tokens, so get_context caps its response well below that. This module owns-the budget constants and the truncation strategy.+The staged truncation strategy that used to live here is now the+reference implementation for ALL tools and lives in+``repowise.server.mcp_server._budget``. This module keeps the historical+names importable (tests and older callers import ``_truncate_to_budget`` and+friends from here) and adds nothing of its own."""from __future__ import annotations-import json-import logging-from typing import Any--logger = logging.getLogger(__name__)--# --- Output size budget --------------------------------------------------------# The Claude Code harness rejects MCP tool results whose stringified form exceeds-# ~10k tokens (it refuses to inline them and then refuses to Read the spilled-# file). When that happens the agent falls back to multiple get_symbol calls,-# each of which re-plays the cached system prompt — a significant cost driver-# on dense files in long multi-turn agent sessions.-#-# We therefore cap get_context output well below that ceiling. 8000 tokens-# leaves headroom for the wrapping JSON envelope and _meta fields the harness-# adds on top. The estimator is intentionally dependency-free: 4 chars/token is-# the widely-quoted average for English + code on BPE tokenizers and is within-# ~20% of tiktoken for typical wiki content. Precise counting is unnecessary-# because we only need to stay comfortably under the hard limit.-_TOKEN_BUDGET = 8000-_CHARS_PER_TOKEN = 4-_CHAR_BUDGET = _TOKEN_BUDGET * _CHARS_PER_TOKEN---def _estimate_tokens(obj: Any) -> int:- """Cheap upper-bound token estimate for an arbitrary JSON-serialisable object.-- Serialises to compact JSON (the wire format the MCP layer eventually emits)- and divides by ``_CHARS_PER_TOKEN``. We use the serialised form — not just- raw text fields — because structural JSON overhead (quotes, braces, field- names) is non-trivial and is what the downstream tokenizer actually sees.- """- return len(json.dumps(obj, separators=(",", ":"), default=str)) // _CHARS_PER_TOKEN---# Heavy optional fields we can strip from a target's docs block without losing-# its identity. Ordering matters: earlier entries are dropped first because they-# carry the most bytes per unit of navigational value.-_HEAVY_DOC_FIELDS: tuple[str, ...] = ("content_md", "documentation", "file_summary")---def _symbol_priority(sym: dict[str, Any], query_terms: set[str]) -> tuple[int, int, int]:- """Return a sort key (higher = keep) for a symbol within a target.-- Priority order (language-agnostic — no Python-specific heuristics):- 1. Exact name match against any user query term.- 2. Substring / case-insensitive match against query terms.- 3. Kind rank: classes/types outrank functions/methods which outrank the- rest. This mirrors navigational usefulness across Python, TS, Go,- Rust, C++, etc. where a type anchors a module more than a helper fn.- 4. PageRank / centrality if present on the dict (forward-compatible —- ``get_context`` doesn't currently populate it but ``_resolve_one_target``- may in the future).- """- name = (sym.get("name") or "").lower()- exact = 1 if name and name in query_terms else 0- fuzzy = 1 if any(t and t in name for t in query_terms) else 0- kind = (sym.get("kind") or "").lower()- kind_rank = {- "class": 3,- "interface": 3,- "struct": 3,- "trait": 3,- "type": 3,- "enum": 3,- "function": 2,- "method": 2,- }.get(kind, 1)- centrality = int((sym.get("pagerank") or sym.get("centrality") or 0) * 1000)- return (exact * 10 + fuzzy * 5 + kind_rank, centrality, -len(json.dumps(sym, default=str)))---def _query_terms_for(target: str) -> set[str]:- """Derive cheap query terms from a target string for symbol prioritisation.-- ``get_context`` has no explicit query argument, so we fall back to the- target identifier itself — the tail of a file path, or the raw symbol name.- This is deliberately coarse: it just nudges symbol retention toward the- thing the caller asked about.- """- tail = target.rsplit("/", 1)[-1].lower()- # Strip common extension if present (language-agnostic: split once on '.').- if "." in tail:- tail = tail.rsplit(".", 1)[0]- return {t for t in (tail, target.lower()) if t}---def _truncate_to_budget(- result: dict[str, Any],- char_budget: int = _CHAR_BUDGET,-) -> dict[str, Any]:- """Cap the ``get_context`` response at roughly ``_TOKEN_BUDGET`` tokens.-- Strategy (applied in order, stopping as soon as the budget is met):-- 1. **Strip heavy optional doc fields** (``content_md``, ``documentation``,- ``file_summary``) from each target. These are 1–2k tokens apiece and- duplicate information the agent can re-request via ``full_doc``.- 2. **Shrink symbol lists within each target**, keeping the highest-priority- symbols per ``_symbol_priority``. This preserves the navigational index- (names, signatures, line numbers) while dropping bulk docstrings.- 3. **Drop whole targets** from the tail of the list. Per spec we prefer- keeping fewer full-fidelity targets over many stubs, so once symbols- can't shrink further we evict entire targets rather than gutting them.-- Adds ``truncated: bool``, ``dropped_targets: list[str]``, and- ``dropped_symbols: dict[target, list[name]]`` top-level fields — additive- only, existing callers are unaffected.-- Edge cases:- * Empty ``targets`` → returns unchanged with ``truncated=False``.- * A single target whose symbol list alone busts the budget → we reduce- symbols down to 1 and accept the overshoot rather than returning an- empty response. The ``truncated`` flag still fires.- * Targets that carry an ``error`` field (not-found) are cheap and are- preserved unless literally nothing else fits.- """- result.setdefault("truncated", False)- result.setdefault("dropped_targets", [])- result.setdefault("dropped_symbols", {})-- targets: dict[str, Any] = result.get("targets") or {}- if not targets:- return result-- def _size() -> int:- return len(json.dumps(result, separators=(",", ":"), default=str))-- if _size() <= char_budget:- return result-- # Stage 1: strip heavy optional doc fields across all targets.- for name, tgt in targets.items():- docs = tgt.get("docs") if isinstance(tgt, dict) else None- if not isinstance(docs, dict):- continue- for field in _HEAVY_DOC_FIELDS:- if field in docs:- docs.pop(field, None)- result["truncated"] = True- if _size() <= char_budget:- return result-- # Stage 2: prioritise symbols within each target. We iterate from the- # largest target down so the biggest offenders shrink first.- def _target_cost(item: tuple[str, Any]) -> int:- return len(json.dumps(item[1], default=str))-- for tgt_name, tgt in sorted(targets.items(), key=_target_cost, reverse=True):- docs = tgt.get("docs") if isinstance(tgt, dict) else None- if not isinstance(docs, dict):- continue- symbols = docs.get("symbols")- if not isinstance(symbols, list) or not symbols:- continue- query_terms = _query_terms_for(tgt_name)- ordered = sorted(symbols, key=lambda s: _symbol_priority(s, query_terms), reverse=True)-- # Per-symbol greedy fit. The cost of the whole response with a symbol- # list ``S`` is exactly:- # base + sum(cost(s) for s in S) + max(0, len(S) - 1)- # where ``base`` is the response size with this target's ``symbols``- # emptied and ``cost(s)`` is the symbol's compact-JSON length. Both are- # context-independent under the compact separators we serialise with,- # so we precompute each symbol's cost ONCE and track a running sum- # instead of re-serialising the entire response per candidate symbol- # (the old O(targets × symbols²) behaviour). The keep/drop decision is- # byte-for-byte identical to the previous ``_size()``-per-symbol loop.- costs = [len(json.dumps(s, separators=(",", ":"), default=str)) for s in ordered]- docs["symbols"] = []- base = _size()- kept: list[dict[str, Any]] = []- dropped: list[str] = []- sum_kept = 0- for sym, cost in zip(ordered, costs, strict=True):- # Tentative size if we add this symbol to the current kept set:- # the +len(kept) term is the comma separators for kept+1 entries.- tentative = base + sum_kept + cost + len(kept)- if tentative <= char_budget:- kept.append(sym)- sum_kept += cost- else:- dropped.append(sym.get("name") or "<anonymous>")- if not kept and ordered:- # Edge case: a single symbol is larger than the budget. Keep one- # (truncating its docstring) rather than returning zero symbols —- # the caller at least learns the target resolved.- head = dict(ordered[0])- if isinstance(head.get("docstring"), str):- head["docstring"] = head["docstring"][:200]- kept = [head]- dropped = [s.get("name") or "<anonymous>" for s in ordered[1:]]- docs["symbols"] = kept- if dropped:- result["dropped_symbols"][tgt_name] = dropped- result["truncated"] = True- if _size() <= char_budget:- return result-- # Stage 3: drop whole targets, largest first, until we fit. Prefer to keep- # error-only targets (they're tiny and signal "not found" to the caller).- def _evictable_order() -> list[str]:- items = list(targets.items())- items.sort(- key=lambda kv: (- 0 if isinstance(kv[1], dict) and "error" in kv[1] else 1,- len(json.dumps(kv[1], default=str)),- ),- reverse=True,- )- return [k for k, _ in items]-- for name in _evictable_order():- if len(targets) <= 1:- break- targets.pop(name, None)- result["dropped_targets"].append(name)- result["truncated"] = True- if _size() <= char_budget:- break-- if result["truncated"]:- logger.info(- "get_context truncated to budget",- extra={- "char_budget": char_budget,- "token_budget": _TOKEN_BUDGET,- "final_chars": _size(),- "dropped_targets": result["dropped_targets"],- "dropped_symbol_counts": {k: len(v) for k, v in result["dropped_symbols"].items()},- },- )- return result+from repowise.server.mcp_server._budget.budgeter import (+ CHAR_BUDGET as _CHAR_BUDGET,+)+from repowise.server.mcp_server._budget.budgeter import (+ CHARS_PER_TOKEN as _CHARS_PER_TOKEN,+)+from repowise.server.mcp_server._budget.budgeter import (+ HEAVY_DOC_FIELDS as _HEAVY_DOC_FIELDS,+)+from repowise.server.mcp_server._budget.budgeter import (+ TOKEN_BUDGET as _TOKEN_BUDGET,+)+from repowise.server.mcp_server._budget.budgeter import (+ estimate_response_tokens as _estimate_tokens,+)+from repowise.server.mcp_server._budget.budgeter import (+ query_terms_for as _query_terms_for,+)+from repowise.server.mcp_server._budget.budgeter import (+ symbol_priority as _symbol_priority,+)+from repowise.server.mcp_server._budget.budgeter import (+ truncate_to_budget as _truncate_to_budget,+)++__all__ = [+ "_CHARS_PER_TOKEN",+ "_CHAR_BUDGET",+ "_HEAVY_DOC_FIELDS",+ "_TOKEN_BUDGET",+ "_estimate_tokens",+ "_query_terms_for",+ "_symbol_priority",+ "_truncate_to_budget",+]diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex 35009e548..be7dcbe19 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -12,7 +12,9 @@ from repowise.core.persistence.models import (DeadCodeFinding,GitMetadata,)+from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -22,7 +24,6 @@ from repowise.server.mcp_server._helpers import (filter_rows_by_attr,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.core.registry import mcp_tool_registry as mcp@mcp.tool()@@ -92,10 +93,10 @@ async def get_dead_code(# MCP transport rejects payloads above ~25k tokens. A single serialized# finding is ~400 chars, so 3 tiers x ~25 findings keeps us under budget# with headroom for summary/grouping fields.- _MAX_PER_TIER = 25+ max_per_tier = 25requested_limit = limit- limit = min(max(limit, 1), _MAX_PER_TIER)- limit_clamped = requested_limit > _MAX_PER_TIER+ limit = min(max(limit, 1), max_per_tier)+ limit_clamped = requested_limit > max_per_tier# --- repo="all": aggregate dead code across all repos ---if repo == "all":@@ -228,7 +229,7 @@ async def get_dead_code(if limit_clamped:result_ws["limit_note"] = (f"Requested limit={requested_limit} exceeded the MCP transport budget "- f"and was clamped to {_MAX_PER_TIER}. Use tier/directory/owner filters "+ f"and was clamped to {max_per_tier}. Use tier/directory/owner filters ""or paginate to see more findings.")result_ws["_meta"] = _build_meta()@@ -236,6 +237,9 @@ async def get_dead_code(# --- Single repo path ---ctx = await _resolve_repo_context(repo)+ # Findings beyond the per-tier limit are persisted, not silently dropped —+ # the response carries an expandable [repowise#<ref>] marker for them.+ collector = OmissionCollector("get_dead_code", repo_root=ctx.path)async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)@@ -290,7 +294,7 @@ async def get_dead_code(]# --- Build tiered structure ---- tiers = _build_tiers(filtered, limit, tier, git_meta_map)+ tiers = _build_tiers(filtered, limit, tier, git_meta_map, collector)# --- Summary across ALL open findings (unfiltered) ---by_kind: dict[str, int] = {}@@ -322,11 +326,12 @@ async def get_dead_code(if limit_clamped:result["limit_note"] = (f"Requested limit={requested_limit} exceeded the MCP transport budget "- f"and was clamped to {_MAX_PER_TIER}. Use tier/directory/owner filters "+ f"and was clamped to {max_per_tier}. Use tier/directory/owner filters ""or paginate to see more findings.")result["_meta"] = _build_meta(repository=repository)+ collector.attach(result)return result@@ -412,8 +417,13 @@ def _build_tiers(limit: int,tier_filter: str | None,git_meta_map: dict | None = None,+ collector: OmissionCollector | None = None,) -> dict:- """Split findings into high/medium/low confidence tiers."""+ """Split findings into high/medium/low confidence tiers.++ With a *collector*, findings beyond the per-tier limit are captured for+ the omission store instead of being silently truncated.+ """high = sorted([f for f in findings if f.confidence >= 0.8],key=lambda f: (-f.confidence, -f.lines),@@ -428,6 +438,15 @@ def _build_tiers()def _tier_block(name: str, items: list, description: str) -> dict:+ beyond_limit = items[limit:]+ if beyond_limit and collector is not None:+ collector.add(+ f"{name}-tier findings beyond limit={limit} ({len(beyond_limit)} dropped)",+ "\n".join(+ json.dumps(_serialize_finding(f, git_meta_map), separators=(",", ":"))+ for f in beyond_limit+ ),+ )return {"description": description,"count": len(items),diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex c96dc0a1c..4af10dd85 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -6,17 +6,24 @@ import jsonfrom collections import Counter, defaultdictfrom typing import Any-from sqlalchemy import func as sa_func, select+from sqlalchemy import func as sa_func+from sqlalchemy import select+from repowise.core.generation.onboarding.slots import (+ ONBOARDING_ORDER,+ PROMOTED_SLOTS,+)from repowise.core.persistence.crud import (get_health_metrics as _get_health_metrics,+)+from repowise.core.persistence.crud import (get_health_summary as _get_health_summary,+)+from repowise.core.persistence.crud import (get_kg_layers as _get_kg_layers,- get_kg_tour_steps as _get_kg_tour_steps,)-from repowise.core.generation.onboarding.slots import (- ONBOARDING_ORDER,- PROMOTED_SLOTS,+from repowise.core.persistence.crud import (+ get_kg_tour_steps as _get_kg_tour_steps,)from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (@@ -26,19 +33,18 @@ from repowise.core.persistence.models import (GraphNode,Page,)+from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,- _is_workspace_mode,_resolve_all_contexts,_resolve_repo_context,filter_graph_nodes,filter_rows_by_attr,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.core.registry import mcp_tool_registry as mcp-# ---------------------------------------------------------------------------# repo="all" — workspace-level summary@@ -201,6 +207,9 @@ async def get_overview(repo: str | None = None) -> dict:ctx = await _resolve_repo_context(repo)exclude_spec = _get_exclude_spec(ctx.path)+ # Entries beyond the response caps below are persisted, not silently+ # dropped — the response carries an expandable [repowise#<ref>] marker.+ collector = OmissionCollector("get_overview", repo_root=ctx.path)async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)@@ -232,7 +241,13 @@ async def get_overview(repo: str | None = None) -> dict:).order_by(Page.title))- module_pages = result.scalars().all()[:20] # Cap to keep response bounded+ all_module_pages = result.scalars().all()+ module_pages = all_module_pages[:20] # Cap to keep response bounded+ if len(all_module_pages) > 20:+ collector.add(+ f"module pages beyond cap=20 ({len(all_module_pages) - 20} dropped)",+ "\n".join(f"{p.title}: {p.target_path}" for p in all_module_pages[20:]),+ )# Get entry point files from graph nodes (exclude tests & fixtures)result = await session.execute(@@ -399,10 +414,9 @@ async def get_overview(repo: str | None = None) -> dict:if p.lower() not in generic_labels and p not in ("src",):dir_counts[p] += 1break- if dir_counts:- display_label = dir_counts.most_common(1)[0][0]- else:- display_label = f"cluster_{cid}"+ display_label = (+ dir_counts.most_common(1)[0][0] if dir_counts else f"cluster_{cid}"+ )community_summary.append({@@ -420,11 +434,13 @@ async def get_overview(repo: str | None = None) -> dict:if kg_layers:architecture["layers"] = [{- "name": l.name,- "description": (l.description or "")[:120],- "file_count": len(json.loads(l.node_ids_json) if l.node_ids_json else []),+ "name": layer.name,+ "description": (layer.description or "")[:120],+ "file_count": len(+ json.loads(layer.node_ids_json) if layer.node_ids_json else []+ ),}- for l in kg_layers+ for layer in kg_layers]architecture["tour_available"] = bool(kg_tour)architecture["tour_step_count"] = len(kg_tour)@@ -583,7 +599,7 @@ async def get_overview(repo: str | None = None) -> dict:}for p in module_pages],- "entry_points": [n.node_id for n in entry_nodes[:15]],+ "entry_points": _capped_entry_points(entry_nodes, collector),"git_health": git_health,"knowledge_map": knowledge_map,"community_summary": community_summary,@@ -643,4 +659,15 @@ async def get_overview(repo: str | None = None) -> dict:result["workspace"] = ws_footerresult["_meta"] = _build_meta(repository=repository)+ collector.attach(result)return result+++def _capped_entry_points(entry_nodes: list, collector: OmissionCollector) -> list[str]:+ """First 15 entry-point ids; the remainder goes to the omission store."""+ if len(entry_nodes) > 15:+ collector.add(+ f"entry points beyond cap=15 ({len(entry_nodes) - 15} dropped)",+ "\n".join(n.node_id for n in entry_nodes[15:]),+ )+ return [n.node_id for n in entry_nodes[:15]]diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex afdc415de..e42591acd 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -19,7 +19,9 @@ from repowise.core.persistence.models import (GraphNode,Repository,)+from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._budget import OmissionCollectorfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -32,7 +34,6 @@ from repowise.server.mcp_server._helpers import (is_excluded,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.core.registry import mcp_tool_registry as mcp_FIX_PATTERN = re.compile(r"\b(fix|bug|patch|hotfix|revert|regression|broken|crash|error)\b",@@ -392,6 +393,59 @@ async def _assess_one_target(return result_data+def _as_path(entry: Any) -> str | None:+ """Best-effort file path from a blast-radius list entry (str or dict)."""+ if isinstance(entry, str):+ return entry+ if isinstance(entry, dict):+ return (+ entry.get("file_path")+ or entry.get("path")+ or entry.get("file")+ or entry.get("missing_partner")+ or entry.get("partner")+ )+ return None+++def _trim_blast_lists(+ pr_blast_radius: dict[str, Any],+ exclude_spec: Any,+ collector: OmissionCollector | None = None,+) -> dict[str, Any]:+ """Cap the noisy ``pr_blast_radius`` lists, capturing what gets dropped.++ ``pr_blast_radius`` is the analyzer's own payload — preserve it for+ callers that want the full picture, but drop excluded paths and truncate+ the noisy lists so we stay well under the 25k-token transport ceiling on+ PRs that touch many files. With a *collector*, every entry trimmed for+ size is persisted to the omission store (excluded paths are not — they+ are filtered by policy, not budget).+ """+ trimmed_blast: dict[str, Any] = dict(pr_blast_radius)+ for key, cap in (+ ("transitive_affected", 15),+ ("cochange_warnings", 10),+ ("test_gaps", 10),+ ("recommended_reviewers", 5),+ ):+ value = trimmed_blast.get(key)+ if not isinstance(value, list):+ continue+ if exclude_spec:+ value = [e for e in value if not is_excluded(_as_path(e), exclude_spec)]+ trimmed_blast[key] = value+ if len(value) > cap:+ trimmed_blast[key] = value[:cap]+ trimmed_blast[f"{key}_truncated_total"] = len(value)+ if collector is not None:+ collector.add(+ f"pr_blast_radius.{key} beyond cap={cap} ({len(value) - cap} dropped)",+ value[cap:],+ )+ return trimmed_blast++@mcp.tool()async def get_risk(targets: list[str],@@ -631,48 +685,23 @@ async def get_risk("targets": {r["target"]: r for r in results},}+ collector = OmissionCollector("get_risk", repo_root=ctx.path)if pr_blast_radius is not None:# PR mode — drop global_hotspots (irrelevant to a specific diff), trim# per-target co-change lists, and synthesize a tight directive the# agent can act on without parsing the whole blast-radius dossier.+ # Everything trimmed below is persisted via the collector so the+ # response carries an expandable [repowise#<ref>] marker for it.for r in response["targets"].values():partners = r.get("co_change_partners") or []if len(partners) > 3:r["co_change_partners"] = partners[:3]-- def _as_path(entry: Any) -> str | None:- if isinstance(entry, str):- return entry- if isinstance(entry, dict):- return (- entry.get("file_path")- or entry.get("path")- or entry.get("file")- or entry.get("missing_partner")- or entry.get("partner")+ collector.add(+ f"{r.get('target')} :: co_change_partners beyond 3",+ partners[3:],)- return None- # ``pr_blast_radius`` is the analyzer's own payload — preserve it for- # callers that want the full picture, but drop excluded paths and- # truncate the noisy lists so we stay well under the 25k-token transport- # ceiling on PRs that touch many files.- trimmed_blast: dict[str, Any] = dict(pr_blast_radius)- for key, cap in (- ("transitive_affected", 15),- ("cochange_warnings", 10),- ("test_gaps", 10),- ("recommended_reviewers", 5),- ):- value = trimmed_blast.get(key)- if not isinstance(value, list):- continue- if exclude_spec:- value = [e for e in value if not is_excluded(_as_path(e), exclude_spec)]- trimmed_blast[key] = value- if len(value) > cap:- trimmed_blast[key] = value[:cap]- trimmed_blast[f"{key}_truncated_total"] = len(value)+ trimmed_blast = _trim_blast_lists(pr_blast_radius, exclude_spec, collector)response["pr_blast_radius"] = trimmed_blast# Directive: 3 short lists the agent can read in one glance. Each@@ -759,4 +788,5 @@ async def get_risk(response["global_hotspots"] = global_hotspotsresponse["_meta"] = _build_meta(repository=repository)+ collector.attach(response)return responsediff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 3ec5107a0..2cae27a93 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -8,7 +8,7 @@ the WikiSymbol row at index time.Why a separate tool instead of "include source" on get_context?* Granularity: a single function is ~30 lines vs a 300-line file. Cuts the- cached prompt prefix by ~10× when the agent only needs one symbol.+ cached prompt prefix by ~10x when the agent only needs one symbol.* Predictability: response size is bounded by the symbol size, never thefile size — no surprise 50 KB payloads.* No reparsing: the bytes come straight from disk via the persisted line@@ -23,13 +23,22 @@ Resolution strategy (in order):2. Exact match on (file_path, qualified_name) — supports class.method form3. Exact match on (file_path, name) — supports unqualified names+The tool also resolves **omission refs**: a ``symbol_id`` of the form+``"repowise#<12-hex>"`` (from a ``[repowise#<ref>: ...]`` truncation marker)+retrieves the omitted content from the durable omission store instead of the+symbol index. The two id shapes are syntactically unambiguous — a real+symbol_id always contains a file path — so dispatch is trivial and the+symbol contract is untouched.+Returns a flat dict (not wrapped in `targets`) so the agent can pipe the`source` field straight to its scratch buffer."""from __future__ import annotations+import reimport time+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -37,6 +46,7 @@ from sqlalchemy import selectfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import WikiSymbol+from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server._helpers import (_get_exclude_spec,_get_repo,@@ -46,7 +56,6 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import symbol_hint as _symbol_hint-from repowise.core.registry import mcp_tool_registry as mcp_log = __import__("logging").getLogger("repowise.mcp.symbol")@@ -54,6 +63,86 @@ _log = __import__("logging").getLogger("repowise.mcp.symbol")# can never blow up the agent's context window. Tuned to ~12 KB of source._MAX_SOURCE_LINES = 400+# Omission-ref dispatch: "repowise#<12-hex>" never collides with a+# "{path}::{name}" symbol_id. Also tolerates a pasted whole marker.+_OMISSION_REF_RE = re.compile(r"^repowise#([0-9a-f]{12})$")+++def _extract_omission_ref(symbol_id: str) -> str | None:+ """Return the 12-hex omission ref when *symbol_id* is ref-shaped, else None."""+ candidate = symbol_id.strip()+ match = _OMISSION_REF_RE.match(candidate)+ if match:+ return match.group(1)+ if candidate.startswith("[repowise#"):+ from repowise.core.distill.markers import MARKER_RE++ marker = MARKER_RE.search(candidate)+ if marker:+ return marker.group("ref")+ return None+++def _resolve_omission_ref(+ symbol_id: str, ref: str, query: str | None, repo_root: Any, t0: float+) -> dict:+ """Look *ref* up in the omission store(s) and shape a tool response.++ Checks the repo-local store first, then the user-level fallback —+ the same order as ``repowise expand``. Stores are only opened when the+ DB file already exists (opening would otherwise create an empty one).+ """+ from repowise.core.distill.store import OmissionStore, default_store_path++ candidates: list[Path] = []+ if repo_root:+ candidates.append(default_store_path(Path(str(repo_root))))+ home_store = default_store_path(Path.home())+ if home_store not in candidates:+ candidates.append(home_store)++ record: dict | None = None+ for db_path in candidates:+ if not db_path.exists():+ continue+ store = OmissionStore(db_path)+ try:+ record = store.get_record(ref, query=query)+ finally:+ store.close()+ if record is not None:+ break++ if record is None:+ return {+ "symbol_id": symbol_id,+ "ref": ref,+ "error": (+ f"No stored content for omission ref {ref!r} — it may have "+ "expired (7-day TTL), been pruned, or been produced in a "+ "different repo. Re-run the original call for fresh content."+ ),+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),+ }++ created = record.get("created_at")+ response: dict[str, Any] = {+ "symbol_id": symbol_id,+ "ref": ref,+ "kind": "omission",+ "source": record.get("source"),+ "original_tokens": record.get("original_tokens"),+ "content": record.get("content"),+ "_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),+ }+ if isinstance(created, (int, float)):+ response["created_at"] = datetime.fromtimestamp(created, tz=UTC).isoformat()+ if query is not None:+ response["query"] = query+ if not record.get("content"):+ response["note"] = "No lines matched the query; omit query for the full content."+ return response+def _parse_symbol_id(symbol_id: str) -> tuple[str | None, str | None]:"""Split a "{path}::{name}" id. Either side may be None if missing.@@ -283,6 +372,7 @@ async def get_symbol(symbol_id: str,context_lines: int = 0,repo: str | None = None,+ query: str | None = None,) -> dict:"""Read one function/class with exact line bounds — cheaper and safer than Read+math.@@ -290,15 +380,19 @@ async def get_symbol(without the agent having to compute offsets or guess at file structure.Bounded to ~400 lines (hard cap) so a misconfigured row can never blow upthe context window. Pass the canonical ``"path/to/file.py::Name"`` that- appears in ``get_context``'s symbol list.+ appears in ``get_context``'s symbol list. Also resolves omission refs:+ pass ``"repowise#<12-hex>"`` from a ``[repowise#...]`` truncation marker+ to retrieve the omitted content (``query`` filters it to matching lines).Returns {file, name, kind, signature, start_line, end_line, source,truncated}. On miss returns {error: "Symbol not found …"}.Args:- symbol_id: "path/to/file.py::SymbolName" (canonical id from get_context).- context_lines: extra source lines before/after (0–50, default 0).+ symbol_id: "path/to/file.py::SymbolName" (canonical id from get_context),+ or "repowise#<12-hex>" from an omission marker.+ context_lines: extra source lines before/after (0-50, default 0).repo: usually omitted.+ query: omission refs only — regex (or substring) returning matching lines."""if repo == "all":return _unsupported_repo_all("get_symbol")@@ -311,6 +405,11 @@ async def get_symbol("error": "symbol_id is required","_meta": _build_meta(timing_ms=(time.perf_counter() - t0) * 1000),}++ omission_ref = _extract_omission_ref(symbol_id)+ if omission_ref is not None:+ return _resolve_omission_ref(symbol_id, omission_ref, query, ctx.path, t0)+repository = Noneif context_lines < 0 or context_lines > 50:# Bound context_lines to a sane range — runaway values would@@ -346,7 +445,7 @@ async def get_symbol(}repo_root = Path(str(ctx.path))- source, start, end, total = _slice_source(+ source, start, end, _total = _slice_source(repo_root, row.file_path, row.start_line, row.end_line, context_lines)diff --git a/packages/server/src/repowise/server/routers/costs.py b/packages/server/src/repowise/server/routers/costs.pyindex 92f8ca11b..88fea7a32 100644--- a/packages/server/src/repowise/server/routers/costs.py+++ b/packages/server/src/repowise/server/routers/costs.py@@ -2,16 +2,23 @@from __future__ import annotations-from datetime import datetime, date+import sqlite3+from datetime import date, datetime+from pathlib import Pathimport sqlalchemy as sa-from sqlalchemy import select+from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession-from fastapi import APIRouter, Depends, Query+from repowise.core.persistence import crudfrom repowise.core.persistence.models import LlmCostfrom repowise.server.deps import get_db_session, verify_api_key-from repowise.server.schemas import CostGroupResponse, CostSummaryResponse+from repowise.server.schemas import (+ CostGroupResponse,+ CostSummaryResponse,+ DistillSavingsGroup,+ DistillSavingsResponse,+)router = APIRouter(prefix="/api/repos",@@ -109,3 +116,65 @@ async def list_costs()for row in rows]+++#: Pricing model for the savings dollar estimate — saved tokens are+#: input-side tokens the coding agent never had to read.+_SAVINGS_PRICING_MODEL = "claude-sonnet-4-6"++[email protected]("/{repo_id}/distill-savings", response_model=DistillSavingsResponse)+async def get_distill_savings(+ repo_id: str,+ since: str | None = Query(None, description="ISO date filter, e.g. 2025-01-01"),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> DistillSavingsResponse:+ """Savings-ledger rollup from the repo's omission store sidecar.++ Covers the ``repowise distill`` command/hook path only; MCP response+ truncation is not recorded in the ledger. Returns ``available=False``+ when the repo has no omission store on disk.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ if not repo.local_path:+ return DistillSavingsResponse(available=False)++ db_path = Path(repo.local_path) / ".repowise" / "omissions" / "omissions.db"+ if not db_path.is_file():+ return DistillSavingsResponse(available=False)++ since_dt = _parse_since(since)+ since_ts = since_dt.timestamp() if since_dt is not None else None++ from repowise.core.distill import tracking+ from repowise.core.generation.cost_tracker import get_model_pricing++ # Read-only stdlib sqlite3 on the sidecar: tiny aggregate queries, and a+ # ro handle never contends with hook/CLI writers.+ try:+ conn = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=1)+ except sqlite3.Error:+ return DistillSavingsResponse(available=False)+ try:+ summary = tracking.savings_summary(conn, since=since_ts)+ per_filter = tracking.savings_rollup(conn, by="filter", since=since_ts)+ per_day = tracking.savings_rollup(conn, by="day", since=since_ts)+ except sqlite3.Error:+ return DistillSavingsResponse(available=False)+ finally:+ conn.close()++ rate = get_model_pricing(_SAVINGS_PRICING_MODEL)["input"]+ return DistillSavingsResponse(+ available=True,+ events=summary["events"],+ raw_tokens=summary["raw_tokens"],+ distilled_tokens=summary["distilled_tokens"],+ saved_tokens=summary["saved_tokens"],+ estimated_usd_saved=summary["saved_tokens"] * rate / 1_000_000,+ pricing_model=_SAVINGS_PRICING_MODEL,+ per_filter=[DistillSavingsGroup(**row) for row in per_filter],+ per_day=[DistillSavingsGroup(**row) for row in per_day],+ )diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 25d2f092a..2f4bae5ff 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -136,6 +136,8 @@ from .symbols import (from .ui_helpers import (CostGroupResponse,CostSummaryResponse,+ DistillSavingsGroup,+ DistillSavingsResponse,SetActiveProviderRequest,SetApiKeyRequest,WebhookResponse,@@ -206,6 +208,8 @@ __all__ = ["DecisionRecordResponse","DecisionStatusUpdate","DirectRiskEntry",+ "DistillSavingsGroup",+ "DistillSavingsResponse","EgoGraphResponse","ExecutionFlowEntry","ExecutionFlowsResponse",diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.pyindex 7d107fe67..047d95a14 100644--- a/packages/server/src/repowise/server/schemas/ui_helpers.py+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py@@ -33,3 +33,30 @@ class CostSummaryResponse(BaseModel):total_input_tokens: inttotal_output_tokens: intsince: str | None+++class DistillSavingsGroup(BaseModel):+ group: str+ events: int+ raw_tokens: int+ distilled_tokens: int+ saved_tokens: int+++class DistillSavingsResponse(BaseModel):+ """Savings ledger rollup for the Costs page card.++ Covers the ``repowise distill`` command/hook path only — MCP response+ truncation is not recorded in the ledger. ``available`` is False when+ the repo has no omission store on disk (feature unused).+ """++ available: bool+ events: int = 0+ raw_tokens: int = 0+ distilled_tokens: int = 0+ saved_tokens: int = 0+ estimated_usd_saved: float = 0.0+ pricing_model: str = ""+ per_filter: list[DistillSavingsGroup] = []+ per_day: list[DistillSavingsGroup] = []diff --git a/packages/ui/src/costs/distill-savings-card.tsx b/packages/ui/src/costs/distill-savings-card.tsxnew file mode 100644index 000000000..21d674771--- /dev/null+++ b/packages/ui/src/costs/distill-savings-card.tsx@@ -0,0 +1,108 @@+"use client";++import { Scissors } from "lucide-react";+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";+import { formatCost, formatTokens } from "../lib/format";++export interface DistillSavingsGroup {+ group: string;+ events: number;+ raw_tokens: number;+ distilled_tokens: number;+ saved_tokens: number;+}++export interface DistillSavingsData {+ available: boolean;+ events: number;+ raw_tokens: number;+ distilled_tokens: number;+ saved_tokens: number;+ estimated_usd_saved: number;+ pricing_model: string;+ per_filter: DistillSavingsGroup[];+ per_day: DistillSavingsGroup[];+}++export interface DistillSavingsCardProps {+ /** Savings rollup from /distill-savings; undefined while loading. */+ data?: DistillSavingsData;+}++/**+ * Tokens saved by `repowise distill` (command + hook path). MCP response+ * truncation is not part of this ledger, and the card says so — the number+ * shown is real avoided agent input, not budget-capped responses.+ */+export function DistillSavingsCard({ data }: DistillSavingsCardProps) {+ const hasData = data?.available && data.events > 0;+ const pct =+ hasData && data.raw_tokens > 0+ ? Math.round((data.saved_tokens / data.raw_tokens) * 100)+ : 0;+ const topFilters = hasData ? data.per_filter.slice(0, 3) : [];++ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm flex items-center gap-2">+ <Scissors className="h-4 w-4 text-cyan-500" />+ Distill savings+ </CardTitle>+ </CardHeader>+ <CardContent className="pt-0">+ {hasData ? (+ <div className="space-y-3">+ <div className="flex items-baseline gap-2">+ <span className="text-2xl font-semibold text-[var(--color-text-primary)] tabular-nums">+ {formatTokens(data.saved_tokens)}+ </span>+ <span className="text-xs text-[var(--color-text-secondary)]">+ tokens saved ({pct}%) ·{" "}+ <span className="font-medium text-green-500">+ {formatCost(data.estimated_usd_saved)}+ </span>{" "}+ est.+ </span>+ </div>+ <div className="space-y-1">+ {topFilters.map((f) => {+ const width =+ data.saved_tokens > 0+ ? Math.max(4, Math.round((f.saved_tokens / data.saved_tokens) * 100))+ : 0;+ return (+ <div key={f.group} className="flex items-center gap-2 text-xs">+ <span className="w-24 shrink-0 truncate text-[var(--color-text-secondary)]">+ {f.group}+ </span>+ <div className="flex-1 h-1.5 rounded bg-[var(--color-bg-inset)] overflow-hidden">+ <div+ className="h-full rounded bg-[var(--color-accent-primary)]"+ style={{ width: `${width}%` }}+ />+ </div>+ <span className="w-14 shrink-0 text-right tabular-nums text-[var(--color-text-primary)]">+ {formatTokens(f.saved_tokens)}+ </span>+ </div>+ );+ })}+ </div>+ <p className="text-[10px] text-[var(--color-text-tertiary)] leading-snug">+ {data.events.toLocaleString()} distillation{data.events === 1 ? "" : "s"} via the{" "}+ <code>repowise distill</code> command/hook path. MCP response truncation is not+ counted. Estimate at {data.pricing_model} input rate.+ </p>+ </div>+ ) : (+ <p className="text-xs text-[var(--color-text-tertiary)] leading-snug max-w-[300px]">+ No distillation savings recorded yet. Run noisy commands through{" "}+ <code>repowise distill <cmd></code> or install the rewrite hook (+ <code>repowise hook rewrite install</code>) to start trimming agent context.+ </p>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/packages/ui/src/costs/index.ts b/packages/ui/src/costs/index.tsindex 909a25c03..7a4974ef3 100644--- a/packages/ui/src/costs/index.ts+++ b/packages/ui/src/costs/index.ts@@ -6,3 +6,9 @@ export { CostHeatmap } from "./cost-heatmap";export type { CostHeatmapProps } from "./cost-heatmap";export { CacheHitRatioCard } from "./cache-hit-ratio-card";export type { CacheHitRatioCardProps } from "./cache-hit-ratio-card";+export { DistillSavingsCard } from "./distill-savings-card";+export type {+ DistillSavingsCardProps,+ DistillSavingsData,+ DistillSavingsGroup,+} from "./distill-savings-card";diff --git a/packages/web/src/app/repos/[id]/costs/page.tsx b/packages/web/src/app/repos/[id]/costs/page.tsxindex 929bc203a..3f7b1fa17 100644--- a/packages/web/src/app/repos/[id]/costs/page.tsx+++ b/packages/web/src/app/repos/[id]/costs/page.tsx@@ -19,11 +19,12 @@ import { Tabs, TabsList, TabsTrigger, TabsContent } from "@repowise-dev/ui/ui/taimport {CacheHitRatioCard,CostHeatmap,+ DistillSavingsCard,ProviderComparison,OperationBreakdown,} from "@repowise-dev/ui/costs";-import { listCosts, getCostSummary } from "@/lib/api/costs";-import type { CostGroup, CostSummary } from "@/lib/api/costs";+import { listCosts, getCostSummary, getDistillSavings } from "@/lib/api/costs";+import type { CostGroup, CostSummary, DistillSavings } from "@/lib/api/costs";import { formatCost, formatNumber, formatTokens } from "@repowise-dev/ui/lib/format";export default function CostsPage() {@@ -55,6 +56,12 @@ export default function CostsPage() {{ revalidateOnFocus: false },);+ const { data: distillSavings } = useSWR<DistillSavings>(+ `distill-savings:${id}`,+ () => getDistillSavings(id),+ { revalidateOnFocus: false },+ );+return (<div className="p-4 sm:p-6 space-y-6 max-w-[1600px]"><div>@@ -166,6 +173,7 @@ export default function CostsPage() {<TabsContent value="cache" className="mt-4"><div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <DistillSavingsCard data={distillSavings} /><CacheHitRatioCard /><Card><CardHeader className="pb-2">diff --git a/packages/web/src/lib/api/costs.ts b/packages/web/src/lib/api/costs.tsindex 760110d6b..2b8284cf6 100644--- a/packages/web/src/lib/api/costs.ts+++ b/packages/web/src/lib/api/costs.ts@@ -20,6 +20,26 @@ export interface CostSummary {since: string | null;}+export interface DistillSavingsGroup {+ group: string;+ events: number;+ raw_tokens: number;+ distilled_tokens: number;+ saved_tokens: number;+}++export interface DistillSavings {+ available: boolean;+ events: number;+ raw_tokens: number;+ distilled_tokens: number;+ saved_tokens: number;+ estimated_usd_saved: number;+ pricing_model: string;+ per_filter: DistillSavingsGroup[];+ per_day: DistillSavingsGroup[];+}+// ---------------------------------------------------------------------------// API functions// ---------------------------------------------------------------------------@@ -42,3 +62,12 @@ export async function getCostSummary(since,});}++export async function getDistillSavings(+ repoId: string,+ since?: string,+): Promise<DistillSavings> {+ return apiGet<DistillSavings>(`/api/repos/${repoId}/distill-savings`, {+ since,+ });+}diff --git a/plugins/claude-code/DEVELOPER.md b/plugins/claude-code/DEVELOPER.mdindex 284251051..3f98e3733 100644--- a/plugins/claude-code/DEVELOPER.md+++ b/plugins/claude-code/DEVELOPER.md@@ -62,7 +62,7 @@ lives at the repo root.The `repowise` binary must be on PATH (`/repowise:init` installs it).**`hooks/hooks.json`** — Registers a `PostToolUse` hook-(`Bash|Grep|Glob` → `repowise-augment`) so context enrichment works as soon as+(`Bash|Grep|Glob|Read|Edit|Write` → `repowise-augment`) so context enrichment works as soon asthe plugin is installed. This mirrors the hook `repowise init` writes to`~/.claude/settings.json`; both firing is safe — see "Hook de-duplication".diff --git a/plugins/claude-code/hooks/hooks.json b/plugins/claude-code/hooks/hooks.jsonindex c55ac719f..cc353b7c9 100644--- a/plugins/claude-code/hooks/hooks.json+++ b/plugins/claude-code/hooks/hooks.json@@ -2,7 +2,7 @@"hooks": {"PostToolUse": [{- "matcher": "Bash|Grep|Glob",+ "matcher": "Bash|Grep|Glob|Read|Edit|Write","hooks": [{"type": "command",diff --git a/pyproject.toml b/pyproject.tomlindex 26425586f..7587241d2 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -112,6 +112,7 @@ dev = [[project.scripts]repowise = "repowise.cli.main:cli"repowise-augment = "repowise.cli.augment_hook:main"+repowise-rewrite = "repowise.cli.rewrite_hook:main"[project.urls]Homepage = "https://github.com/repowise-dev/repowise"diff --git a/tests/fixtures/distill/cargo_test_fail.txt b/tests/fixtures/distill/cargo_test_fail.txtnew file mode 100644index 000000000..156118077--- /dev/null+++ b/tests/fixtures/distill/cargo_test_fail.txt@@ -0,0 +1,66 @@+ Compiling proc-macro2 v1.0.86+ Compiling unicode-ident v1.0.12+ Compiling quote v1.0.36+ Compiling syn v2.0.72+ Compiling serde v1.0.204+ Compiling serde_json v1.0.120+ Compiling thiserror v1.0.61+ Compiling repowise-core v0.16.0 (/home/dev/repowise/core)+warning: unused variable: `budget`+ --> core/src/distill/router.rs:48:9+ |+48 | let budget = remaining_tokens(ctx);+ | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_budget`+ |+ = note: `#[warn(unused_variables)]` on by default++warning: `repowise-core` (lib) generated 1 warning+ Finished `test` profile [unoptimized + debuginfo] target(s) in 14.82s+ Running unittests src/lib.rs (target/debug/deps/repowise_core-7c1f2a90b44e8d13)++running 24 tests+test graph::tests::test_pagerank_sums_to_one ... ok+test graph::tests::test_betweenness_cached ... ok+test ingestion::tests::test_parser_python ... ok+test ingestion::tests::test_parser_typescript ... ok+test ingestion::tests::test_parser_csharp ... ok+test ingestion::tests::test_incremental_scope ... ok+test markers::tests::test_render_roundtrip ... ok+test markers::tests::test_invalid_ref_rejected ... ok+test store::tests::test_put_get ... ok+test store::tests::test_ttl_prune ... FAILED+test store::tests::test_size_cap_prune ... ok+test router::tests::test_command_normalize ... ok+test router::tests::test_wrapper_strip ... FAILED+test router::tests::test_disabled_filters ... ok+test budget::tests::test_estimate ... ok+test health::tests::test_biomarkers ... ok+test health::tests::test_size_orthogonal ... ok+test git::tests::test_blame_rollup ... ok+test git::tests::test_cochange_window ... ok+test git::tests::test_provenance_layer ... ok+test dead_code::tests::test_tiering ... ok+test dead_code::tests::test_zombie_packages ... ok+test cli::tests::test_exit_code_passthrough ... ok+test cli::tests::test_expand_missing_ref ... ok++failures:++---- store::tests::test_ttl_prune stdout ----+thread 'store::tests::test_ttl_prune' panicked at core/src/store.rs:201:9:+assertion `left == right` failed+ left: 3+ right: 0+note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace++---- router::tests::test_wrapper_strip stdout ----+thread 'router::tests::test_wrapper_strip' panicked at core/src/router.rs:88:5:+assertion failed: normalized.starts_with("pytest")++failures:+ router::tests::test_wrapper_strip+ store::tests::test_ttl_prune++test result: FAILED. 22 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.31s++error: test failed, to rerun pass `--lib`diff --git a/tests/fixtures/distill/find_paths.txt b/tests/fixtures/distill/find_paths.txtnew file mode 100644index 000000000..472f856fe--- /dev/null+++ b/tests/fixtures/distill/find_paths.txt@@ -0,0 +1,469 @@+packages/core/src/repowise/core/analysis/change_risk/features.py+packages/core/src/repowise/core/analysis/change_risk/model.py+packages/core/src/repowise/core/analysis/change_risk/normalize.py+packages/core/src/repowise/core/analysis/change_risk/__init__.py+packages/core/src/repowise/core/analysis/communities.py+packages/core/src/repowise/core/analysis/dead_code/analyzer.py+packages/core/src/repowise/core/analysis/dead_code/constants.py+packages/core/src/repowise/core/analysis/dead_code/contract_methods.py+packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py+packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py+packages/core/src/repowise/core/analysis/dead_code/go_reachability.py+packages/core/src/repowise/core/analysis/dead_code/jvm_reachability.py+packages/core/src/repowise/core/analysis/dead_code/models.py+packages/core/src/repowise/core/analysis/dead_code/__init__.py+packages/core/src/repowise/core/analysis/decisions/evolution.py+packages/core/src/repowise/core/analysis/decisions/extractor.py+packages/core/src/repowise/core/analysis/decisions/gate.py+packages/core/src/repowise/core/analysis/decisions/prompts.py+packages/core/src/repowise/core/analysis/decisions/provenance.py+packages/core/src/repowise/core/analysis/decisions/semantic_match.py+packages/core/src/repowise/core/analysis/decisions/__init__.py+packages/core/src/repowise/core/analysis/decision_evolution.py+packages/core/src/repowise/core/analysis/decision_extractor.py+packages/core/src/repowise/core/analysis/decision_gate.py+packages/core/src/repowise/core/analysis/decision_provenance.py+packages/core/src/repowise/core/analysis/decision_semantic_match.py+packages/core/src/repowise/core/analysis/execution_flows.py+packages/core/src/repowise/core/analysis/health/biomarkers/base.py+packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py+packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py+packages/core/src/repowise/core/analysis/health/biomarkers/change_entropy.py+packages/core/src/repowise/core/analysis/health/biomarkers/churn_risk.py+packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py+packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py+packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py+packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py+packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gradient.py+packages/core/src/repowise/core/analysis/health/biomarkers/co_change_scatter.py+packages/core/src/repowise/core/analysis/health/biomarkers/developer_congestion.py+packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.py+packages/core/src/repowise/core/analysis/health/biomarkers/duplicated_assertion_block.py+packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py+packages/core/src/repowise/core/analysis/health/biomarkers/god_class.py+packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py+packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py+packages/core/src/repowise/core/analysis/health/biomarkers/large_assertion_block.py+packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py+packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py+packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py+packages/core/src/repowise/core/analysis/health/biomarkers/ownership_risk.py+packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py+packages/core/src/repowise/core/analysis/health/biomarkers/prior_defect.py+packages/core/src/repowise/core/analysis/health/biomarkers/registry.py+packages/core/src/repowise/core/analysis/health/biomarkers/untested_hotspot.py+packages/core/src/repowise/core/analysis/health/biomarkers/__init__.py+packages/core/src/repowise/core/analysis/health/complexity/languages.py+packages/core/src/repowise/core/analysis/health/complexity/walker.py+packages/core/src/repowise/core/analysis/health/complexity/__init__.py+packages/core/src/repowise/core/analysis/health/config.py+packages/core/src/repowise/core/analysis/health/coverage/clover.py+packages/core/src/repowise/core/analysis/health/coverage/cobertura.py+packages/core/src/repowise/core/analysis/health/coverage/detector.py+packages/core/src/repowise/core/analysis/health/coverage/lcov.py+packages/core/src/repowise/core/analysis/health/coverage/model.py+packages/core/src/repowise/core/analysis/health/coverage/repowise_json.py+packages/core/src/repowise/core/analysis/health/coverage/__init__.py+packages/core/src/repowise/core/analysis/health/duplication/detector.py+packages/core/src/repowise/core/analysis/health/duplication/limits.py+packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.py+packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py+packages/core/src/repowise/core/analysis/health/duplication/token_cache.py+packages/core/src/repowise/core/analysis/health/duplication/__init__.py+packages/core/src/repowise/core/analysis/health/engine.py+packages/core/src/repowise/core/analysis/health/function_blame_rollup.py+packages/core/src/repowise/core/analysis/health/governance.py+packages/core/src/repowise/core/analysis/health/models.py+packages/core/src/repowise/core/analysis/health/scoring.py+packages/core/src/repowise/core/analysis/health/suggestions.py+packages/core/src/repowise/core/analysis/health/trends.py+packages/core/src/repowise/core/analysis/health/__init__.py+packages/core/src/repowise/core/analysis/knowledge_graph.py+packages/core/src/repowise/core/analysis/pr_blast.py+packages/core/src/repowise/core/analysis/security_scan.py+packages/core/src/repowise/core/analysis/__init__.py+packages/core/src/repowise/core/cancellation.py+packages/core/src/repowise/core/distill/budget.py+packages/core/src/repowise/core/distill/filters/base.py+packages/core/src/repowise/core/distill/filters/build_output.py+packages/core/src/repowise/core/distill/filters/file_listing.py+packages/core/src/repowise/core/distill/filters/git_diff.py+packages/core/src/repowise/core/distill/filters/git_log.py+packages/core/src/repowise/core/distill/filters/git_status.py+packages/core/src/repowise/core/distill/filters/logs.py+packages/core/src/repowise/core/distill/filters/test_output.py+packages/core/src/repowise/core/distill/filters/__init__.py+packages/core/src/repowise/core/distill/markers.py+packages/core/src/repowise/core/distill/registry.py+packages/core/src/repowise/core/distill/router.py+packages/core/src/repowise/core/distill/store.py+packages/core/src/repowise/core/distill/tracking.py+packages/core/src/repowise/core/distill/__init__.py+packages/core/src/repowise/core/generation/api_contract_detector.py+packages/core/src/repowise/core/generation/categories.py+packages/core/src/repowise/core/generation/context/assembler.py+packages/core/src/repowise/core/generation/context/contexts.py+packages/core/src/repowise/core/generation/context/graph_intelligence.py+packages/core/src/repowise/core/generation/context/token_budget.py+packages/core/src/repowise/core/generation/context/__init__.py+packages/core/src/repowise/core/generation/context_assembler.py+packages/core/src/repowise/core/generation/cost_tracker.py+packages/core/src/repowise/core/generation/editor_files/agents_md.py+packages/core/src/repowise/core/generation/editor_files/base.py+packages/core/src/repowise/core/generation/editor_files/claude_md.py+packages/core/src/repowise/core/generation/editor_files/data.py+packages/core/src/repowise/core/generation/editor_files/fetcher.py+packages/core/src/repowise/core/generation/editor_files/tech_stack.py+packages/core/src/repowise/core/generation/editor_files/__init__.py+packages/core/src/repowise/core/generation/interlinking.py+packages/core/src/repowise/core/generation/job_system.py+packages/core/src/repowise/core/generation/kg_context.py+packages/core/src/repowise/core/generation/kg_enrichment.py+packages/core/src/repowise/core/generation/knowledge_graph.py+packages/core/src/repowise/core/generation/layers.py+packages/core/src/repowise/core/generation/mermaid_safety.py+packages/core/src/repowise/core/generation/models.py+packages/core/src/repowise/core/generation/onboarding/registry.py+packages/core/src/repowise/core/generation/onboarding/signals.py+packages/core/src/repowise/core/generation/onboarding/slots.py+packages/core/src/repowise/core/generation/onboarding/subkinds/active_landscape.py+packages/core/src/repowise/core/generation/onboarding/subkinds/codebase_map.py+packages/core/src/repowise/core/generation/onboarding/subkinds/development_guide.py+packages/core/src/repowise/core/generation/onboarding/subkinds/getting_started.py+packages/core/src/repowise/core/generation/onboarding/subkinds/guided_tour.py+packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py+packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py+packages/core/src/repowise/core/generation/onboarding/subkinds/__init__.py+packages/core/src/repowise/core/generation/onboarding/__init__.py+packages/core/src/repowise/core/generation/page_generator/core.py+packages/core/src/repowise/core/generation/page_generator/decision_harvest.py+packages/core/src/repowise/core/generation/page_generator/helpers.py+packages/core/src/repowise/core/generation/page_generator/levels.py+packages/core/src/repowise/core/generation/page_generator/orchestrate.py+packages/core/src/repowise/core/generation/page_generator/pertype.py+packages/core/src/repowise/core/generation/page_generator/prompts.py+packages/core/src/repowise/core/generation/page_generator/tiering.py+packages/core/src/repowise/core/generation/page_generator/validation.py+packages/core/src/repowise/core/generation/page_generator/__init__.py+packages/core/src/repowise/core/generation/report.py+packages/core/src/repowise/core/generation/selection/budget.py+packages/core/src/repowise/core/generation/selection/scoring.py+packages/core/src/repowise/core/generation/selection/selector.py+packages/core/src/repowise/core/generation/selection/__init__.py+packages/core/src/repowise/core/generation/tour.py+packages/core/src/repowise/core/generation/__init__.py+packages/core/src/repowise/core/ingestion/aspnet_extensions.py+packages/core/src/repowise/core/ingestion/call_resolver.py+packages/core/src/repowise/core/ingestion/change_detector.py+packages/core/src/repowise/core/ingestion/dynamic_hints/alpine.py+packages/core/src/repowise/core/ingestion/dynamic_hints/base.py+packages/core/src/repowise/core/ingestion/dynamic_hints/c.py+packages/core/src/repowise/core/ingestion/dynamic_hints/cpp.py+packages/core/src/repowise/core/ingestion/dynamic_hints/django.py+packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py+packages/core/src/repowise/core/ingestion/dynamic_hints/go.py+packages/core/src/repowise/core/ingestion/dynamic_hints/jvm.py+packages/core/src/repowise/core/ingestion/dynamic_hints/luau.py+packages/core/src/repowise/core/ingestion/dynamic_hints/node.py+packages/core/src/repowise/core/ingestion/dynamic_hints/php.py+packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.py+packages/core/src/repowise/core/ingestion/dynamic_hints/python_imports.py+packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py+packages/core/src/repowise/core/ingestion/dynamic_hints/ruby.py+packages/core/src/repowise/core/ingestion/dynamic_hints/rust.py+packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py+packages/core/src/repowise/core/ingestion/dynamic_hints/spring.py+packages/core/src/repowise/core/ingestion/dynamic_hints/swift.py+packages/core/src/repowise/core/ingestion/dynamic_hints/xaml.py+packages/core/src/repowise/core/ingestion/dynamic_hints/_walk.py+packages/core/src/repowise/core/ingestion/dynamic_hints/__init__.py+packages/core/src/repowise/core/ingestion/external_systems/base.py+packages/core/src/repowise/core/ingestion/external_systems/bazel.py+packages/core/src/repowise/core/ingestion/external_systems/cargo.py+packages/core/src/repowise/core/ingestion/external_systems/classifier.py+packages/core/src/repowise/core/ingestion/external_systems/cmake.py+packages/core/src/repowise/core/ingestion/external_systems/go.py+packages/core/src/repowise/core/ingestion/external_systems/maven.py+packages/core/src/repowise/core/ingestion/external_systems/npm.py+packages/core/src/repowise/core/ingestion/external_systems/nuget.py+packages/core/src/repowise/core/ingestion/external_systems/pypi.py+packages/core/src/repowise/core/ingestion/external_systems/__init__.py+packages/core/src/repowise/core/ingestion/extractors/bindings/cpp.py+packages/core/src/repowise/core/ingestion/extractors/bindings/csharp.py+packages/core/src/repowise/core/ingestion/extractors/bindings/go.py+packages/core/src/repowise/core/ingestion/extractors/bindings/java.py+packages/core/src/repowise/core/ingestion/extractors/bindings/kotlin.py+packages/core/src/repowise/core/ingestion/extractors/bindings/php.py+packages/core/src/repowise/core/ingestion/extractors/bindings/python.py+packages/core/src/repowise/core/ingestion/extractors/bindings/ruby.py+packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py+packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py+packages/core/src/repowise/core/ingestion/extractors/bindings/swift.py+packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py+packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py+packages/core/src/repowise/core/ingestion/extractors/docstrings.py+packages/core/src/repowise/core/ingestion/extractors/helpers.py+packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py+packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py+packages/core/src/repowise/core/ingestion/extractors/heritage/go.py+packages/core/src/repowise/core/ingestion/extractors/heritage/java.py+packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py+packages/core/src/repowise/core/ingestion/extractors/heritage/php.py+packages/core/src/repowise/core/ingestion/extractors/heritage/python.py+packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py+packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py+packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py+packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py+packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py+packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py+packages/core/src/repowise/core/ingestion/extractors/signatures.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/cpp_macros.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/csharp_mvvm.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/java_records.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/jvm_codegen.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/kotlin_jvm.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/lombok.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/_helpers.py+packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py+packages/core/src/repowise/core/ingestion/extractors/visibility.py+packages/core/src/repowise/core/ingestion/extractors/__init__.py+packages/core/src/repowise/core/ingestion/framework_edges/android_manifest.py+packages/core/src/repowise/core/ingestion/framework_edges/aspnet.py+packages/core/src/repowise/core/ingestion/framework_edges/base.py+packages/core/src/repowise/core/ingestion/framework_edges/django.py+packages/core/src/repowise/core/ingestion/framework_edges/express.py+packages/core/src/repowise/core/ingestion/framework_edges/fastapi.py+packages/core/src/repowise/core/ingestion/framework_edges/flask.py+packages/core/src/repowise/core/ingestion/framework_edges/go.py+packages/core/src/repowise/core/ingestion/framework_edges/gtest.py+packages/core/src/repowise/core/ingestion/framework_edges/hono.py+packages/core/src/repowise/core/ingestion/framework_edges/jakarta.py+packages/core/src/repowise/core/ingestion/framework_edges/laravel.py+packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py+packages/core/src/repowise/core/ingestion/framework_edges/next_app.py+packages/core/src/repowise/core/ingestion/framework_edges/pytest_edges.py+packages/core/src/repowise/core/ingestion/framework_edges/quarkus.py+packages/core/src/repowise/core/ingestion/framework_edges/rails.py+packages/core/src/repowise/core/ingestion/framework_edges/remix.py+packages/core/src/repowise/core/ingestion/framework_edges/rust.py+packages/core/src/repowise/core/ingestion/framework_edges/spring.py+packages/core/src/repowise/core/ingestion/framework_edges/trpc.py+packages/core/src/repowise/core/ingestion/framework_edges/typo3.py+packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+packages/core/src/repowise/core/ingestion/git_commit_index.py+packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py+packages/core/src/repowise/core/ingestion/git_indexer/backfill.py+packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py+packages/core/src/repowise/core/ingestion/git_indexer/co_change.py+packages/core/src/repowise/core/ingestion/git_indexer/enrich.py+packages/core/src/repowise/core/ingestion/git_indexer/file_history.py+packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py+packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+packages/core/src/repowise/core/ingestion/git_indexer/prior_defects.py+packages/core/src/repowise/core/ingestion/git_indexer/records.py+packages/core/src/repowise/core/ingestion/git_indexer/tiers.py+packages/core/src/repowise/core/ingestion/git_indexer/_constants.py+packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+packages/core/src/repowise/core/ingestion/graph/builder.py+packages/core/src/repowise/core/ingestion/graph/_betweenness.py+packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py+packages/core/src/repowise/core/ingestion/graph/_edges.py+packages/core/src/repowise/core/ingestion/graph/_metrics.py+packages/core/src/repowise/core/ingestion/graph/_rehydrate.py+packages/core/src/repowise/core/ingestion/graph/_resolvers.py+packages/core/src/repowise/core/ingestion/graph/_serialize.py+packages/core/src/repowise/core/ingestion/graph/_stem.py+packages/core/src/repowise/core/ingestion/graph/__init__.py+packages/core/src/repowise/core/ingestion/graph_warmups.py+packages/core/src/repowise/core/ingestion/heritage_resolver.py+packages/core/src/repowise/core/ingestion/import_index.py+packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py+packages/core/src/repowise/core/ingestion/languages/go_interface_satisfaction.py+packages/core/src/repowise/core/ingestion/languages/python_modules.py+packages/core/src/repowise/core/ingestion/languages/registry.py+packages/core/src/repowise/core/ingestion/languages/spec.py+packages/core/src/repowise/core/ingestion/languages/specs/c.py+packages/core/src/repowise/core/ingestion/languages/specs/clojure.py+packages/core/src/repowise/core/ingestion/languages/specs/cpp.py+packages/core/src/repowise/core/ingestion/languages/specs/crystal.py+packages/core/src/repowise/core/ingestion/languages/specs/csharp.py+packages/core/src/repowise/core/ingestion/languages/specs/dart.py+packages/core/src/repowise/core/ingestion/languages/specs/dlang.py+packages/core/src/repowise/core/ingestion/languages/specs/dockerfile.py+packages/core/src/repowise/core/ingestion/languages/specs/elixir.py+packages/core/src/repowise/core/ingestion/languages/specs/elm.py+packages/core/src/repowise/core/ingestion/languages/specs/erlang.py+packages/core/src/repowise/core/ingestion/languages/specs/fsharp.py+packages/core/src/repowise/core/ingestion/languages/specs/go.py+packages/core/src/repowise/core/ingestion/languages/specs/graphql.py+packages/core/src/repowise/core/ingestion/languages/specs/haskell.py+packages/core/src/repowise/core/ingestion/languages/specs/java.py+packages/core/src/repowise/core/ingestion/languages/specs/javascript.py+packages/core/src/repowise/core/ingestion/languages/specs/json.py+packages/core/src/repowise/core/ingestion/languages/specs/julia.py+packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py+packages/core/src/repowise/core/ingestion/languages/specs/luau.py+packages/core/src/repowise/core/ingestion/languages/specs/makefile.py+packages/core/src/repowise/core/ingestion/languages/specs/markdown.py+packages/core/src/repowise/core/ingestion/languages/specs/nim.py+packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py+packages/core/src/repowise/core/ingestion/languages/specs/ocaml.py+packages/core/src/repowise/core/ingestion/languages/specs/openapi.py+packages/core/src/repowise/core/ingestion/languages/specs/php.py+packages/core/src/repowise/core/ingestion/languages/specs/proto.py+packages/core/src/repowise/core/ingestion/languages/specs/python.py+packages/core/src/repowise/core/ingestion/languages/specs/r.py+packages/core/src/repowise/core/ingestion/languages/specs/ruby.py+packages/core/src/repowise/core/ingestion/languages/specs/rust.py+packages/core/src/repowise/core/ingestion/languages/specs/scala.py+packages/core/src/repowise/core/ingestion/languages/specs/shell.py+packages/core/src/repowise/core/ingestion/languages/specs/sql.py+packages/core/src/repowise/core/ingestion/languages/specs/swift.py+packages/core/src/repowise/core/ingestion/languages/specs/terraform.py+packages/core/src/repowise/core/ingestion/languages/specs/toml.py+packages/core/src/repowise/core/ingestion/languages/specs/typescript.py+packages/core/src/repowise/core/ingestion/languages/specs/unknown.py+packages/core/src/repowise/core/ingestion/languages/specs/xaml.py+packages/core/src/repowise/core/ingestion/languages/specs/yaml.py+packages/core/src/repowise/core/ingestion/languages/specs/zig.py+packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+packages/core/src/repowise/core/ingestion/languages/__init__.py+packages/core/src/repowise/core/ingestion/language_configs.py+packages/core/src/repowise/core/ingestion/language_data.py+packages/core/src/repowise/core/ingestion/models.py+packages/core/src/repowise/core/ingestion/parser.py+packages/core/src/repowise/core/ingestion/parser_helpers.py+packages/core/src/repowise/core/ingestion/parse_cache.py+packages/core/src/repowise/core/ingestion/resolvers/context.py+packages/core/src/repowise/core/ingestion/resolvers/cpp.py+packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py+packages/core/src/repowise/core/ingestion/resolvers/csharp.py+packages/core/src/repowise/core/ingestion/resolvers/dotnet/global_usings.py+packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py+packages/core/src/repowise/core/ingestion/resolvers/dotnet/msbuild.py+packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py+packages/core/src/repowise/core/ingestion/resolvers/dotnet/solution.py+packages/core/src/repowise/core/ingestion/resolvers/dotnet/__init__.py+packages/core/src/repowise/core/ingestion/resolvers/generic.py+packages/core/src/repowise/core/ingestion/resolvers/go.py+packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py+packages/core/src/repowise/core/ingestion/resolvers/java.py+packages/core/src/repowise/core/ingestion/resolvers/jvm_gradle.py+packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py+packages/core/src/repowise/core/ingestion/resolvers/kotlin.py+packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.py+packages/core/src/repowise/core/ingestion/resolvers/luau.py+packages/core/src/repowise/core/ingestion/resolvers/php.py+packages/core/src/repowise/core/ingestion/resolvers/php_composer.py+packages/core/src/repowise/core/ingestion/resolvers/python.py+packages/core/src/repowise/core/ingestion/resolvers/ruby.py+packages/core/src/repowise/core/ingestion/resolvers/ruby_rails.py+packages/core/src/repowise/core/ingestion/resolvers/rust.py+packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py+packages/core/src/repowise/core/ingestion/resolvers/scala.py+packages/core/src/repowise/core/ingestion/resolvers/scala_build.py+packages/core/src/repowise/core/ingestion/resolvers/swift.py+packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py+packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py+packages/core/src/repowise/core/ingestion/resolvers/typescript.py+packages/core/src/repowise/core/ingestion/resolvers/__init__.py+packages/core/src/repowise/core/ingestion/special_handlers.py+packages/core/src/repowise/core/ingestion/traverser.py+packages/core/src/repowise/core/ingestion/tsconfig_resolver.py+packages/core/src/repowise/core/ingestion/type_ref_resolution.py+packages/core/src/repowise/core/ingestion/__init__.py+packages/core/src/repowise/core/persistence/coordinator.py+packages/core/src/repowise/core/persistence/crud/analysis.py+packages/core/src/repowise/core/persistence/crud/chat.py+packages/core/src/repowise/core/persistence/crud/decisions.py+packages/core/src/repowise/core/persistence/crud/external_systems.py+packages/core/src/repowise/core/persistence/crud/git.py+packages/core/src/repowise/core/persistence/crud/graph.py+packages/core/src/repowise/core/persistence/crud/knowledge_graph.py+packages/core/src/repowise/core/persistence/crud/pages.py+packages/core/src/repowise/core/persistence/crud/repository.py+packages/core/src/repowise/core/persistence/crud/_shared.py+packages/core/src/repowise/core/persistence/crud/__init__.py+packages/core/src/repowise/core/persistence/database.py+packages/core/src/repowise/core/persistence/decision_graph.py+packages/core/src/repowise/core/persistence/models.py+packages/core/src/repowise/core/persistence/search.py+packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py+packages/core/src/repowise/core/persistence/stores/sql_index_store.py+packages/core/src/repowise/core/persistence/stores/sql_job_store.py+packages/core/src/repowise/core/persistence/stores/_sql_analysis.py+packages/core/src/repowise/core/persistence/stores/_sql_graph_records.py+packages/core/src/repowise/core/persistence/stores/_sql_meta.py+packages/core/src/repowise/core/persistence/stores/__init__.py+packages/core/src/repowise/core/persistence/vector_store/in_memory.py+packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py+packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py+packages/core/src/repowise/core/persistence/vector_store/_base.py+packages/core/src/repowise/core/persistence/vector_store/__init__.py+packages/core/src/repowise/core/persistence/_interfaces/graph_store.py+packages/core/src/repowise/core/persistence/_interfaces/index_store.py+packages/core/src/repowise/core/persistence/_interfaces/job_store.py+packages/core/src/repowise/core/persistence/_interfaces/_analysis.py+packages/core/src/repowise/core/persistence/_interfaces/_graph_records.py+packages/core/src/repowise/core/persistence/_interfaces/_meta.py+packages/core/src/repowise/core/persistence/_interfaces/__init__.py+packages/core/src/repowise/core/persistence/__init__.py+packages/core/src/repowise/core/pipeline/checkpoint.py+packages/core/src/repowise/core/pipeline/modes.py+packages/core/src/repowise/core/pipeline/orchestrator.py+packages/core/src/repowise/core/pipeline/persist.py+packages/core/src/repowise/core/pipeline/phases/analysis.py+packages/core/src/repowise/core/pipeline/phases/generation.py+packages/core/src/repowise/core/pipeline/phases/git.py+packages/core/src/repowise/core/pipeline/phases/ingestion.py+packages/core/src/repowise/core/pipeline/phases/_common.py+packages/core/src/repowise/core/pipeline/phases/__init__.py+packages/core/src/repowise/core/pipeline/phase_timing.py+packages/core/src/repowise/core/pipeline/progress.py+packages/core/src/repowise/core/pipeline/resume/controller.py+packages/core/src/repowise/core/pipeline/resume/ledger.py+packages/core/src/repowise/core/pipeline/resume/phases.py+packages/core/src/repowise/core/pipeline/resume/rehydrate.py+packages/core/src/repowise/core/pipeline/resume/__init__.py+packages/core/src/repowise/core/pipeline/upgrade.py+packages/core/src/repowise/core/pipeline/__init__.py+packages/core/src/repowise/core/providers/embedding/base.py+packages/core/src/repowise/core/providers/embedding/gemini.py+packages/core/src/repowise/core/providers/embedding/ollama.py+packages/core/src/repowise/core/providers/embedding/openai.py+packages/core/src/repowise/core/providers/embedding/openrouter.py+packages/core/src/repowise/core/providers/embedding/registry.py+packages/core/src/repowise/core/providers/embedding/__init__.py+packages/core/src/repowise/core/providers/llm/anthropic.py+packages/core/src/repowise/core/providers/llm/base.py+packages/core/src/repowise/core/providers/llm/codex_cli.py+packages/core/src/repowise/core/providers/llm/deepseek.py+packages/core/src/repowise/core/providers/llm/gemini.py+packages/core/src/repowise/core/providers/llm/litellm.py+packages/core/src/repowise/core/providers/llm/mock.py+packages/core/src/repowise/core/providers/llm/ollama.py+packages/core/src/repowise/core/providers/llm/openai.py+packages/core/src/repowise/core/providers/llm/openrouter.py+packages/core/src/repowise/core/providers/llm/registry.py+packages/core/src/repowise/core/providers/llm/__init__.py+packages/core/src/repowise/core/providers/__init__.py+packages/core/src/repowise/core/rate_limiter.py+packages/core/src/repowise/core/reasoning.py+packages/core/src/repowise/core/registry/cli_registry.py+packages/core/src/repowise/core/registry/mcp_tool_registry.py+packages/core/src/repowise/core/registry/pipeline_hooks.py+packages/core/src/repowise/core/registry/__init__.py+packages/core/src/repowise/core/repo_config.py+packages/core/src/repowise/core/workspace/config.py+packages/core/src/repowise/core/workspace/contracts.py+packages/core/src/repowise/core/workspace/cross_repo.py+packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py+packages/core/src/repowise/core/workspace/extractors/http_extractor.py+packages/core/src/repowise/core/workspace/extractors/service_boundary.py+packages/core/src/repowise/core/workspace/extractors/topic_extractor.py+packages/core/src/repowise/core/workspace/extractors/__init__.py+packages/core/src/repowise/core/workspace/registry.py+packages/core/src/repowise/core/workspace/scanner.py+packages/core/src/repowise/core/workspace/update.py+packages/core/src/repowise/core/workspace/__init__.py+packages/core/src/repowise/core/__init__.pydiff --git a/tests/fixtures/distill/generic_logs.txt b/tests/fixtures/distill/generic_logs.txtnew file mode 100644index 000000000..af103ff52--- /dev/null+++ b/tests/fixtures/distill/generic_logs.txt@@ -0,0 +1,70 @@+2026-06-05 10:12:01,118 INFO uvicorn.access 127.0.0.1:52214 - "GET /api/graph/repo-7f3a/c4/l1 HTTP/1.1" 200+2026-06-05 10:12:01,204 INFO repowise.server.services.c4_builder derived containers count=9 repo=repo-7f3a+2026-06-05 10:12:01,377 INFO uvicorn.access 127.0.0.1:52214 - "GET /api/graph/repo-7f3a/c4/l2 HTTP/1.1" 200+2026-06-05 10:12:02,021 INFO uvicorn.access 127.0.0.1:52215 - "GET /api/health/repo-7f3a/kpis HTTP/1.1" 200+2026-06-05 10:12:02,114 DEBUG repowise.core.persistence pool checkout conn=0x7f3aa1b2c4d8+2026-06-05 10:12:02,118 DEBUG repowise.core.persistence pool checkin conn=0x7f3aa1b2c4d8+2026-06-05 10:12:02,409 INFO uvicorn.access 127.0.0.1:52216 - "GET /api/docs/repo-7f3a/pages HTTP/1.1" 200+2026-06-05 10:12:03,001 DEBUG repowise.core.persistence pool checkout conn=0x7f3aa1b2c4d8+2026-06-05 10:12:03,006 DEBUG repowise.core.persistence pool checkin conn=0x7f3aa1b2c4d8+2026-06-05 10:12:03,118 INFO uvicorn.access 127.0.0.1:52217 - "GET /api/graph/repo-7f3a/nodes?layer=web HTTP/1.1" 200+2026-06-05 10:12:03,544 INFO repowise.core.pipeline.orchestrator phase started phase=ingestion repo=repo-9b1c+2026-06-05 10:12:03,798 DEBUG repowise.core.ingestion.parser parsed file path=packages/web/src/app/page.tsx symbols=14 took_ms=11+2026-06-05 10:12:03,811 DEBUG repowise.core.ingestion.parser parsed file path=packages/web/src/app/layout.tsx symbols=6 took_ms=4+2026-06-05 10:12:03,838 DEBUG repowise.core.ingestion.parser parsed file path=packages/web/src/lib/api.ts symbols=22 took_ms=9+2026-06-05 10:12:03,861 DEBUG repowise.core.ingestion.parser parsed file path=packages/web/src/lib/format.ts symbols=8 took_ms=3+2026-06-05 10:12:03,902 DEBUG repowise.core.ingestion.parser parsed file path=packages/server/src/api/graph.py symbols=31 took_ms=14+2026-06-05 10:12:03,944 DEBUG repowise.core.ingestion.parser parsed file path=packages/server/src/api/docs.py symbols=18 took_ms=8+2026-06-05 10:12:04,012 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/pipeline/orchestrator.py symbols=42 took_ms=21+2026-06-05 10:12:04,118 INFO uvicorn.access 127.0.0.1:52218 - "GET /api/graph/repo-7f3a/c4/l3?container=server HTTP/1.1" 200+2026-06-05 10:12:04,377 WARNING repowise.server.services.c4_builder container has no components container=migrations repo=repo-7f3a+2026-06-05 10:12:04,561 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/ingestion/parser.py symbols=38 took_ms=19+2026-06-05 10:12:04,598 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/ingestion/graph.py symbols=27 took_ms=12+2026-06-05 10:12:04,633 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/analysis/dead_code/analyzer.py symbols=33 took_ms=16+2026-06-05 10:12:04,701 INFO uvicorn.access 127.0.0.1:52219 - "GET /api/health/repo-7f3a/biomarkers HTTP/1.1" 200+2026-06-05 10:12:05,118 ERROR repowise.server.api.chat SSE stream aborted repo=repo-7f3a err=ClientDisconnected attempt=1+2026-06-05 10:12:05,204 INFO repowise.server.api.chat reconnecting stream repo=repo-7f3a backoff_ms=250+2026-06-05 10:12:05,455 INFO uvicorn.access 127.0.0.1:52220 - "GET /api/chat/repo-7f3a/stream HTTP/1.1" 200+2026-06-05 10:12:05,977 DEBUG repowise.core.persistence pool checkout conn=0x7f3aa1b2c4d8+2026-06-05 10:12:05,981 DEBUG repowise.core.persistence pool checkin conn=0x7f3aa1b2c4d8+2026-06-05 10:12:06,099 INFO uvicorn.access 127.0.0.1:52221 - "GET /api/graph/repo-7f3a/nodes?layer=server HTTP/1.1" 200+2026-06-05 10:12:06,381 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/analysis/change_risk.py symbols=19 took_ms=7+2026-06-05 10:12:06,414 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/generation/context/token_budget.py symbols=9 took_ms=3+2026-06-05 10:12:06,467 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/workspace/extractors/http_extractor.py symbols=24 took_ms=13+2026-06-05 10:12:06,521 INFO uvicorn.access 127.0.0.1:52222 - "GET /api/docs/repo-7f3a/page/architecture HTTP/1.1" 200+2026-06-05 10:12:07,004 ERROR repowise.core.pipeline.orchestrator phase failed phase=ingestion repo=repo-9b1c err=UnicodeDecodeError file=packages/legacy/data.bin+2026-06-05 10:12:07,011 INFO repowise.core.pipeline.orchestrator retrying file with latin-1 fallback file=packages/legacy/data.bin+2026-06-05 10:12:07,118 INFO uvicorn.access 127.0.0.1:52223 - "GET /api/graph/repo-7f3a/c4/l1 HTTP/1.1" 200+2026-06-05 10:12:07,392 DEBUG repowise.core.ingestion.parser parsed file path=packages/cli/src/commands/update_cmd.py symbols=29 took_ms=15+2026-06-05 10:12:07,433 DEBUG repowise.core.ingestion.parser parsed file path=packages/cli/src/commands/augment_cmd.py symbols=21 took_ms=9+2026-06-05 10:12:07,489 DEBUG repowise.core.ingestion.parser parsed file path=packages/cli/src/augment_hook.py symbols=4 took_ms=2+2026-06-05 10:12:07,551 INFO uvicorn.access 127.0.0.1:52224 - "GET /api/health/repo-7f3a/trends HTTP/1.1" 200+2026-06-05 10:12:08,118 INFO uvicorn.access 127.0.0.1:52225 - "GET /api/graph/repo-7f3a/c4/l2 HTTP/1.1" 200+2026-06-05 10:12:08,204 DEBUG repowise.core.persistence pool checkout conn=0x7f3aa1b2c4d8+2026-06-05 10:12:08,209 DEBUG repowise.core.persistence pool checkin conn=0x7f3aa1b2c4d8+2026-06-05 10:12:08,377 INFO uvicorn.access 127.0.0.1:52226 - "GET /api/graph/repo-7f3a/nodes?layer=core HTTP/1.1" 200+2026-06-05 10:12:08,561 DEBUG repowise.core.ingestion.parser parsed file path=packages/server/src/mcp_server/tool_context.py symbols=26 took_ms=11+2026-06-05 10:12:08,633 DEBUG repowise.core.ingestion.parser parsed file path=packages/server/src/mcp_server/tool_overview.py symbols=12 took_ms=5+2026-06-05 10:12:08,701 INFO uvicorn.access 127.0.0.1:52227 - "GET /api/decisions/repo-7f3a HTTP/1.1" 200+2026-06-05 10:12:09,118 WARNING repowise.server.api.graph slow query path=/api/graph/repo-7f3a/blast-radius took_ms=1840 threshold_ms=1000+2026-06-05 10:12:09,377 INFO uvicorn.access 127.0.0.1:52228 - "GET /api/graph/repo-7f3a/blast-radius?node=parser HTTP/1.1" 200+2026-06-05 10:12:09,561 DEBUG repowise.core.ingestion.parser parsed file path=packages/web/src/components/chat/chat-interface.tsx symbols=35 took_ms=18+2026-06-05 10:12:09,633 DEBUG repowise.core.ingestion.parser parsed file path=packages/web/src/components/docs/docs-viewer.tsx symbols=28 took_ms=14+2026-06-05 10:12:09,704 INFO uvicorn.access 127.0.0.1:52229 - "GET /api/graph/repo-7f3a/c4/l3?container=web HTTP/1.1" 200+2026-06-05 10:12:10,118 INFO repowise.core.pipeline.orchestrator phase completed phase=ingestion repo=repo-9b1c files=412 took_s=6.6+2026-06-05 10:12:10,377 INFO uvicorn.access 127.0.0.1:52230 - "GET /api/health/repo-9b1c/kpis HTTP/1.1" 200+2026-06-05 10:12:10,561 INFO repowise.core.pipeline.orchestrator phase started phase=graph repo=repo-9b1c+2026-06-05 10:12:10,633 DEBUG repowise.core.persistence pool checkout conn=0x7f3aa1b2c4d8+2026-06-05 10:12:10,638 DEBUG repowise.core.persistence pool checkin conn=0x7f3aa1b2c4d8+2026-06-05 10:12:11,118 INFO uvicorn.access 127.0.0.1:52231 - "GET /api/graph/repo-9b1c/c4/l1 HTTP/1.1" 200+2026-06-05 10:12:11,377 ERROR repowise.server.api.chat SSE stream aborted repo=repo-7f3a err=ClientDisconnected attempt=2+2026-06-05 10:12:11,402 INFO repowise.server.api.chat reconnecting stream repo=repo-7f3a backoff_ms=500+2026-06-05 10:12:11,561 INFO uvicorn.access 127.0.0.1:52232 - "GET /api/chat/repo-7f3a/stream HTTP/1.1" 200+2026-06-05 10:12:12,118 INFO uvicorn.access 127.0.0.1:52233 - "GET /api/graph/repo-9b1c/c4/l2 HTTP/1.1" 200+2026-06-05 10:12:12,377 DEBUG repowise.core.ingestion.parser parsed file path=packages/core/src/distill/router.py symbols=7 took_ms=3+2026-06-05 10:12:12,561 INFO uvicorn.access 127.0.0.1:52234 - "GET /api/docs/repo-9b1c/pages HTTP/1.1" 200+2026-06-05 10:12:13,118 INFO repowise.core.pipeline.orchestrator phase completed phase=graph repo=repo-9b1c nodes=2841 edges=11427 took_s=2.4+2026-06-05 10:12:13,377 INFO uvicorn.access 127.0.0.1:52235 - "GET /api/health/repo-9b1c/biomarkers HTTP/1.1" 200+2026-06-05 10:12:14,118 INFO uvicorn.access 127.0.0.1:52236 - "GET /api/graph/repo-9b1c/nodes?layer=core HTTP/1.1" 200+2026-06-05 10:12:14,377 INFO uvicorn.access 127.0.0.1:52237 - "GET /api/decisions/repo-9b1c HTTP/1.1" 200+2026-06-05 10:12:15,118 INFO uvicorn.access 127.0.0.1:52238 - "GET /api/graph/repo-9b1c/c4/l3?container=core HTTP/1.1" 200diff --git a/tests/fixtures/distill/git_diff_large.txt b/tests/fixtures/distill/git_diff_large.txtnew file mode 100644index 000000000..434b21129--- /dev/null+++ b/tests/fixtures/distill/git_diff_large.txt@@ -0,0 +1,5157 @@+diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.py+index d0be19e4..7fb48981 100644+--- a/packages/cli/src/repowise/cli/commands/health_cmd.py++++ b/packages/cli/src/repowise/cli/commands/health_cmd.py+@@ -8,6 +8,7 @@ back to a live in-process analysis when run outside an indexed repo.+ from __future__ import annotations++ import json++from pathlib import Path++ import click+ from rich.table import Table+@@ -215,6 +216,7 @@ def health_command(+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ coverage_map=coverage_map,++ duplication_cache_dir=Path(repo_path) / ".repowise",+ )+ # Load any .repowise/health-rules.json the user keeps in the repo.+ from repowise.core.analysis.health.config import HealthConfig+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 d4c2098d..f33de34b 100644+--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py++++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py+@@ -47,6 +47,8 @@ from repowise.cli.providers import resolve_embedder+ from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json+ from repowise.cli.ui import (+ BRAND,++ BRAND_STYLE,++ OWL_SPINNER,+ MaybeCountColumn,+ RichProgressCallback,+ interactive_advanced_config,+@@ -455,7 +457,7 @@ def init_command(+ scan_info = None+ if is_interactive:+ print_banner(console, repo_name=repo_path.name)+- with console.status(" Scanning repository…", spinner="dots"):++ with console.status(" Scanning repository…", spinner=OWL_SPINNER):+ scan_info = quick_repo_scan(repo_path)+ print_scan_summary(console, scan_info)+ mode = interactive_mode_select(console)+@@ -616,7 +618,7 @@ def init_command(+ # Validate provider connection+ from repowise.core.providers.llm.base import ProviderError++- with console.status(" Verifying provider connection…", spinner="dots"):++ with console.status(" Verifying provider connection…", spinner=OWL_SPINNER):+ try:+ run_async(+ provider.generate(+@@ -645,7 +647,7 @@ def init_command(+ orchestrator_mode = OrchestratorMode.FAST if run_mode == "fast" else OrchestratorMode.STANDARD++ with Progress(+- SpinnerColumn(),++ SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ MaybeCountColumn(),+@@ -708,9 +710,11 @@ def init_command(+ with cancellation_scope():+ result = run_async(_index_with_resume())+ except (PipelineCancelled, KeyboardInterrupt):++ from repowise.cli.ui.mascot import EYES_SLEEPY, mini+++ console.print(+- "\n[yellow]Interrupted.[/] Indexed work so far has been saved — "+- "run [bold]repowise init --resume[/] to continue where it stopped."++ f"\n{mini(EYES_SLEEPY)} [yellow]Interrupted.[/] Indexed work so far has been "++ "saved — run [bold]repowise init --resume[/] to continue where it stopped."+ )+ return++@@ -757,7 +761,7 @@ def init_command(+ console, 4, total_phases, "Persistence", "Saving to database and building search index"+ )++- with console.status(" Persisting to database…", spinner="dots"):++ with console.status(" Persisting to database…", spinner=OWL_SPINNER):+ run_async(persist_result(result, repo_path))+ console.print(" [green]✓[/green] Database updated")++diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py+index 29ecf4b8..ca41107e 100644+--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py++++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py+@@ -27,7 +27,7 @@ from repowise.cli.providers import (+ build_vector_store,+ flush_cost_tracker,+ )+-from repowise.cli.ui import MaybeCountColumn, RichProgressCallback++from repowise.cli.ui import BRAND_STYLE, OWL_SPINNER, MaybeCountColumn, RichProgressCallback++ # The LLM-cost confirmation threshold. A run whose estimate exceeds this asks+ # for confirmation (unless ``--yes``); below it generation proceeds silently.+@@ -187,7 +187,7 @@ def _enrich_knowledge_graph(+ result.knowledge_graph_result = _run()+ return++- with console.status(" Enriching knowledge graph (layers + tour)…", spinner="dots"):++ with console.status(" Enriching knowledge graph (layers + tour)…", spinner=OWL_SPINNER):+ try:+ result.knowledge_graph_result = _run()+ enriched = result.knowledge_graph_result+@@ -237,7 +237,7 @@ def run_repo_generation(+ provider._cost_tracker = cost_tracker++ with Progress(+- SpinnerColumn(),++ SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ MaybeCountColumn(),+diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+index 84c9a05c..f0e15b7d 100644+--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py++++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+@@ -45,6 +45,8 @@ from repowise.cli.providers import resolve_embedder+ from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json+ from repowise.cli.ui import (+ BRAND,++ BRAND_STYLE,++ OWL_SPINNER,+ MaybeCountColumn,+ RichProgressCallback,+ interactive_advanced_config,+@@ -211,7 +213,7 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCt++ try:+ with Progress(+- SpinnerColumn(),++ SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ MaybeCountColumn(),+diff --git a/packages/cli/src/repowise/cli/commands/reindex_cmd.py b/packages/cli/src/repowise/cli/commands/reindex_cmd.py+index 17e9cee6..30c794bc 100644+--- a/packages/cli/src/repowise/cli/commands/reindex_cmd.py++++ b/packages/cli/src/repowise/cli/commands/reindex_cmd.py+@@ -12,6 +12,7 @@ from repowise.cli.helpers import (+ resolve_repo_path,+ run_async,+ )++from repowise.cli.ui import BRAND_STYLE, OWL_SPINNER+++ @click.command("reindex")+@@ -115,7 +116,7 @@ async def _reindex(repo_path, embedder_name: str, batch_size: int) -> None:+ failed = 0++ with Progress(+- SpinnerColumn(),++ SpinnerColumn(spinner_name=OWL_SPINNER, style=BRAND_STYLE),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TextColumn("{task.completed}/{task.total}"),+diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py+index ed1b58ca..1dd532e8 100644+--- a/packages/cli/src/repowise/cli/commands/update_cmd.py++++ b/packages/cli/src/repowise/cli/commands/update_cmd.py+@@ -346,22 +346,45 @@ def _build_repo_graph(+ """+ from pathlib import Path as PathlibPath++- from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder, compute_content_hash++ traverser = FileTraverser(repo_path, extra_exclude_patterns=exclude_patterns or None)+ file_infos = list(traverser.traverse())+ repo_structure = traverser.get_repo_structure()++- parser = ASTParser()++ # Content-hash parse cache: an incremental update re-ingests the whole++ # repo, but only the changed files actually need a tree-sitter parse.++ # Best-effort — any cache failure falls back to a full parse.++ parse_cache = None++ try:++ from repowise.core.ingestion.parse_cache import ParseCache++++ parse_cache = ParseCache(PathlibPath(repo_path) / ".repowise")++ parse_cache.load()++ except Exception:++ parse_cache = None++++ parser: Any = None # constructed lazily — every-file-cached updates skip query compilation+ parsed_files: list = []+ source_map: dict[str, bytes] = {}+- graph_builder = GraphBuilder(repo_path, exclude_patterns=exclude_patterns)++ graph_builder = GraphBuilder(++ repo_path,++ exclude_patterns=exclude_patterns,++ centrality_cache_dir=PathlibPath(repo_path) / ".repowise",++ )++ skipped = 0+ for fi in file_infos:+ try:+ source = PathlibPath(fi.abs_path).read_bytes()+- parsed = parser.parse_file(fi, source)++ content_hash = compute_content_hash(source)++ parsed = parse_cache.get(fi, content_hash) if parse_cache is not None else None++ if parsed is None:++ if parser is None:++ parser = ASTParser()++ parsed = parser.parse_file(fi, source)++ if parse_cache is not None:++ parse_cache.put(parsed, content_hash)+ except Exception:+ skipped += 1+ continue+@@ -370,6 +393,8 @@ def _build_repo_graph(+ source_map[fi.path] = source+ graph_builder.add_file(parsed)+ graph_builder.build()++ if parse_cache is not None:++ parse_cache.save()++ if skipped:+ console.print(f"[yellow]Skipped {skipped} file(s) that failed to parse.[/yellow]")+@@ -393,10 +418,16 @@ def _rebuild_graph_and_git(+ file_diffs: list,+ cfg: dict,+ exclude_patterns: list[str],++ git_tier: str | None = None,+ ) -> tuple[list, dict[str, bytes], Any, Any, int, dict[str, dict]]:+ """Re-traverse + parse the repo, rebuild the graph (+ framework edges), and+ re-index git metadata for the changed files.+++ ``git_tier`` is the persisted ``state.json:git_tier`` value: a fast-mode++ (ESSENTIAL) repo must not pay per-file blame on every update for signals++ its index never had. Unknown/missing values fall back to FULL, matching++ the historical behavior for legacy state files.+++ Returns ``(parsed_files, source_map, graph_builder, repo_structure,+ file_count, git_meta_map)``.+ """+@@ -409,7 +440,12 @@ def _rebuild_graph_and_git(+ git_meta_map: dict[str, dict] = {}+ try:+ from repowise.core.ingestion.git_indexer import GitIndexer++ from repowise.core.ingestion.git_indexer.tiers import GitIndexTier+++ try:++ tier = GitIndexTier(git_tier) if git_tier else GitIndexTier.FULL++ except ValueError:++ tier = GitIndexTier.FULL+ _commit_limit = cfg.get("commit_limit")+ _follow_renames = cfg.get("follow_renames", False)+ git_indexer = GitIndexer(+@@ -417,6 +453,7 @@ def _rebuild_graph_and_git(+ commit_limit=_commit_limit,+ follow_renames=_follow_renames,+ exclude_patterns=exclude_patterns or None,++ tier=tier,+ )+ changed_paths = _build_filtered_changed_paths(file_diffs, exclude_patterns)+ updated_meta = run_async(git_indexer.index_changed_files(changed_paths))+@@ -425,6 +462,16 @@ def _rebuild_graph_and_git(+ except Exception as exc:+ console.print(f"[yellow]Git re-index skipped: {exc}[/yellow]")+++ # Pre-compute centrality/community metrics with the init path's fan-out++ # parallelism. Without this, persist_graph_nodes computes the same++ # metrics lazily one-by-one. Runs after the co-change edge refresh so++ # the cached subgraphs reflect the final structure. Best-effort: every++ # metric still falls back to lazy computation.++ try:++ run_async(graph_builder.compute_metrics_parallel())++ except Exception as exc:++ console.print(f"[yellow]Metric pre-computation skipped: {exc}[/yellow]")+++ return parsed_files, source_map, graph_builder, repo_structure, file_count, git_meta_map+++@@ -453,6 +500,7 @@ def _run_partial_analysis(+ graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,++ duplication_cache_dir=Path(repo_path) / ".repowise",+ )+ _health_changed = {fd.path for fd in file_diffs if fd.status in ("added", "modified")}+ if _health_changed:+@@ -675,6 +723,13 @@ def _run_full_health_rescore(+ repo_path, exclude_patterns+ )+++ # Fan-out metric precompute (mirrors _rebuild_graph_and_git) — the++ # rescore persists graph nodes too, which reads every metric.++ try:++ run_async(graph_builder.compute_metrics_parallel())++ except Exception:++ pass # metrics fall back to lazy computation+++ exclude_spec = (+ pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)+ if exclude_patterns+@@ -737,6 +792,7 @@ def _run_full_health_rescore(+ graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,++ duplication_cache_dir=Path(repo_path) / ".repowise",+ )+ hcfg = HealthConfig.load(repo_path)+ analyzer_config = (+@@ -1082,26 +1138,15 @@ def update_command(+ console.print(f" [{color}]{fd.status:>10}[/{color}] {fd.path}")++ # Re-parse changed files and rebuild graph for affected pages+- from repowise.core.generation import ContextAssembler, GenerationConfig, PageGenerator+-+ cfg = load_config(repo_path)+- language = cfg.get("language", "en")+- # Config-driven (saved by `repowise init`); CLI override not surfaced+- # on update yet — defaults to on to keep the onboarding collection+- # fresh as the codebase evolves.+- enable_onboarding_cfg = bool(cfg.get("enable_onboarding", True))+- config = GenerationConfig(+- max_concurrency=concurrency,+- language=language,+- reasoning=resolve_reasoning(reasoning, cfg),+- enable_onboarding=enable_onboarding_cfg,+- )++ # Read exclude patterns from config (set during init or via web UI)+ exclude_patterns: list[str] = list(cfg.get("exclude_patterns") or [])++ parsed_files, source_map, graph_builder, repo_structure, file_count, git_meta_map = (+- _rebuild_graph_and_git(repo_path, file_diffs, cfg, exclude_patterns)++ _rebuild_graph_and_git(++ repo_path, file_diffs, cfg, exclude_patterns, git_tier=state.get("git_tier")++ )+ )++ # Determine affected pages (auto-scale budget if not explicitly set)+@@ -1145,6 +1190,23 @@ def update_command(+ )+ return+++ # The generation/LLM layer is only needed past this point — importing it++ # above the index-only branch would make every index-only update (the++ # post-commit hook's hot path) pay the import for code it never runs.++ from repowise.core.generation import ContextAssembler, GenerationConfig, PageGenerator++++ language = cfg.get("language", "en")++ # Config-driven (saved by `repowise init`); CLI override not surfaced++ # on update yet — defaults to on to keep the onboarding collection++ # fresh as the codebase evolves.++ enable_onboarding_cfg = bool(cfg.get("enable_onboarding", True))++ config = GenerationConfig(++ max_concurrency=concurrency,++ language=language,++ reasoning=resolve_reasoning(reasoning, cfg),++ enable_onboarding=enable_onboarding_cfg,++ )+++ provider = resolve_provider(provider_name, model, repo_path=repo_path)++ # Attach a DB-backed CostTracker so every LLM call made during this update+diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude.py b/packages/cli/src/repowise/cli/editor_integrations/claude.py+index 42c6cda6..ba721988 100644+--- a/packages/cli/src/repowise/cli/editor_integrations/claude.py++++ b/packages/cli/src/repowise/cli/editor_integrations/claude.py+@@ -123,8 +123,11 @@ def maybe_generate_claude_md(+ return+ if not _claude_md_enabled(repo_path):+ return++++ from repowise.cli.ui import OWL_SPINNER+++ try:+- with console_obj.status(" Generating .claude/CLAUDE.md…", spinner="dots"):++ with console_obj.status(" Generating .claude/CLAUDE.md…", spinner=OWL_SPINNER):+ run_async(_write_claude_md_async(repo_path))+ console_obj.print(" [green]✓[/green] .claude/CLAUDE.md updated")+ except Exception as exc:+diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex.py b/packages/cli/src/repowise/cli/editor_integrations/codex.py+index a6310d50..e8cf602c 100644+--- a/packages/cli/src/repowise/cli/editor_integrations/codex.py++++ b/packages/cli/src/repowise/cli/editor_integrations/codex.py+@@ -123,6 +123,7 @@ def maybe_generate_agents_md(++ from repowise.cli.editor_files import should_generate_editor_file+ from repowise.cli.helpers import run_async++ from repowise.cli.ui import OWL_SPINNER++ if not should_generate_editor_file(+ repo_path,+@@ -132,7 +133,7 @@ def maybe_generate_agents_md(+ ):+ return+ try:+- with console_obj.status(" Generating AGENTS.md...", spinner="dots"):++ with console_obj.status(" Generating AGENTS.md...", spinner=OWL_SPINNER):+ run_async(_write_agents_md_async(repo_path))+ console_obj.print(" [green]✓[/green] AGENTS.md updated")+ except Exception as exc:+diff --git a/packages/cli/src/repowise/cli/ui/__init__.py b/packages/cli/src/repowise/cli/ui/__init__.py+index 7a37e3fa..b3a28a40 100644+--- a/packages/cli/src/repowise/cli/ui/__init__.py++++ b/packages/cli/src/repowise/cli/ui/__init__.py+@@ -19,6 +19,12 @@ from repowise.cli.ui.brand import (+ print_phase_header,+ )+ from repowise.cli.ui.env_persistence import load_dotenv++from repowise.cli.ui.mascot import (++ OWL_SPINNER,++ THINKING_FRAMES,++ banner_text,++ mini,++)+ from repowise.cli.ui.mode_selection import (+ LARGE_REPO_FILE_THRESHOLD,+ interactive_advanced_config,+@@ -55,11 +61,14 @@ __all__ = [+ "ERR",+ "LARGE_REPO_FILE_THRESHOLD",+ "OK",++ "OWL_SPINNER",++ "THINKING_FRAMES",+ "WARN",+ "MaybeCountColumn",+ "ProviderSelection",+ "RepoScanInfo",+ "RichProgressCallback",++ "banner_text",+ "build_analysis_summary_panel",+ "build_completion_panel",+ "build_contextual_next_steps",+@@ -72,6 +81,7 @@ __all__ = [+ "interactive_provider_select",+ "interactive_repo_select",+ "load_dotenv",++ "mini",+ "print_banner",+ "print_index_only_intro",+ "print_phase_header",+diff --git a/packages/cli/src/repowise/cli/ui/brand.py b/packages/cli/src/repowise/cli/ui/brand.py+index 5814f1c1..9e2a57fa 100644+--- a/packages/cli/src/repowise/cli/ui/brand.py++++ b/packages/cli/src/repowise/cli/ui/brand.py+@@ -3,8 +3,8 @@+ from __future__ import annotations++ from rich.console import Console++from rich.markup import escape+ from rich.rule import Rule+-from rich.text import Text++ # ---------------------------------------------------------------------------+ # Brand / theme+@@ -18,24 +18,33 @@ WARN = "yellow"+ ERR = "bold red"++ # ---------------------------------------------------------------------------+-# ASCII art — bold half-block, compact lowercase, 2 lines++# Banner — owl mascot + heatmap wordmark (art lives in ui/mascot.py)+ # ---------------------------------------------------------------------------++-_LOGO = " █▀█ █▀▀ █▀█ █▀█ █ █ █ ▀ █▀▀ █▀▀\n █▀▄ ██▄ █▀▀ █▄█ ▀▄▀▄▀ █ ▄▄█ ██▄"++# Breathing room required beyond the rendered banner width before we pick the++# full variant; below that we fall back to compact (same design, 1-char strokes).++_BANNER_WIDTH_MARGIN = 4+++ def print_banner(console: Console, repo_name: str | None = None) -> None:+- """Print the repowise logo, tagline, and optional repo name."""++ """Print the repowise owl banner, tagline, and optional repo name."""+ from repowise.cli import __version__++ from repowise.cli.ui import mascot+++ compact = console.width < mascot.banner_width() + _BANNER_WIDTH_MARGIN+ console.print()+- console.print(Text(_LOGO, style=BRAND_STYLE))+- console.print(+- f" [dim]codebase intelligence for developers and AI[/dim] [dim]v{__version__}[/dim]"+- )++ console.print(mascot.banner_text(repo_name, compact=compact))++ console.print()++ if compact:++ console.print(f" [dim]codebase intelligence · v{__version__}[/dim]", highlight=False)++ else:++ console.print(++ f" [dim]codebase intelligence for developers and AI · v{__version__}[/dim]",++ highlight=False,++ )+ if repo_name:+ console.print()+- console.print(f" Repository: [bold]{repo_name}[/bold]")++ console.print(f" Repository: [bold]{escape(repo_name)}[/bold]", highlight=False)+ console.print()+++diff --git a/packages/cli/src/repowise/cli/ui/mascot.py b/packages/cli/src/repowise/cli/ui/mascot.py+new file mode 100644+index 00000000..ca2e7c9e+--- /dev/null++++ b/packages/cli/src/repowise/cli/ui/mascot.py+@@ -0,0 +1,212 @@++"""Owl mascot: banner art, state frames, and the heatmap wordmark.++++Single home for every piece of the init-banner identity: the owl, the++REPOWISE block wordmark (full + compact variants), the GitHub-heatmap++colouring, and the spinner frames used while repowise thinks.++++All render functions are pure and deterministic — the heatmap pattern is++seeded from the repo name, so the same repo always gets the same banner.++"""++++from __future__ import annotations++++import zlib++from functools import cache++from random import Random++++from rich.text import Text++++from repowise.cli.ui.brand import BRAND++++# ---------------------------------------------------------------------------++# Palette++# ---------------------------------------------------------------------------++++WHITE = "#E8E8E8" # owl body strokes (logo white)++++# Floored 5-shade heatmap ramp: deep ember → blazing. No near-black shade so++# the wordmark always reads, even at the cold end of the gradient.++HEAT = ["#5C3208", "#9C5710", "#D97A16", "#F59520", "#FFC06A"]++++# ---------------------------------------------------------------------------++# Owl++# ---------------------------------------------------------------------------++++OWL_FULL = [++ " ,_____,",++ " (◉ , ◉)",++ " ( ▼ )",++ " /)___(\\",++ ' " " ',++]++++OWL_COMPACT = [++ " ,___,",++ " (◉,◉)",++ " ( ▼ )",++ " /)_(\\",++ ' " " ',++]++++EYES_THINKING = ["◐", "◓", "◑", "◒"] # eye-roll cycle (spinner frames)++EYES_IDLE = "◉"++EYES_SLEEPY = "─" # interrupt message++EYES_HAPPY = "^" # completion panels++EYES_ERROR = "x" # reserved: error output deliberately stays sober (no owl) for now++++++def mini(eyes: str = EYES_IDLE) -> str:++ """Single-line mini owl face, e.g. ``{◉ ◉}`` — always 5 chars wide."""++ return "{" + eyes + " " + eyes + "}"++++++THINKING_FRAMES = [mini(e) for e in EYES_THINKING]++++# ---------------------------------------------------------------------------++# Spinner registration — ``rich._spinners.SPINNERS`` is private API (a plain++# dict consumed by ``rich.spinner.Spinner``), so registration is wrapped: if a++# future rich version moves it, everything silently stays on "dots". Always++# reference ``OWL_SPINNER`` at call sites, never the literal ``"owl"``.++# ---------------------------------------------------------------------------++++try:++ from rich._spinners import SPINNERS++++ SPINNERS["owl"] = {"interval": 200, "frames": THINKING_FRAMES}++ OWL_SPINNER = "owl"++except Exception: # pragma: no cover — depends on rich internals++ OWL_SPINNER = "dots"++++# ---------------------------------------------------------------------------++# Wordmark fonts — half-block finished letterforms (R tail = stepped taper).++# FONT_FULL uses 2-char stroke cells; FONT_COMPACT is the same design at++# 1-char strokes for narrow terminals.++# ---------------------------------------------------------------------------++++FONT_FULL = {++ "R": ["██████▄", "██ ██", "██████▀", "██ ▀█▄ ", "██ ▀█▄"],++ "E": ["██████", "██ ", "█████ ", "██ ", "██████"],++ "P": ["██████▄", "██ ██", "██████▀", "██ ", "██ "],++ "O": ["▄█████▄", "██ ██", "██ ██", "██ ██", "▀█████▀"],++ "W": ["██ ██", "██ ██", "██ █ ██", "██ ███ ██", "▀██▀ ▀██▀"],++ "I": ["████", " ██ ", " ██ ", " ██ ", "████"],++ "S": ["▄█████▄", "██ ", "▀█████▄", " ██", "▀█████▀"],++}++++FONT_COMPACT = {++ "R": ["███▄ ", "█ █ ", "███▀ ", "█ ▀▄ ", "█ ▀▄"],++ "E": ["███", "█ ", "██ ", "█ ", "███"],++ "P": ["███▄", "█ █", "███▀", "█ ", "█ "],++ "O": ["▄██▄", "█ █", "█ █", "█ █", "▀██▀"],++ "W": ["█ █", "█ █", "█ █ █", "█ █ █", "▀█▀█▀"],++ "I": ["███", " █ ", " █ ", " █ ", "███"],++ "S": ["▄██▄", "█ ", "▀██▄", " █", "▀██▀"],++}++++_WORD = "REPOWISE"++++++@cache++def render_wordmark(compact: bool = False) -> tuple[tuple[str, ...], tuple[int, ...]]:++ """Wordmark rows + per-column heat-cell ids.++++ Cell ids are aligned to each letter's own grid (one cell = ``cell_w``++ columns starting at the letter's left edge) so every coloured unit is a++ true square — a cell never slices a stroke or bleeds across the++ inter-letter gap. Gap columns map to ``-1`` (unpainted).++ """++ font = FONT_COMPACT if compact else FONT_FULL++ cell_w = 1 if compact else 2++ gap = 1 if compact else 2++++ rows = ["", "", "", "", ""]++ cellmap: list[int] = []++ cell_base = 0++ for li, ch in enumerate(_WORD):++ glyph = font[ch]++ width = len(glyph[0])++ n_cells = (width + cell_w - 1) // cell_w++ for lx in range(width):++ cellmap.append(cell_base + min(lx // cell_w, n_cells - 1))++ cell_base += n_cells++ for r in range(5):++ rows[r] += glyph[r]++ if li < len(_WORD) - 1:++ for r in range(5):++ rows[r] += " " * gap++ cellmap.extend([-1] * gap)++ return tuple(rows), tuple(cellmap)++++++def banner_width(compact: bool = False) -> int:++ """Total rendered banner width in columns (indent + owl + gap + wordmark).++++ Single source of truth for layout maths — ``print_banner`` derives its++ full/compact switch threshold from this, so font or owl changes can't++ silently desync the two.++ """++ owl = OWL_COMPACT if compact else OWL_FULL++ rows, _ = render_wordmark(compact)++ return 1 + max(len(line) for line in owl) + 2 + len(rows[0])++++++def seed_for(repo_name: str | None) -> int:++ """Stable cross-process seed for a repo's heatmap pattern.++++ Uses ``zlib.crc32`` deliberately — the built-in ``hash()`` is salted per++ process, which would give every run a different banner.++ """++ return zlib.crc32((repo_name or "repowise").encode())++++++def heat_grid(seed: int, n_cells: int) -> list[list[int]]:++ """Gradient + jitter shade grid (5 rows by *n_cells*), deterministic.++++ Base shade sweeps linearly left→right across cells; each cell jitters++ ±1 shade around the sweep, clamped to the palette bounds.++ """++ rng = Random(seed)++ span = max(n_cells - 1, 1)++ grid = [[0] * n_cells for _ in range(5)]++ for r in range(5):++ for c in range(n_cells):++ base = (c / span) * (len(HEAT) - 1)++ idx = round(base + rng.uniform(-1.1, 1.1))++ grid[r][c] = min(max(idx, 0), len(HEAT) - 1)++ return grid++++++def _paint_owl(line: str) -> Text:++ """Owl strokes in logo white, eyes in brand orange."""++ out = Text()++ for ch in line:++ if ch == EYES_IDLE:++ out.append(ch, style=f"bold {BRAND}")++ elif ch == " ":++ out.append(" ")++ else:++ out.append(ch, style=f"bold {WHITE}")++ return out++++++def banner_text(repo_name: str | None, compact: bool = False) -> Text:++ """Compose owl + heatmap wordmark into a single renderable ``Text``."""++ owl = OWL_COMPACT if compact else OWL_FULL++ rows, cellmap = render_wordmark(compact)++ n_cells = max(c for c in cellmap if c >= 0) + 1++ grid = heat_grid(seed_for(repo_name), n_cells)++++ owl_w = max(len(line) for line in owl)++ out = Text()++ for r in range(5):++ if r:++ out.append("\n")++ out.append(" ")++ out.append_text(_paint_owl(owl[r].ljust(owl_w)))++ out.append(" ")++ for x, ch in enumerate(rows[r]):++ if ch == " " or cellmap[x] < 0:++ out.append(" ")++ else:++ out.append(ch, style=f"bold {HEAT[grid[r][cellmap[x]]]}")++ return out+diff --git a/packages/cli/src/repowise/cli/ui/result_panels.py b/packages/cli/src/repowise/cli/ui/result_panels.py+index 1d09e8f4..31ddff66 100644+--- a/packages/cli/src/repowise/cli/ui/result_panels.py++++ b/packages/cli/src/repowise/cli/ui/result_panels.py+@@ -10,6 +10,7 @@ from rich.table import Table+ from rich.text import Text++ from repowise.cli.ui.brand import BRAND++from repowise.cli.ui.mascot import EYES_HAPPY, mini+++ def build_analysis_summary_panel(+@@ -79,10 +80,12 @@ def build_completion_panel(+ *,+ next_steps: list[tuple[str, str]] | None = None,+ ) -> Panel:+- """Build a bordered summary panel.++ """Build a bordered summary panel, titled with the happy owl.++ *metrics* is a list of ``(label, value)`` pairs.+ *next_steps* is an optional list of ``(command, description)`` pairs.++ The mascot prefix lives here (not at call sites) so every completion++ panel gets it consistently.+ """+ table = Table(box=None, padding=(0, 2), show_header=False)+ table.add_column("Metric", style="dim", min_width=20)+@@ -101,7 +104,7 @@ def build_completion_panel(++ return Panel(+ Group(*parts),+- title=f"[bold]{title}[/bold]",++ title=f"[bold]{mini(EYES_HAPPY)} {title}[/bold]",+ border_style=BRAND,+ padding=(1, 1),+ )+diff --git a/packages/core/alembic/versions/0030_agent_provenance.py b/packages/core/alembic/versions/0030_agent_provenance.py+new file mode 100644+index 00000000..a11e79e9+--- /dev/null++++ b/packages/core/alembic/versions/0030_agent_provenance.py+@@ -0,0 +1,55 @@++"""Agent-provenance columns on git_commits + git_metadata.++++Per-commit: which coding agent (if any) authored the commit, its autonomy tier++(1 near-autonomous bot account · 2 human-driven agent · 3 assisted), the++attribution channel, and a confidence band. Per-file: the rollup share of++agent-attributed commits and the tier breakdown. Classification is++deterministic local-git pattern matching (identity fields, message footers,++co-author trailers) riding the existing commit-index walk — no extra git pass,++no network. All columns are nullable / defaulted and back-populated on the++next index.++++Revision ID: 0030++Revises: 0029++Create Date: 2026-06-04++"""++++from __future__ import annotations++++from collections.abc import Sequence++++import sqlalchemy as sa++from alembic import op++++# revision identifiers++revision: str = "0030"++down_revision: str | None = "0029"++branch_labels: str | Sequence[str] | None = None++depends_on: str | Sequence[str] | None = None++++++def upgrade() -> None:++ op.add_column("git_commits", sa.Column("agent_name", sa.String(32), nullable=True))++ op.add_column("git_commits", sa.Column("agent_autonomy_tier", sa.Integer, nullable=True))++ op.add_column("git_commits", sa.Column("agent_channel", sa.String(32), nullable=True))++ op.add_column("git_commits", sa.Column("agent_confidence", sa.String(8), nullable=True))++++ op.add_column(++ "git_metadata",++ sa.Column("agent_commit_count", sa.Integer, nullable=False, server_default="0"),++ )++ op.add_column("git_metadata", sa.Column("agent_authored_pct", sa.Float, nullable=True))++ op.add_column(++ "git_metadata",++ sa.Column("agent_tier_counts_json", sa.Text, nullable=False, server_default="{}"),++ )++++++def downgrade() -> None:++ op.drop_column("git_metadata", "agent_tier_counts_json")++ op.drop_column("git_metadata", "agent_authored_pct")++ op.drop_column("git_metadata", "agent_commit_count")++ op.drop_column("git_commits", "agent_confidence")++ op.drop_column("git_commits", "agent_channel")++ op.drop_column("git_commits", "agent_autonomy_tier")++ op.drop_column("git_commits", "agent_name")+diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+index de9bb014..e87adeb0 100644+--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py++++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+@@ -12,7 +12,10 @@ this package.+ from __future__ import annotations++ import fnmatch++import os++import re+ from datetime import UTC, datetime++from functools import lru_cache+ from pathlib import Path+ from typing import Any++@@ -321,6 +324,20 @@ def _is_synthetic_node(node: str) -> bool:+ return node.startswith("external:") or node.startswith("framework:")++++@lru_cache(maxsize=8)++def _never_flag_regex(patterns: tuple[str, ...]) -> re.Pattern[str]:++ """Compile *patterns* into one alternation regex equivalent to fnmatch.++++ ``fnmatch.fnmatch(path, p)`` normcases both sides and matches the++ translated glob; doing that per (node x pattern) costs ~540 fnmatch++ calls per node and dominated the whole dead-code pass (measured: 50s of++ a 51s analyze() on a 13k-node graph, mostly Windows ``normcase``).++ One pre-normcased alternation keeps the exact same match semantics at++ one regex match per node.++ """++ return re.compile("|".join(fnmatch.translate(os.path.normcase(p)) for p in patterns))+++++ class DeadCodeAnalyzer:+ """Detects unreachable files, unused exports, unused internals, and+ zombie packages using the dependency graph and git metadata.+@@ -1138,9 +1155,8 @@ class DeadCodeAnalyzer:+ """Return True if path should never be flagged as dead."""+ if path in whitelist:+ return True+- for pattern in _NEVER_FLAG_PATTERNS:+- if fnmatch.fnmatch(path, pattern):+- return True++ if _never_flag_regex(_NEVER_FLAG_PATTERNS).match(os.path.normcase(path)):++ return True+ # Workspace-driven never-flag — set by language warmups that read+ # the build manifest (Gradle non-``main`` source sets, Cargo+ # ``[[example]]`` / ``[[bench]]`` targets, …). Lets each language+diff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.py+index 7396669a..dfaaedb2 100644+--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py++++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py+@@ -34,7 +34,7 @@ from repowise.core.cancellation import check_cancelled++ from .limits import DuplicationDiagnostics, DuplicationLimits, looks_minified+ from .rabin_karp import WindowHash, index_by_hash, rolling_hashes+-from .tokenizer import Token, tokenize_file++from .tokenizer import tokenize_file++ log = structlog.get_logger(__name__)++@@ -132,19 +132,21 @@ def _co_change_score(+++ def _tokens_equal(+- a_tokens: list[Token],+- b_tokens: list[Token],++ a_kinds: list[str],++ b_kinds: list[str],+ a_start: int,+ b_start: int,+ window: int,+ ) -> bool:+- """Verify hash-collision by comparing token ``kind`` sequences."""+- if a_start + window > len(a_tokens) or b_start + window > len(b_tokens):++ """Verify hash-collision by comparing token ``kind`` sequences.++++ Operates on the per-file kind list (all the verifier ever compared of++ the full ``Token`` records) so cached token streams round-trip without++ rebuilding Token objects.++ """++ if a_start + window > len(a_kinds) or b_start + window > len(b_kinds):+ return False+- for offset in range(window):+- if a_tokens[a_start + offset].kind != b_tokens[b_start + offset].kind:+- return False+- return True++ return a_kinds[a_start : a_start + window] == b_kinds[b_start : b_start + window]+++ def _merge_adjacent_pairs(raw: list[ClonePair]) -> list[ClonePair]:+@@ -195,6 +197,7 @@ def detect_clones(+ window_tokens: int = DEFAULT_WINDOW_TOKENS,+ min_lines: int = DEFAULT_MIN_LINES,+ limits: DuplicationLimits | None = None,++ cache_dir: Path | None = None,+ ) -> DuplicationReport:+ """Run the duplication pipeline over the supplied parsed files.++@@ -216,14 +219,28 @@ def detect_clones(+ lim = limits or DuplicationLimits()+ diag = DuplicationDiagnostics()++- per_file_tokens, per_file_nloc, all_windows = _collect_windows(+- parsed_files, window_tokens, lim, diag++ cache = None++ if cache_dir is not None:++ from .token_cache import DuplicationTokenCache++++ cache = DuplicationTokenCache(cache_dir, window_tokens)++ cache.load()++++ per_file_kinds, per_file_nloc, all_windows = _collect_windows(++ parsed_files, window_tokens, lim, diag, cache+ )++ if cache is not None:++ cache.save()++ log.debug(++ "duplication_token_cache",++ hits=cache.hits,++ misses=cache.misses,++ )+ if not all_windows:+ return DuplicationReport(diagnostics=diag.as_log_fields())++ bucket = index_by_hash(all_windows)+- raw_pairs = _pairs_from_buckets(bucket, per_file_tokens, window_tokens, lim, diag)++ raw_pairs = _pairs_from_buckets(bucket, per_file_kinds, window_tokens, lim, diag)++ final = _finalize_pairs(_merge_adjacent_pairs(raw_pairs), min_lines, meta_map)+ pairs_by_file, duplication_pct = _aggregate(final, per_file_nloc)+@@ -246,15 +263,23 @@ def _collect_windows(+ window_tokens: int,+ limits: DuplicationLimits,+ diag: DuplicationDiagnostics,+-) -> tuple[dict[str, list[Token]], dict[str, int], list[WindowHash]]:++ cache: Any | None = None,++) -> tuple[dict[str, list[str]], dict[str, int], list[WindowHash]]:+ """Tokenize each file once and emit its rolling-hash windows.++ Files are dropped (and counted in *diag*) when they are unreadable,+ minified/generated, shorter than one window, or exceed the per-file+ token cap. Collection stops cleanly once the repo-wide window budget+ is reached so peak memory stays bounded.++++ When a :class:`~.token_cache.DuplicationTokenCache` is supplied,++ unchanged files (by content hash) skip the tokenize + rolling-hash++ work and replay their cached kind sequence and window tuples; every++ gate above still re-evaluates live against the cached lengths.+ """+- per_file_tokens: dict[str, list[Token]] = {}++ import hashlib++++ per_file_kinds: dict[str, list[str]] = {}+ per_file_nloc: dict[str, int] = {}+ all_windows: list[WindowHash] = []++@@ -272,25 +297,57 @@ def _collect_windows(+ diag.skipped_minified += 1+ continue++- toks = tokenize_file(language, source)+- if len(toks) < window_tokens:++ cached = None++ content_hash = ""++ if cache is not None:++ content_hash = hashlib.sha256(source).hexdigest()++ cached = cache.get(content_hash)++++ if cached is not None:++ kinds, nloc, window_tuples = cached++ windows = [++ WindowHash(++ file_path=path,++ hash_value=h,++ start_index=si,++ start_line=sl,++ end_line=el,++ )++ for h, si, sl, el in window_tuples++ ]++ else:++ toks = tokenize_file(language, source)++ if len(toks) > limits.max_tokens_per_file:++ diag.skipped_token_cap += 1++ continue++ kinds = [t.kind for t in toks]++ nloc = _nloc(source)++ windows = rolling_hashes(path, toks, window_tokens)++ if cache is not None:++ cache.put(++ content_hash,++ kinds,++ nloc,++ [(w.hash_value, w.start_index, w.start_line, w.end_line) for w in windows],++ )++++ if len(kinds) < window_tokens:+ continue+- if len(toks) > limits.max_tokens_per_file:++ if len(kinds) > limits.max_tokens_per_file:+ diag.skipped_token_cap += 1+ continue++- windows = rolling_hashes(path, toks, window_tokens)+ if len(all_windows) + len(windows) > limits.max_total_windows:+ diag.window_budget_hit = True+ break++- per_file_tokens[path] = toks+- per_file_nloc[path] = _nloc(source)++ per_file_kinds[path] = kinds++ per_file_nloc[path] = nloc+ all_windows.extend(windows)+ diag.files_tokenized += 1++ diag.total_windows = len(all_windows)+- return per_file_tokens, per_file_nloc, all_windows++ return per_file_kinds, per_file_nloc, all_windows+++ # ---------------------------------------------------------------------------+@@ -300,7 +357,7 @@ def _collect_windows(++ def _pairs_from_buckets(+ bucket: dict[int, list[WindowHash]],+- per_file_tokens: dict[str, list[Token]],++ per_file_kinds: dict[str, list[str]],+ window_tokens: int,+ limits: DuplicationLimits,+ diag: DuplicationDiagnostics,+@@ -329,14 +386,14 @@ def _pairs_from_buckets(+ if deadline is not None and (i & 0x3FF) == 0 and time.monotonic() > deadline:+ diag.timed_out = True+ break+- _verify_bucket(windows, per_file_tokens, window_tokens, seen, raw_pairs)++ _verify_bucket(windows, per_file_kinds, window_tokens, seen, raw_pairs)++ return raw_pairs+++ def _verify_bucket(+ windows: list[WindowHash],+- per_file_tokens: dict[str, list[Token]],++ per_file_kinds: dict[str, list[str]],+ window_tokens: int,+ seen: set[tuple[str, int, str, int]],+ out: list[ClonePair],+@@ -357,8 +414,8 @@ def _verify_bucket(+ continue+ seen.add(key)+ if not _tokens_equal(+- per_file_tokens[a.file_path],+- per_file_tokens[b.file_path],++ per_file_kinds[a.file_path],++ per_file_kinds[b.file_path],+ a.start_index,+ b.start_index,+ window_tokens,+diff --git a/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py+new file mode 100644+index 00000000..ec2a9226+--- /dev/null++++ b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py+@@ -0,0 +1,115 @@++"""Content-hash keyed cache for duplication token streams + windows.++++Tokenizing every file (a full tree-sitter re-parse plus a pure-Python++leaf walk) and re-rolling 1M+ window hashes dominates the duplication++pass — and an incremental ``repowise update`` re-pays it for the whole++repo when a single file changed. Both outputs are pure functions of the++file *bytes* (given fixed window size and pinned hash constants), so they++cache safely by content hash.++++Cached per file: the normalized token-kind sequence (all the verifier++ever compares), the non-blank line count, and the rolling-hash windows++as plain tuples (``WindowHash`` is rebuilt with the file's *current*++path, which makes hits rename-proof). The minified/token-cap/window-++budget gates in the detector stay live — they re-evaluate against the++cached lengths, so config changes apply to cached entries too.++++Best-effort by design: any load/save error degrades to a full++re-tokenize. The cache file is rewritten with only the current file set++each run, so deleted files age out naturally.++"""++++from __future__ import annotations++++import contextlib++import os++import pickle++import sys++import tempfile++from pathlib import Path++++import structlog++++log = structlog.get_logger(__name__)++++_CACHE_VERSION = 1++_CACHE_FILENAME = "duplication_cache.pkl"++++++class DuplicationTokenCache:++ """Pickle-backed ``content_hash -> (kinds, nloc, windows)`` store."""++++ def __init__(self, cache_dir: Path, window_tokens: int) -> None:++ self._path = Path(cache_dir) / _CACHE_FILENAME++ self._window_tokens = window_tokens++ self._entries: dict[str, tuple[list[str], int, list[tuple[int, int, int, int]]]] = {}++ self._fresh: dict[str, tuple[list[str], int, list[tuple[int, int, int, int]]]] = {}++ self.hits = 0++ self.misses = 0++++ # -- lifecycle ---------------------------------------------------------++++ def load(self) -> None:++ try:++ with self._path.open("rb") as fh:++ payload = pickle.load(fh)++ if (++ payload.get("version") != _CACHE_VERSION++ or payload.get("window_tokens") != self._window_tokens++ ):++ return++ self._entries = payload.get("files", {})++ except FileNotFoundError:++ return++ except Exception as exc: # corrupt / unreadable cache -> full tokenize++ log.debug("duplication_cache_load_failed", error=str(exc))++++ def save(self) -> None:++ """Atomically persist the entries used or created this run."""++ try:++ self._path.parent.mkdir(parents=True, exist_ok=True)++ payload = {++ "version": _CACHE_VERSION,++ "window_tokens": self._window_tokens,++ "files": self._fresh,++ }++ fd, tmp_name = tempfile.mkstemp(++ dir=str(self._path.parent), prefix=_CACHE_FILENAME, suffix=".tmp"++ )++ try:++ with os.fdopen(fd, "wb") as fh:++ pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)++ os.replace(tmp_name, self._path)++ except BaseException:++ with contextlib.suppress(OSError):++ os.unlink(tmp_name)++ raise++ except Exception as exc:++ log.debug("duplication_cache_save_failed", error=str(exc))++++ # -- access ------------------------------------------------------------++++ def get(++ self, content_hash: str++ ) -> tuple[list[str], int, list[tuple[int, int, int, int]]] | None:++ entry = self._entries.get(content_hash)++ if entry is None:++ self.misses += 1++ return None++ self.hits += 1++ # Entries touched this run survive into the rewritten cache file.++ self._fresh[content_hash] = entry++ return entry++++ def put(++ self,++ content_hash: str,++ kinds: list[str],++ nloc: int,++ windows: list[tuple[int, int, int, int]],++ ) -> None:++ # Interned kinds keep the pickle compact (each distinct kind is++ # memoized once by identity) and make later equality checks cheap.++ entry = ([sys.intern(k) for k in kinds], nloc, windows)++ self._entries[content_hash] = entry++ self._fresh[content_hash] = entry+diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py+index d0e27ef5..24ab7d59 100644+--- a/packages/core/src/repowise/core/analysis/health/engine.py++++ b/packages/core/src/repowise/core/analysis/health/engine.py+@@ -256,6 +256,7 @@ class HealthAnalyzer:+ parsed_files: list[Any] | None = None,+ coverage_map: dict[str, dict[str, Any]] | None = None,+ module_map: dict[str, str] | None = None,++ duplication_cache_dir: Any | None = None,+ ) -> None:+ self.graph = graph+ self.git_meta_map = git_meta_map or {}+@@ -271,6 +272,10 @@ class HealthAnalyzer:+ # module rollups still group sensibly on small repos that didn't+ # produce community labels.+ self.module_map = module_map or {}++ # Directory for the duplication token/window cache (typically the++ # repo's ``.repowise``). None disables caching — the duplication++ # pass then re-tokenizes everything, exactly as before.++ self.duplication_cache_dir = duplication_cache_dir++ def analyze(+ self,+@@ -309,7 +314,11 @@ class HealthAnalyzer:+ dup_report = DuplicationReport()+ else:+ try:+- dup_report = detect_clones(self.parsed_files, self.git_meta_map)++ dup_report = detect_clones(++ self.parsed_files,++ self.git_meta_map,++ cache_dir=self.duplication_cache_dir,++ )+ _log_duplication_diagnostics(dup_report)+ except Exception as exc:+ log.debug("health_duplication_failed", error=str(exc))+@@ -418,7 +427,10 @@ class HealthAnalyzer:+ else:+ try:+ dup_report = await asyncio.to_thread(+- detect_clones, self.parsed_files, self.git_meta_map++ detect_clones,++ self.parsed_files,++ self.git_meta_map,++ cache_dir=self.duplication_cache_dir,+ )+ _log_duplication_diagnostics(dup_report)+ except Exception as exc:+diff --git a/packages/core/src/repowise/core/generation/__init__.py b/packages/core/src/repowise/core/generation/__init__.py+index db00b92d..0f891ca5 100644+--- a/packages/core/src/repowise/core/generation/__init__.py++++ b/packages/core/src/repowise/core/generation/__init__.py+@@ -5,105 +5,79 @@ Jinja2-templated prompts and BaseProvider.generate().++ Import direction (strictly one-way):+ ingestion.models ← generation.models ← context_assembler ← page_generator++++Exports resolve lazily (PEP 562): importing a light leaf module such as++``generation.report`` from the index-only update path no longer pays for++``context_assembler``/``page_generator``/``editor_files`` — they load on first++attribute access instead.+ """++-from .context_assembler import (+- ApiContractContext,+- ArchitectureDiagramContext,+- ContextAssembler,+- FilePageContext,+- InfraPageContext,+- ModulePageContext,+- RepoOverviewContext,+- SccPageContext,+- SymbolSpotlightContext,+-)+-from .editor_files import (+- ClaudeMdGenerator,+- DecisionSummary,+- EditorFileData,+- EditorFileDataFetcher,+- HotspotFile,+- KeyModule,+- TechStackItem,+-)+-from .job_system import Checkpoint, JobStatus, JobSystem+-from .models import (+- GENERATION_LEVELS,+- ConfidenceDecayResult,+- DeadCodeConfig,+- FreshnessStatus,+- GeneratedPage,+- GenerationConfig,+- GitConfig,+- PageType,+- compute_confidence_decay_with_git,+- compute_freshness,+- compute_page_id,+- compute_source_hash,+- decay_confidence,+-)+-from .api_contract_detector import detect_code_api_contracts+-from .interlinking import (+- LinkIndex,+- WikiLink,+- attach_wiki_links_and_backlinks,+- resolve_wiki_links,+-)+-from .page_generator import SYSTEM_PROMPTS, PageGenerator+-from .selection import (+- BucketAllocation,+- ModuleGroup,+- Selection,+- SelectionInputs,+- select_pages,+- summarize_selection,+-)++from importlib import import_module++from typing import Any++++# Public name → defining submodule. Names import lazily on first access so++# light consumers (e.g. the index-only update path importing ``.report``)++# don't pull the heavy assembler/generator stack via this ``__init__``.++_EXPORTS = {++ "ApiContractContext": ".context_assembler",++ "ArchitectureDiagramContext": ".context_assembler",++ "ContextAssembler": ".context_assembler",++ "FilePageContext": ".context_assembler",++ "InfraPageContext": ".context_assembler",++ "ModulePageContext": ".context_assembler",++ "RepoOverviewContext": ".context_assembler",++ "SccPageContext": ".context_assembler",++ "SymbolSpotlightContext": ".context_assembler",++ "ClaudeMdGenerator": ".editor_files",++ "DecisionSummary": ".editor_files",++ "EditorFileData": ".editor_files",++ "EditorFileDataFetcher": ".editor_files",++ "HotspotFile": ".editor_files",++ "KeyModule": ".editor_files",++ "TechStackItem": ".editor_files",++ "Checkpoint": ".job_system",++ "JobStatus": ".job_system",++ "JobSystem": ".job_system",++ "GENERATION_LEVELS": ".models",++ "ConfidenceDecayResult": ".models",++ "DeadCodeConfig": ".models",++ "FreshnessStatus": ".models",++ "GeneratedPage": ".models",++ "GenerationConfig": ".models",++ "GitConfig": ".models",++ "PageType": ".models",++ "compute_confidence_decay_with_git": ".models",++ "compute_freshness": ".models",++ "compute_page_id": ".models",++ "compute_source_hash": ".models",++ "decay_confidence": ".models",++ "detect_code_api_contracts": ".api_contract_detector",++ "LinkIndex": ".interlinking",++ "WikiLink": ".interlinking",++ "attach_wiki_links_and_backlinks": ".interlinking",++ "resolve_wiki_links": ".interlinking",++ "SYSTEM_PROMPTS": ".page_generator",++ "PageGenerator": ".page_generator",++ "BucketAllocation": ".selection",++ "ModuleGroup": ".selection",++ "Selection": ".selection",++ "SelectionInputs": ".selection",++ "select_pages": ".selection",++ "summarize_selection": ".selection",++}++++__all__ = sorted(_EXPORTS)++++++def __getattr__(name: str) -> Any:++ try:++ module = _EXPORTS[name]++ except KeyError:++ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None++ value = getattr(import_module(module, __name__), name)++ globals()[name] = value # cache: subsequent access skips __getattr__++ return value++++-__all__ = [+- "BucketAllocation",+- "GENERATION_LEVELS",+- "LinkIndex",+- "ModuleGroup",+- "SYSTEM_PROMPTS",+- "Selection",+- "SelectionInputs",+- "WikiLink",+- "attach_wiki_links_and_backlinks",+- "resolve_wiki_links",+- "select_pages",+- "summarize_selection",+- "ApiContractContext",+- "ArchitectureDiagramContext",+- "Checkpoint",+- "ClaudeMdGenerator",+- "ConfidenceDecayResult",+- "ContextAssembler",+- "DeadCodeConfig",+- "DecisionSummary",+- "EditorFileData",+- "EditorFileDataFetcher",+- "FilePageContext",+- "FreshnessStatus",+- "GeneratedPage",+- "GenerationConfig",+- "GitConfig",+- "HotspotFile",+- "InfraPageContext",+- "JobStatus",+- "JobSystem",+- "KeyModule",+- "ModulePageContext",+- "PageGenerator",+- "PageType",+- "RepoOverviewContext",+- "SccPageContext",+- "SymbolSpotlightContext",+- "TechStackItem",+- "compute_confidence_decay_with_git",+- "compute_freshness",+- "compute_page_id",+- "compute_source_hash",+- "decay_confidence",+- "detect_code_api_contracts",+-]++def __dir__() -> list[str]:++ return sorted(set(globals()) | set(_EXPORTS))+diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py+index 1911fb07..75192e73 100644+--- a/packages/core/src/repowise/core/generation/context/assembler.py++++ b/packages/core/src/repowise/core/generation/context/assembler.py+@@ -90,8 +90,14 @@ class ContextAssembler:+ page_summaries: dict[str, str] | None = None,+ decision_records: list[dict] | None = None,+ kg_context: Any | None = None,++ symbol_index: dict[str, list[tuple[Any, dict]]] | None = None,+ ) -> FilePageContext:+- """Assemble context for the file_page template."""++ """Assemble context for the file_page template.++++ *symbol_index* (see :func:`build_symbol_index`) makes the call-graph /++ heritage extraction a dict lookup instead of a full graph-node scan —++ pass it when assembling context for many files against one graph.++ """+ path = parsed.file_info.path+ budget = self._config.token_budget+ used = 0+@@ -158,8 +164,8 @@ class ContextAssembler:+ depth = self._select_generation_depth(path, git_meta, pagerank.get(path, 0.0))++ # Graph intelligence: call graph, heritage, community metadata+- call_graph_entries = extract_call_graph(path, graph)+- heritage_entries = extract_heritage(path, graph)++ call_graph_entries = extract_call_graph(path, graph, symbol_index)++ heritage_entries = extract_heritage(path, graph, symbol_index)+ community_label, community_cohesion = extract_community_meta(path, graph)++ return FilePageContext(+diff --git a/packages/core/src/repowise/core/generation/context/graph_intelligence.py b/packages/core/src/repowise/core/generation/context/graph_intelligence.py+index a6fa3048..a9e69af5 100644+--- a/packages/core/src/repowise/core/generation/context/graph_intelligence.py++++ b/packages/core/src/repowise/core/generation/context/graph_intelligence.py+@@ -9,15 +9,50 @@ from __future__ import annotations+ from typing import Any+++-def extract_call_graph(file_path: str, graph: Any) -> list[dict]:+- """Extract symbol-level call edges for symbols defined in this file."""+- entries: list[dict] = []++def build_symbol_index(graph: Any) -> dict[str, list[tuple[Any, dict]]]:++ """Bucket symbol nodes by ``file_path`` in one pass over the graph.++++ ``extract_call_graph`` / ``extract_heritage`` historically scanned every++ graph node per file — O(files x nodes) across a generation run. Callers++ that assemble context for many files build this index once and pass it++ in; per-file extraction becomes a dict lookup. Buckets preserve the++ graph's node iteration order, so results are byte-identical to the scan.++ """++ index: dict[str, list[tuple[Any, dict]]] = {}+ try:+ for node, data in graph.nodes(data=True):+ if data.get("node_type") != "symbol":+ continue+- if data.get("file_path") != file_path:+- continue++ fp = data.get("file_path")++ if fp:++ index.setdefault(fp, []).append((node, data))++ except Exception:++ return {}++ return index++++++def _file_symbol_nodes(++ file_path: str, graph: Any, symbol_index: dict[str, list[tuple[Any, dict]]] | None++) -> Any:++ """This file's symbol nodes — from the index when supplied, else a scan."""++ if symbol_index is not None:++ return symbol_index.get(file_path, [])++ return (++ (node, data)++ for node, data in graph.nodes(data=True)++ if data.get("node_type") == "symbol" and data.get("file_path") == file_path++ )++++++def extract_call_graph(++ file_path: str,++ graph: Any,++ symbol_index: dict[str, list[tuple[Any, dict]]] | None = None,++) -> list[dict]:++ """Extract symbol-level call edges for symbols defined in this file."""++ entries: list[dict] = []++ try:++ for node, data in _file_symbol_nodes(file_path, graph, symbol_index):+ # Outgoing calls from this symbol+ for _, target, edata in graph.out_edges(node, data=True):+ if edata.get("edge_type") == "calls":+@@ -56,15 +91,15 @@ def extract_call_graph(file_path: str, graph: Any) -> list[dict]:+ return unique[:15]+++-def extract_heritage(file_path: str, graph: Any) -> list[dict]:++def extract_heritage(++ file_path: str,++ graph: Any,++ symbol_index: dict[str, list[tuple[Any, dict]]] | None = None,++) -> list[dict]:+ """Extract extends/implements edges for symbols in this file."""+ entries: list[dict] = []+ try:+- for node, data in graph.nodes(data=True):+- if data.get("node_type") != "symbol":+- continue+- if data.get("file_path") != file_path:+- continue++ for node, data in _file_symbol_nodes(file_path, graph, symbol_index):+ for _, target, edata in graph.out_edges(node, data=True):+ etype = edata.get("edge_type", "")+ if etype in ("extends", "implements"):+diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.py+index 67458fb4..8a4f46f6 100644+--- a/packages/core/src/repowise/core/generation/page_generator/core.py++++ b/packages/core/src/repowise/core/generation/page_generator/core.py+@@ -208,15 +208,26 @@ class PageGenerator(PerTypeGenerationMixin):+ self,+ parsed: ParsedFile,+ ctx: FilePageContext,++ rag_prefetched: bool = False,+ ) -> GeneratedPage:+- """Generate a file_page from a pre-assembled context (avoids double-assembly)."""++ """Generate a file_page from a pre-assembled context (avoids double-assembly).++++ *rag_prefetched* is set by the level-2 builder when RAG context was++ already resolved for the whole level in one batched search (see++ ``levels._prefetch_rag_context``) — the per-page search below would++ re-fetch identical results inside the LLM semaphore, so it is skipped.++ """+ # RAG context: query vector store for related pages (B1).+ # Gated by two short-circuits so we don't burn an embedder+ # round-trip on every page when the result wouldn't help:+ # 1. ``enable_rag_context`` config flag (off → fully skip).+ # 2. ``rag_min_store_size`` — early pages run against an empty+ # or near-empty store and the search returns nothing useful.+- if self._vector_store is not None and getattr(self._config, "enable_rag_context", True):++ if (++ not rag_prefetched++ and self._vector_store is not None++ and getattr(self._config, "enable_rag_context", True)++ ):+ min_store_size = max(0, int(getattr(self._config, "rag_min_store_size", 10) or 0))+ store_ok = True+ if min_store_size > 0:+diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.py+index ff088069..80ea7ce8 100644+--- a/packages/core/src/repowise/core/generation/page_generator/levels.py++++ b/packages/core/src/repowise/core/generation/page_generator/levels.py+@@ -130,6 +130,59 @@ async def _prefetch_dependency_summaries(run: _GenerationRun) -> None:+ log.debug("rag.batch_dep_prefetch_failed", error=str(exc))++++async def _prefetch_rag_context(++ run: _GenerationRun, items: list[tuple[Any, FilePageContext]]++) -> bool:++ """Resolve RAG context for all tier-1 file pages in one batched search.++++ Replicates the per-page gating in ``_generate_file_page_from_ctx`` (flag,++ store size, query-term derivation, self-exclusion) but runs BEFORE the++ level starts, outside the LLM semaphore, with all queries embedded in a++ single embedder call via :meth:`VectorStore.search_many`. The store is++ static for the whole level (pages embed in one batch at level end), so++ prefetched results are identical to what each page would have fetched.++++ Returns True when the per-page search can be skipped (results resolved,++ or the per-page gate would have skipped every search anyway); False on++ batch failure so pages fall back to the per-page path.++ """++ if run.vector_store is None or not getattr(run.config, "enable_rag_context", True):++ return False++ min_store_size = max(0, int(getattr(run.config, "rag_min_store_size", 10) or 0))++ if min_store_size > 0:++ try:++ current_ids = await run.vector_store.list_page_ids()++ if len(current_ids) < min_store_size:++ # Store too small for useful RAG — the per-page gate would++ # skip every search this level, so there is nothing to fetch.++ return True++ except Exception:++ pass # same as the per-page gate: fall through to the search++ queries: list[str] = []++ targets: list[tuple[Any, FilePageContext]] = []++ for p, ctx in items:++ query_terms = p.exports or [++ s["name"] for s in ctx.symbols[:3] if s.get("visibility") == "public"++ ]++ if not query_terms:++ continue++ queries.append(", ".join(query_terms[:5]))++ targets.append((p, ctx))++ if not queries:++ return True++ try:++ all_results = await run.vector_store.search_many(queries, limit=3)++ except Exception as exc:++ log.debug("rag.batch_search_failed", error=str(exc))++ return False++ for (p, ctx), results in zip(targets, all_results, strict=False):++ self_id = f"file_page:{p.file_info.path}"++ ctx.rag_context = [++ f"[{r.page_id}]\n{r.snippet}" for r in results if r.page_id != self_id++ ]++ return True+++++ async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:+ """Level 2 (file_page): topo-ordered context assembly + tier routing.++@@ -141,7 +194,13 @@ async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:+ _topo_order_code_files(run)+ await _prefetch_dependency_summaries(run)++- coros: list[tuple[str, Any]] = []++ # One pass over the graph's symbol nodes feeds every file's call-graph /++ # heritage extraction (instead of a full node scan per file).++ from ..context.graph_intelligence import build_symbol_index++++ symbol_index = build_symbol_index(run.graph)++++ items: list[tuple[Any, FilePageContext]] = []+ for p in run.code_files:+ kg_file_ctx = run.kg_ctx.get_file_context(p.file_info.path) if run.kg_ctx.available else None+ ctx: FilePageContext = gen._assembler.assemble_file_page(+@@ -156,13 +215,32 @@ async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:+ dead_code_findings=run.dead_code_by_file.get(p.file_info.path),+ decision_records=run.decisions_by_file.get(p.file_info.path),+ kg_context=kg_file_ctx,++ symbol_index=symbol_index,+ )+ run.file_page_contexts[p.file_info.path] = ctx++ items.append((p, ctx))++++ def _emits_tier1(p: Any) -> bool:++ path = p.file_info.path++ return (++ path in run.sel_file_paths++ and path in run.tier1_paths++ and compute_page_id("file_page", path) not in run.completed_ids++ )++++ rag_prefetched = await _prefetch_rag_context(++ run, [(p, ctx) for p, ctx in items if _emits_tier1(p)]++ )++++ coros: list[tuple[str, Any]] = []++ for p, ctx in items:+ path = p.file_info.path+ pid = compute_page_id("file_page", path)+ if path in run.sel_file_paths and pid not in run.completed_ids:+ if path in run.tier1_paths:+- coros.append((pid, gen._generate_file_page_from_ctx(p, ctx)))++ coros.append(++ (pid, gen._generate_file_page_from_ctx(p, ctx, rag_prefetched=rag_prefetched))++ )+ else:+ coros.append((pid, gen._generate_file_page_tier2(p, ctx)))+ return coros+diff --git a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py+index 264a6f6f..344bfda4 100644+--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py++++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py+@@ -365,6 +365,16 @@ class _GenerationRun:+ error=str(exc),+ )+ return exc # return as value so gather works++ except BaseException:++ # Cancellation (Ctrl+C teardown): CancelledError is a++ # BaseException, so it skips the handler above. If the cancel++ # landed while this page was still queued on the semaphore,++ # ``coro`` was never started — close it so interpreter++ # shutdown doesn't spray one "coroutine ... was never++ # awaited" RuntimeWarning per pending page (issue #358).++ # close() is a no-op on a coroutine that already ran.++ coro.close()++ raise++ tasks = [guarded_named(pid, c) for pid, c in named_coros]+ results = await asyncio.gather(*tasks)+diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py+index 8d3577d9..392c553a 100644+--- a/packages/core/src/repowise/core/ingestion/call_resolver.py++++ b/packages/core/src/repowise/core/ingestion/call_resolver.py+@@ -64,6 +64,7 @@ class CallResolver:+ import_targets: dict[str, set[str]],+ *,+ repo_path: str | None = None,++ import_maps: Any | None = None,+ ) -> None:+ # Per-file symbol index: {file_path: {symbol_name: symbol_id}}+ self._file_symbols: dict[str, dict[str, str]] = {}+@@ -71,6 +72,11 @@ class CallResolver:+ # Per-file method index: {file_path: {(class_name, method_name): symbol_id}}+ self._file_methods: dict[str, dict[tuple[str, str], str]] = {}+++ # Global method index: {(class_name, method_name): [(file_path, symbol_id)]}++ # in file-insertion order — replaces the trait-dispatch scan over++ # every file's method dict with one short-list lookup.++ self._global_methods: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)+++ # Global symbol index: {name: [symbol_ids]} — for Tier 3+ self._global_symbols: dict[str, list[str]] = defaultdict(list)++@@ -80,14 +86,27 @@ class CallResolver:+ # Import graph: {file_path: set of imported file paths}+ self._import_targets = import_targets++- # Import name mapping: {file_path: {local_name: source_file}}+- self._import_names: dict[str, dict[str, str]] = defaultdict(dict)++ # Shared import-name maps (built once per GraphBuilder.build() and++ # injected; standalone construction builds them locally).++ if import_maps is None:++ from .import_index import build_import_name_maps+++ import_maps = build_import_name_maps(parsed_files)++ # Import name mapping: {file_path: {local_name: source_file}}++ self._import_names: dict[str, dict[str, str]] = import_maps.import_names+ # Full binding data: {file_path: {local_name: NamedBinding}}+- self._import_bindings: dict[str, dict[str, NamedBinding]] = defaultdict(dict)+-++ self._import_bindings: dict[str, dict[str, NamedBinding]] = import_maps.import_bindings+ # Module alias mapping: {file_path: {alias: source_file}}+- self._module_aliases: dict[str, dict[str, str]] = defaultdict(dict)++ self._module_aliases: dict[str, dict[str, str]] = import_maps.module_aliases++++ # Lazy per-file merged views of every imported file's symbol /++ # method tables — turns the Tier-2b "scan each imported file"++ # loops into single dict lookups. Built on first miss per file;++ # merge order is sorted(import paths) with first-wins so shadowed++ # names resolve deterministically (the old set-iteration order was++ # hash-randomized per process).++ self._merged_import_symbols: dict[str, dict[str, str]] = {}++ self._merged_import_methods: dict[str, dict[tuple[str, str], str]] = {}++ # Barrel re-export origins: {barrel_file: {name: origin_file}}+ self._barrel_origins: dict[str, dict[str, str]] = defaultdict(dict)+@@ -366,7 +385,10 @@ class CallResolver:+ return None++ def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:+- """Build all lookup indices from parsed file data."""++ """Build symbol lookup indices from parsed file data.++++ (Import-name maps are shared — see ``import_index.build_import_name_maps``.)++ """+ for path, parsed in parsed_files.items():+ file_syms: dict[str, str] = {}+ file_methods: dict[tuple[str, str], str] = {}+@@ -377,7 +399,9 @@ class CallResolver:++ # Method index: (class_name, method_name) → symbol_id+ if sym.parent_name:+- file_methods[(sym.parent_name, sym.name)] = sym.id++ key = (sym.parent_name, sym.name)++ file_methods[key] = sym.id++ self._global_methods[key].append((path, sym.id))++ # Global indices+ self._global_symbols[sym.name].append(sym.id)+@@ -387,25 +411,35 @@ class CallResolver:+ self._file_symbols[path] = file_syms+ self._file_methods[path] = file_methods++- # Build import-name mapping using per-import resolved_file+- for imp in parsed.imports:+- if imp.resolved_file is None:++ def _merged_symbols_for(self, file_path: str) -> dict[str, str]:++ """Merged ``{name → symbol_id}`` across every file *file_path* imports.++++ Sorted-path merge order with first-wins gives deterministic++ precedence for names exported by multiple imports.++ """++ merged = self._merged_import_symbols.get(file_path)++ if merged is None:++ merged = {}++ for imported_file in sorted(self._import_targets.get(file_path, ())):++ if imported_file.startswith("external:"):+ continue+- resolved = imp.resolved_file+- if imp.bindings:+- for binding in imp.bindings:+- if binding.local_name == "*":+- continue+- binding.source_file = resolved+- self._import_names[path][binding.local_name] = resolved+- self._import_bindings[path][binding.local_name] = binding+- if binding.is_module_alias:+- self._module_aliases[path][binding.local_name] = resolved+- else:+- # Fallback for imports without binding data+- for name in imp.imported_names:+- if name != "*":+- self._import_names[path][name] = resolved++ for name, sym_id in self._file_symbols.get(imported_file, {}).items():++ merged.setdefault(name, sym_id)++ self._merged_import_symbols[file_path] = merged++ return merged++++ def _merged_methods_for(self, file_path: str) -> dict[tuple[str, str], str]:++ """Merged ``{(class, method) → symbol_id}`` across imports (see above)."""++ merged = self._merged_import_methods.get(file_path)++ if merged is None:++ merged = {}++ for imported_file in sorted(self._import_targets.get(file_path, ())):++ if imported_file.startswith("external:"):++ continue++ for key, sym_id in self._file_methods.get(imported_file, {}).items():++ merged.setdefault(key, sym_id)++ self._merged_import_methods[file_path] = merged++ return merged++ def resolve_file(self, file_path: str, calls: list[CallSite]) -> list[ResolvedCall]:+ """Resolve all calls in a single file to symbol-level edges."""+@@ -504,13 +538,10 @@ class CallResolver:+ if target_name in source_syms:+ return ResolvedCall(caller_id, source_syms[target_name], 0.90, call.line)++- # 2b: Check all imported files for the symbol+- for imported_file in self._import_targets.get(file_path, set()):+- if imported_file.startswith("external:"):+- continue+- imported_syms = self._file_symbols.get(imported_file, {})+- if target_name in imported_syms:+- return ResolvedCall(caller_id, imported_syms[target_name], 0.85, call.line)++ # 2b: Check all imported files for the symbol (pre-merged lookup)++ merged_syms = self._merged_symbols_for(file_path)++ if target_name in merged_syms:++ return ResolvedCall(caller_id, merged_syms[target_name], 0.85, call.line)++ # Tier 3: global unique match — only within the same language+ candidates = self._global_symbols.get(target_name, [])+@@ -591,22 +622,20 @@ class CallResolver:+ if key in file_methods:+ return ResolvedCall(caller_id, file_methods[key], 0.93, call.line)++- # Check imported files for (class, method) pairs+- for imported_file in self._import_targets.get(file_path, set()):+- if imported_file.startswith("external:"):+- continue+- imp_methods = self._file_methods.get(imported_file, {})+- if key in imp_methods:+- return ResolvedCall(caller_id, imp_methods[key], 0.88, call.line)++ # Check imported files for (class, method) pairs (pre-merged lookup)++ merged_methods = self._merged_methods_for(file_path)++ if key in merged_methods:++ return ResolvedCall(caller_id, merged_methods[key], 0.88, call.line)++ # Strategy 2b: trait method dispatch — receiver is a type that+ # implements a trait; the method may be defined on the trait's+- # impl block in another file.+- for _path, methods in self._file_methods.items():++ # impl block in another file. The global index preserves the old++ # file-insertion match order; entries from the caller's own file++ # are skipped exactly as before.++ for _path, sym_id in self._global_methods.get(key, ()):+ if _path == file_path:+ continue+- if key in methods:+- return ResolvedCall(caller_id, methods[key], 0.75, call.line)++ return ResolvedCall(caller_id, sym_id, 0.75, call.line)++ # Strategy 3: receiver is "self" or "this" — look in same class+ if receiver_name in ("self", "this"):+diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py+index aa464034..cff6d725 100644+--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py++++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py+@@ -60,22 +60,18 @@ HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {+++ def extract_heritage(+- tree: object,+- query: object,++ matches: list[dict],+ config: object,+ file_info: object,+ src: str,+- *,+- run_query: Callable,+ ) -> list[HeritageRelation]:+ """Extract inheritance/implementation relationships from class definitions.++- Walks the same @symbol.def captures used by _extract_symbols, extracting+- superclass/interface/trait information from the definition AST nodes.++ Walks the same @symbol.def captures used by _extract_symbols (the parser++ executes the compiled query once per file and shares the capture dicts++ across all extraction passes), extracting superclass/interface/trait++ information from the definition AST nodes.+ """+- if query is None:+- return []+-+ lang = file_info.language # type: ignore[attr-defined]+ heritage_types = heritage_node_types_for(lang)+ if not heritage_types:+@@ -88,7 +84,7 @@ def extract_heritage(+ relations: list[HeritageRelation] = []+ seen: set[tuple[int, str]] = set()++- for capture_dict in run_query(query, tree.root_node): # type: ignore[attr-defined]++ for capture_dict in matches:+ def_nodes = capture_dict.get("symbol.def", [])+ name_nodes = capture_dict.get("symbol.name", [])++diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py+index 01719a3f..5fb248ab 100644+--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py++++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py+@@ -36,6 +36,7 @@ def load_commit_index(+ *,+ commit_sink: list[dict] | None = None,+ since_ts: int | None = None,++ provenance_classifier: object | None = None,+ ) -> dict[str, list[_CommitRec]]:+ """Bucket every commit in the recent history by the files it touched.++@@ -66,6 +67,13 @@ def load_commit_index(+ without re-walking the full window. Default (``None``) processes the whole+ depth.+++ *provenance_classifier* (an++ :class:`~.git_indexer.agent_provenance.AgentProvenanceClassifier`) labels++ each commit's agent provenance once per commit — pure in-memory regex on++ the already-parsed record, no extra git pass. ``None`` uses the built-in++ pattern registry; callers with repo-local pattern extensions pass the++ config-aware instance instead.+++ Failures (git unavailable, corrupt log output, etc.) return an+ empty dict so the caller can fall back to per-file indexing.+ """+@@ -78,6 +86,10 @@ def load_commit_index(+ _extract_rename_paths,+ _parse_commit_record,+ )++ from .git_indexer.agent_provenance import AgentProvenanceClassifier++++ if provenance_classifier is None:++ provenance_classifier = AgentProvenanceClassifier()++ try:+ raw = repo.git.log( # type: ignore[attr-defined]+@@ -114,6 +126,16 @@ def load_commit_index(+ continue+ commits_parsed += 1+++ # Agent provenance — classified ONCE per commit here (not per touched++ # file): the per-file records below share the result by reference.++ prov = provenance_classifier.classify( # type: ignore[attr-defined]++ header["author_name"],++ header["author_email"],++ header["committer_name"],++ header["committer_email"],++ f"{header['subject']}\n{header['body']}",++ )+++ # Full change footprint of this commit (every file, not just the+ # indexable subset) — only accumulated when a sink is requested so the+ # default path pays nothing.+@@ -162,6 +184,8 @@ def load_commit_index(+ body=header["body"],+ added=added,+ deleted=deleted,++ agent=prov.agent,++ agent_tier=prov.autonomy_tier,+ )+ )++@@ -174,6 +198,10 @@ def load_commit_index(+ "ts": header["ts"],+ "subject": header["subject"],+ "changes": commit_changes,++ "agent_name": prov.agent,++ "agent_autonomy_tier": prov.autonomy_tier,++ "agent_channel": prov.channel,++ "agent_confidence": prov.confidence,+ }+ )++diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/README.md b/packages/core/src/repowise/core/ingestion/git_indexer/README.md+index c9fefa60..775a9604 100644+--- a/packages/core/src/repowise/core/ingestion/git_indexer/README.md++++ b/packages/core/src/repowise/core/ingestion/git_indexer/README.md+@@ -17,7 +17,9 @@ layers consume:+ - co-change partners and Hassan **change entropy** (History Complexity Metric);+ - per-function blame (modification counts, line age) for function-level health;+ - **prior-defect history** — bug-fix commits touching each file in the trailing+- window, the most cost-effective defect predictor.++ window, the most cost-effective defect predictor;++- **agent provenance** — which coding agent (if any) authored each commit, at++ what autonomy tier, plus per-file `agent_authored_pct` rollups.++ ## Window anchoring (`REPOWISE_GIT_WINDOW_ANCHOR`)++@@ -94,6 +96,41 @@ live `repowise risk` path) is reconstructed **in memory** here: walking commits+ oldest→newest, each author's prior-commit count is the running tally. Empty in+ rename-tracking mode (which uses the per-file walk, not the batched index).+++## Agent provenance++++`agent_provenance.py` labels every walked commit++`{agent, autonomy_tier, channel, confidence}` from the attribution channels++present in **local git history** — identity fields (bot accounts / service++e-mails), exact message footers ("Generated with Claude Code", Codex,++opencode, aider), and `Co-authored-by:` trailers anchored to service++identities. Tiers: **1** near-autonomous (an agent service account authored++the commit) · **2** human-driven agent (footer, or a service identity as++*committer* over a human author) · **3** assisted (co-author trailer only).++++Design rules:++++- **Precision-first.** Every pattern is anchored to a service identity; a bare++ name never matches (a human contributor named "Devin" must not become the++ Devin agent). A false "agent-authored" label on a human commit is worse++ than a miss.++- **Local channels only.** PR-level evidence (bot PR authors, agent branch++ prefixes, PR-body footers) needs the forge API and is out of scope — squash++ merges that strip trailers are a known *recall* loss, stated rather than++ patched with network calls at index time.++- **Zero extra cost.** Classification rides the existing commit-index walk —++ pure in-memory regex on already-parsed records, ~20 µs/commit (≈10 ms at the++ default commit depth), no additional `git` pass.++- **Config-driven.** Repos can extend the registry from++ `.repowise/config.yaml` under an `agent_provenance:` block++ (`service_emails`, `footer_patterns`, `coauthor_patterns`) — additive on top++ of the built-ins, malformed entries skipped with a warning.++++Persisted as four nullable columns on `git_commits`++(`agent_name`/`agent_autonomy_tier`/`agent_channel`/`agent_confidence`) and a++per-file rollup on `git_metadata` (`agent_commit_count`, `agent_authored_pct`,++`agent_tier_counts_json`), surfaced in the `/git-metadata` file view and the++MCP `get_context` ownership block.+++ ## Internal layout++ | Module | Contents |+@@ -102,6 +139,7 @@ rename-tracking mode (which uses the per-file walk, not the batched index).+ | `_constants.py` | commit-depth defaults, decay half-lives, the bug-fix keyword classifier (`is_fix_commit`, mirrors the benchmark) + `PRIOR_DEFECT_WINDOW_DAYS`, skip heuristics, GitPython noise patch |+ | `records.py` | `_CommitRec`, `GitIndexSummary` (carries `commit_rows`), the `git log` record format + rename/skip path helpers |+ | `commit_rows.py` | `build_commit_rows` — per-commit Kamei features + change-risk from the walk's sunk commits (pure, in-memory author experience) |++| `agent_provenance.py` | `AgentProvenanceClassifier` — deterministic per-commit agent attribution (local channels, config-extensible) |+ | `file_history.py` | `index_file` — per-file parse + base metrics (blame gated by tier) |+ | `enrich.py` | blame ownership, commit significance, rename detection, percentiles |+ | `function_blame.py` | per-line blame index → per-function modification counts + line age (FULL tier; feeds `function_hotspot` / `code_age_volatility`) |+diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+index 3a361f9a..2546ec4e 100644+--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py++++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+@@ -20,6 +20,11 @@ This package was split out of a single 1k-line module; the public import path+ from __future__ import annotations++ from ._constants import HOTSPOT_HALFLIFE_DAYS, is_fix_commit++from .agent_provenance import (++ AgentProvenance,++ AgentProvenanceClassifier,++ classifier_from_repo_config,++)+ from .backfill import BACKFILL_PHASE, backfill_full_tier+ from .co_change import compute_co_changes, compute_co_changes_and_entropy+ from .enrich import (+@@ -52,6 +57,8 @@ __all__ = [+ "_FIELD_SEP",+ "_LOG_FORMAT",+ "_RECORD_SEP",++ "AgentProvenance",++ "AgentProvenanceClassifier",+ "GitIndexSummary",+ "GitIndexTier",+ "GitIndexer",+@@ -60,6 +67,7 @@ __all__ = [+ "_parse_commit_record",+ "_should_skip_index",+ "backfill_full_tier",++ "classifier_from_repo_config",+ "compute_co_changes",+ "compute_co_changes_and_entropy",+ "compute_percentiles",+diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py+new file mode 100644+index 00000000..1286985c+--- /dev/null++++ b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py+@@ -0,0 +1,255 @@++"""Per-commit agent-provenance classification — deterministic, precision-first.++++Labels a commit ``{agent, autonomy_tier, channel, confidence}`` from the++attribution channels available in **local git history** (identity fields,++message footers, ``Co-authored-by:`` trailers — no network, no API calls, no++LLM), in strip-resistance order:++++ Tier 1 (near-autonomous — an agent service account authored the commit):++ * commit AUTHOR is a known agent bot account / service e-mail++ (``copilot-swe-agent[bot]``, ``devin-ai-integration[bot]``,++ ``[email protected]``, ...)++ Tier 2 (human-driven agent — the agent wrote the change):++ * commit-message footer (exact service phrases: "Generated with Claude++ Code", opencode, Codex) or the aider author-name suffix ``... (aider)``++ * a service identity as COMMITTER over a human author (the agent++ pushed/amended a human-driven change — deliberately NOT tier 1)++ Tier 3 (assisted — an agent contributed, a human authored):++ * ``Co-authored-by:`` trailer naming a known agent service identity++++Precedence is tier order (1 > 2 > 3); first match wins. A commit with no++match is human (``None``). Every pattern is anchored to a *service identity*++(bot login, service e-mail, exact footer phrase) — never a bare name. A loose++name pattern is how a human contributor named "Devin" gets misclassified as++the Devin agent; a false "agent-authored" label on a human commit is worse++than a miss.++++PR-level channels (bot PR author, agent branch prefixes, PR-body footers)++require the forge API and are intentionally out of scope here: squash merges++that strip commit trailers are therefore a known recall loss, not a precision++loss. ``confidence`` is carried per channel so future, weaker channels can be++filtered by consumers; every local channel is ``"high"``.++++The default registry below is data, not code: repos can extend it from++``.repowise/config.yaml`` (see :func:`classifier_from_repo_config`) without++touching this module, e.g.::++++ agent_provenance:++ service_emails:++ [email protected]: {agent: mybot, tier: 1}++ footer_patterns:++ - {pattern: "Generated by MyBot", agent: mybot}++ coauthor_patterns:++ - {pattern: "^co-authored-by: mybot <[^>]*@example\\.com>", agent: mybot}++++Classification is pure in-memory regex over already-parsed commit records and++rides the existing commit-index walk — it adds no git subprocess and no I/O.++"""++++from __future__ import annotations++++import re++from dataclasses import dataclass++++import structlog++++logger = structlog.get_logger(__name__)++++__all__ = [++ "AgentProvenance",++ "AgentProvenanceClassifier",++ "classifier_from_repo_config",++]++++++# ------------------------------------------------------------------ registry --++++# Bot login (lowercase, without the ``[bot]`` suffix) → agent name, for++# ``<login>[bot]@users.noreply.github.com`` author/committer e-mails (GitHub's++# canonical bot identity, also re-injected on squash merges).++_BOT_LOGINS: dict[str, str] = {++ "copilot-swe-agent": "copilot",++ "copilot": "copilot",++ "devin-ai-integration": "devin",++ "cursor": "cursor",++ "cursoragent": "cursor",++ "google-labs-jules": "jules",++ "codegen-sh": "codegen",++ "openhands-ai": "openhands",++ "sweep-ai": "sweep",++ "claude": "claude",++}++++# Exact service e-mails → (agent, tier) for commit identity fields.++_SERVICE_EMAILS: dict[str, tuple[str, int]] = {++ "[email protected]": ("cursor", 1),++ "devin-ai-integration[bot]@users.noreply.github.com": ("devin", 1),++}++++# Commit-message footers → agent (exact service phrases only).++_FOOTER_PATTERNS: list[tuple[str, str]] = [++ (r"generated with \[?claude code\]?", "claude"),++ (r"generated with \[?opencode\]?", "opencode"),++ (r"generated with \[?(?:openai )?codex\]?", "codex"),++ (r"^\s*aider wrote this", "aider"),++]++++# ``Co-authored-by:`` trailers → agent. Anchored to the trailer position AND++# the agent's service identity — a name alone is not enough (see module doc).++_COAUTHOR_PATTERNS: list[tuple[str, str]] = [++ (++ r"^co-authored-by:\s*claude(?:\s+(?:opus|sonnet|haiku)[^<]*)?\s*<[^>]*@anthropic\.com>",++ "claude",++ ),++ (r"^co-authored-by:\s*copilot\s*<\d+\+copilot@users\.noreply\.github\.com>", "copilot"),++ (++ r"^co-authored-by:\s*cursor(?:\s*agent)?\s*<(?:cursoragent@cursor\.com|[^>]*cursor[^>]*)>",++ "cursor",++ ),++ (r"^co-authored-by:\s*opencode\s*<", "opencode"),++ (r"^co-authored-by:\s*devin[^<]*<[^>]*devin-ai-integration[^>]*>", "devin"),++ (r"^co-authored-by:\s*aider[^<]*<[^>]*aider[^>]*>", "aider"),++]++++_AIDER_NAME_RE = re.compile(r"\(aider\)\s*$")++++++@dataclass(frozen=True)++class AgentProvenance:++ """One commit's agent attribution. ``agent is None`` means human."""++++ agent: str | None = None++ autonomy_tier: int | None = None # 1 near-autonomous · 2 human-driven · 3 assisted++ channel: str | None = None++ confidence: str | None = None # "high" | "medium" (local channels: always high)++++++_HUMAN = AgentProvenance()++++++class AgentProvenanceClassifier:++ """Compiled pattern registry + the classification rule.++++ Construct once per index run (compilation is the only non-trivial cost);++ :meth:`classify` is then a handful of anchored regex searches per commit.++ Extra patterns merge on top of the built-in registry; they never replace++ it (precision of the defaults is validated, user patterns are additive).++ """++++ def __init__(++ self,++ *,++ extra_service_emails: dict[str, tuple[str, int]] | None = None,++ extra_footer_patterns: list[tuple[str, str]] | None = None,++ extra_coauthor_patterns: list[tuple[str, str]] | None = None,++ ) -> None:++ self._service_emails = {**_SERVICE_EMAILS, **(extra_service_emails or {})}++ # ``[bot]`` is optional: GitHub squash-merges authored by the Copilot++ # coding agent use ``<id>[email protected]`` (no++ # suffix). Safe because each login is a unique, vendor-owned GitHub++ # account — no human can register them.++ self._bot_email_re = re.compile(++ r"^(?:\d+\+)?("++ + "|".join(re.escape(b) for b in _BOT_LOGINS)++ + r")(?:\[bot\])?@users\.noreply\.github\.com$",++ re.IGNORECASE,++ )++ self._footers = [++ (re.compile(p, re.IGNORECASE | re.MULTILINE), agent)++ for p, agent in [*_FOOTER_PATTERNS, *(extra_footer_patterns or [])]++ ]++ self._coauthors = [++ (re.compile(p, re.IGNORECASE | re.MULTILINE), agent)++ for p, agent in [*_COAUTHOR_PATTERNS, *(extra_coauthor_patterns or [])]++ ]++++ def _identity_match(self, email: str) -> tuple[str, int] | None:++ e = (email or "").strip().lower()++ if not e:++ return None++ hit = self._service_emails.get(e)++ if hit:++ return hit++ m = self._bot_email_re.match(e)++ if m:++ return (_BOT_LOGINS[m.group(1).lower()], 1)++ return None++++ def classify(++ self,++ author_name: str,++ author_email: str,++ committer_name: str,++ committer_email: str,++ message: str,++ ) -> AgentProvenance:++ """Classify one commit from local metadata. *message* is the full++ commit message (subject + body) — trailers and footers live in the++ body, so passing the subject alone silently disables two channels."""++ # T1 — agent service identity AUTHORED the commit.++ hit = self._identity_match(author_email)++ if hit:++ return AgentProvenance(hit[0], hit[1], "service_email", "high")++ # T2 — message footer / aider author-name suffix.++ for pat, agent in self._footers:++ if pat.search(message):++ return AgentProvenance(agent, 2, "message_footer", "high")++ if _AIDER_NAME_RE.search(author_name or ""):++ return AgentProvenance("aider", 2, "author_name_aider", "high")++ # T2 — service identity as COMMITTER over a human author: the agent++ # pushed/amended a human-driven change. Deliberately tier 2, not 1.++ hit = self._identity_match(committer_email)++ if hit:++ return AgentProvenance(hit[0], max(hit[1], 2), "service_committer", "high")++ # T3 — co-author trailer naming an agent service identity.++ for pat, agent in self._coauthors:++ if pat.search(message):++ return AgentProvenance(agent, 3, "coauthor_trailer", "high")++ return _HUMAN++++++def classifier_from_repo_config(repo_path: object) -> AgentProvenanceClassifier:++ """Build a classifier with any repo-local pattern extensions.++++ Reads the optional ``agent_provenance`` block of ``.repowise/config.yaml``++ (see module docstring for the shape). Malformed entries are skipped with a++ warning — a broken user pattern must never take down the git index.++ """++ extra_emails: dict[str, tuple[str, int]] = {}++ extra_footers: list[tuple[str, str]] = []++ extra_coauthors: list[tuple[str, str]] = []++ try:++ from ...repo_config import load_repo_config++++ block = load_repo_config(repo_path).get("agent_provenance") or {} # type: ignore[arg-type]++ if isinstance(block, dict):++ for email, spec in (block.get("service_emails") or {}).items():++ if isinstance(spec, dict) and spec.get("agent"):++ tier = max(1, min(3, int(spec.get("tier", 1))))++ extra_emails[str(email).lower()] = (str(spec["agent"]), tier)++ for key, sink in (++ ("footer_patterns", extra_footers),++ ("coauthor_patterns", extra_coauthors),++ ):++ for entry in block.get(key) or []:++ if not (++ isinstance(entry, dict) and entry.get("pattern") and entry.get("agent")++ ):++ continue++ try:++ re.compile(entry["pattern"])++ except re.error as exc:++ logger.warning(++ "agent_provenance_pattern_invalid",++ pattern=entry["pattern"],++ error=str(exc),++ )++ continue++ sink.append((entry["pattern"], str(entry["agent"])))++ except Exception as exc: # config parsing must never break indexing++ logger.warning("agent_provenance_config_failed", error=str(exc))++ return AgentProvenanceClassifier(++ extra_service_emails=extra_emails,++ extra_footer_patterns=extra_footers,++ extra_coauthor_patterns=extra_coauthors,++ )+diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py+index d49a2b7d..1ce3cedb 100644+--- a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py++++ b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py+@@ -98,6 +98,12 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:+ "author_experience": exp,+ "change_risk_score": risk.score,+ "change_risk_level": risk.level,++ # Agent provenance — classified during the walk (commit-index++ # sink); pure passthrough here so this transform stays git-free.++ "agent_name": c.get("agent_name"),++ "agent_autonomy_tier": c.get("agent_autonomy_tier"),++ "agent_channel": c.get("agent_channel"),++ "agent_confidence": c.get("agent_confidence"),+ }+ )+ return rows+diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py+index 59e81574..938ef0a4 100644+--- a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py++++ b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py+@@ -208,15 +208,18 @@ def compute_percentiles(metadata_list: list[dict]) -> None:++ total = len(metadata_list)+ for rank, idx in enumerate(sorted_by_churn):+- metadata_list[idx]["churn_percentile"] = rank / total if total > 0 else 0.0+-+- # Hotspot: top 25% churn (churn_percentile >= 0.75) AND the absolute+- # activity floors — without the floors, a quiet repo's top quartile is+- # just "every file touched in 90 days" (issue #361).+- for meta in metadata_list:+- churn_pct = meta.get("churn_percentile", 0.0)++ meta = metadata_list[idx]++ churn_pct = rank / total if total > 0 else 0.0++ meta["churn_percentile"] = churn_pct++ # Hotspot: top 25% churn (churn_percentile >= 0.75) AND the absolute++ # activity floors — without the floors, a quiet repo's top quartile is++ # just "every file touched in 90 days" (issue #361). Folded into the++ # rank loop so the list is scanned once.+ if churn_pct >= 0.75 and meets_hotspot_floors(meta):+ meta["is_hotspot"] = True++ # change_entropy percentile default — overwritten below for files++ # carrying a positive entropy signal.++ meta.setdefault("change_entropy_pct", 0.0)++ # change_entropy percentile (mirrors churn_percentile). Rank ONLY files+ # that carry a positive entropy signal; files with zero entropy — every+@@ -224,8 +227,6 @@ def compute_percentiles(metadata_list: list[dict]) -> None:+ # alone — keep pct 0.0 so the change_entropy biomarker stays silent. (A+ # naive rank-everything would hand the topmost zero-entropy file a high+ # percentile when most files are zero.)+- for meta in metadata_list:+- meta.setdefault("change_entropy_pct", 0.0)+ entropy_idxs = [+ i for i in range(total) if (metadata_list[i].get("change_entropy") or 0.0) > 0.0+ ]+diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py+index 9f50dd7f..3fe4c8ca 100644+--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py++++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py+@@ -110,6 +110,12 @@ def new_meta(file_path: str) -> dict[str, Any]:+ # ``prior_defect`` health biomarker; mirrors the benchmark's+ # prior-defects baseline definition (product == benchmark).+ "prior_defect_count": 0,++ # Agent provenance rollup: how much of this file's indexed history is++ # agent-attributed (local channels only — see agent_provenance module).++ # agent_authored_pct stays None when the file has no commits at all.++ "agent_commit_count": 0,++ "agent_authored_pct": None,++ "agent_tier_counts_json": "{}",+ # Temporal hotspot score (exponentially decayed churn)+ "temporal_hotspot_score": 0.0,+ # Change entropy (Hassan HCM) — populated repo-wide by the co-change+@@ -126,6 +132,7 @@ def _parse_per_file_log(+ *,+ commit_limit: int,+ follow_renames: bool,++ provenance_classifier: Any | None = None,+ ) -> tuple[list[_CommitRec], str | None]:+ """Run a per-file ``git log --numstat`` and parse it into commit records.++@@ -176,6 +183,16 @@ def _parse_per_file_log(+ subject=header["subject"],+ body=header["body"],+ )++ if provenance_classifier is not None:++ prov = provenance_classifier.classify(++ header["author_name"],++ header["author_email"],++ header["committer_name"],++ header["committer_email"],++ f"{header['subject']}\n{header['body']}",++ )++ current.agent = prov.agent++ current.agent_tier = prov.autonomy_tier+ commits.append(current)+ for line in numstat_lines:+ numstat_parts = line.split("\t")+@@ -205,6 +222,7 @@ def index_file(+ include_blame: bool = True,+ precomputed_commits: list[_CommitRec] | None = None,+ as_of_ts: float | None = None,++ provenance_classifier: Any | None = None,+ ) -> dict:+ """Index a single file's git history. Runs in executor.++@@ -239,6 +257,7 @@ def index_file(+ file_path,+ commit_limit=commit_limit,+ follow_renames=follow_renames,++ provenance_classifier=provenance_classifier,+ )++ if not commits:+@@ -291,6 +310,18 @@ def index_file(+ total_churn = meta["lines_added_90d"] + meta["lines_deleted_90d"]+ meta["avg_commit_size"] = total_churn / c90 if c90 > 0 else 0.0+++ # Agent-provenance rollup: share of this file's indexed commits that++ # are agent-attributed, plus the per-autonomy-tier breakdown. The++ # per-commit labels were classified once during the walk; this is a++ # pure count over the already-carried records.++ agent_commits = [c for c in commits if getattr(c, "agent", None)]++ meta["agent_commit_count"] = len(agent_commits)++ meta["agent_authored_pct"] = len(agent_commits) / len(commits)++ tier_counts: Counter[str] = Counter(++ str(c.agent_tier) for c in agent_commits if c.agent_tier++ )++ meta["agent_tier_counts_json"] = json.dumps(dict(tier_counts))+++ # Temporal hotspot score: exponentially decayed per-commit churn.+ _ln2 = math.log(2)+ temporal_score = 0.0+diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+index 0cd84ed1..58ed967f 100644+--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py++++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+@@ -12,6 +12,7 @@ import asyncio+ import contextlib+ import json+ import os++import threading+ import time+ from collections.abc import Callable+ from pathlib import Path+@@ -120,6 +121,7 @@ class GitIndexer:+ # ``git log -- <file>`` — turning O(files) process spawns into O(1).+ commit_index: dict[str, list[_CommitRec]] = {}+ commit_sink: list[dict] = []++ prov_clf = self._provenance_classifier()+ if not self.follow_renames:+ from ..git_commit_index import load_commit_index++@@ -128,31 +130,35 @@ class GitIndexer:+ self.commit_limit,+ set(indexable_files),+ commit_sink=commit_sink,++ provenance_classifier=prov_clf,+ )++ include_blame = self.tier.includes_blame+ as_of_ts = self._resolve_as_of_ts(repo, commit_index)++ get_thread_repo, close_thread_repos = self._thread_repo_pool()++ def _index_one_sync(file_path: str) -> dict:+- """Use a per-thread Repo to avoid shared-handle issues on Windows."""+- try:+- import git as gitpython++ """Use a per-thread Repo to avoid shared-handle issues on Windows.++- thread_repo = gitpython.Repo(self.repo_path, search_parent_directories=True)+- try:+- precomputed = commit_index.get(file_path) if commit_index else None+- return index_file(+- thread_repo,+- file_path,+- repo_path=self.repo_path,+- commit_limit=self.commit_limit,+- follow_renames=self.follow_renames,+- include_blame=include_blame,+- precomputed_commits=precomputed,+- as_of_ts=as_of_ts,+- )+- finally:+- thread_repo.close()++ The Repo is created once per worker thread and reused across files++ — constructing a fresh ``gitpython.Repo`` per file costs ~40 ms++ each (config + ref resolution), which dominated the git phase on++ repos with thousands of files.++ """++ try:++ thread_repo = get_thread_repo()++ precomputed = commit_index.get(file_path) if commit_index else None++ return index_file(++ thread_repo,++ file_path,++ repo_path=self.repo_path,++ commit_limit=self.commit_limit,++ follow_renames=self.follow_renames,++ include_blame=include_blame,++ precomputed_commits=precomputed,++ as_of_ts=as_of_ts,++ provenance_classifier=prov_clf,++ )+ except Exception:+ return {"file_path": file_path}++@@ -212,6 +218,7 @@ class GitIndexer:+ # Abandon any timed-out threads immediately instead of letting+ # asyncio.run() block for minutes during default-executor cleanup.+ executor.shutdown(wait=False, cancel_futures=True)++ close_thread_repos()++ results: list[dict] = []+ for r in metadata_list:+@@ -279,7 +286,14 @@ class GitIndexer:+ return summary, results++ async def index_changed_files(self, changed_file_paths: list[str]) -> list[dict]:+- """Incremental update: re-index only changed files."""++ """Incremental update: re-index only changed files.++++ Mirrors ``index_repo``'s batched shape: one repo-wide commit-index++ walk feeds every per-file worker (instead of one ``git log -- <file>``++ subprocess per changed file), so the metadata an update produces is++ identical to what a fresh full index would produce — including the++ agent-provenance rollup, which the old per-file path never classified.++ """+ repo = self._get_repo()+ if repo is None:+ return []+@@ -287,25 +301,36 @@ class GitIndexer:+ loop = asyncio.get_event_loop()+ semaphore = asyncio.Semaphore(20)+ include_blame = self.tier.includes_blame+- as_of_ts = self._resolve_as_of_ts(repo)++++ prov_clf = self._provenance_classifier()++ commit_index: dict[str, list[_CommitRec]] = {}++ if not self.follow_renames:++ from ..git_commit_index import load_commit_index++++ commit_index = load_commit_index(++ repo,++ self.commit_limit,++ set(changed_file_paths),++ provenance_classifier=prov_clf,++ )++ as_of_ts = self._resolve_as_of_ts(repo, commit_index)++ get_thread_repo, close_thread_repos = self._thread_repo_pool()++ def _index_one_sync(file_path: str) -> dict:+ try:+- import git as gitpython+-+- thread_repo = gitpython.Repo(self.repo_path, search_parent_directories=True)+- try:+- return index_file(+- thread_repo,+- file_path,+- repo_path=self.repo_path,+- commit_limit=self.commit_limit,+- follow_renames=self.follow_renames,+- include_blame=include_blame,+- as_of_ts=as_of_ts,+- )+- finally:+- thread_repo.close()++ thread_repo = get_thread_repo()++ precomputed = commit_index.get(file_path) if commit_index else None++ return index_file(++ thread_repo,++ file_path,++ repo_path=self.repo_path,++ commit_limit=self.commit_limit,++ follow_renames=self.follow_renames,++ include_blame=include_blame,++ precomputed_commits=precomputed,++ as_of_ts=as_of_ts,++ provenance_classifier=prov_clf,++ )+ except Exception:+ return {"file_path": file_path}++@@ -325,7 +350,10 @@ class GitIndexer:+ return {"file_path": file_path}++ tasks = [index_one(fp) for fp in changed_file_paths]+- results_raw = await asyncio.gather(*tasks, return_exceptions=True)++ try:++ results_raw = await asyncio.gather(*tasks, return_exceptions=True)++ finally:++ close_thread_repos()++ results: list[dict] = []+ for r in results_raw:+@@ -373,7 +401,12 @@ class GitIndexer:+ # Empty indexable set: we only want the full-footprint sink, not the+ # per-file bucket (which the incremental file pass already rebuilt).+ load_commit_index(+- repo, self.commit_limit, set(), commit_sink=sink, since_ts=since_ts++ repo,++ self.commit_limit,++ set(),++ commit_sink=sink,++ since_ts=since_ts,++ provenance_classifier=self._provenance_classifier(),+ )+ return build_commit_rows(sink)+ except Exception as exc:+@@ -386,6 +419,22 @@ class GitIndexer:+ # Internal methods+ # ------------------------------------------------------------------+++ def _provenance_classifier(self) -> Any:++ """Config-aware agent-provenance classifier, built once per index run.++++ Failure-isolated: a malformed repo config falls back to the built-in++ pattern registry rather than breaking the git phase.++ """++ try:++ from .agent_provenance import classifier_from_repo_config++++ return classifier_from_repo_config(self.repo_path)++ except Exception as exc:++ logger.debug("agent_provenance_classifier_failed", error=str(exc))++ from .agent_provenance import AgentProvenanceClassifier++++ return AgentProvenanceClassifier()+++ def _resolve_as_of_ts(+ self, repo: Any, commit_index: dict[str, list[_CommitRec]] | None = None+ ) -> float | None:+@@ -417,6 +466,42 @@ class GitIndexer:+ except Exception:+ return None+++ def _thread_repo_pool(self) -> tuple[Callable[[], Any], Callable[[], None]]:++ """Return ``(get_thread_repo, close_all)`` for per-thread Repo reuse.++++ gitpython ``Repo`` handles can't be shared across threads on Windows,++ but constructing one per *file* costs ~40 ms each. This pool hands++ each worker thread its own lazily-created ``Repo`` and reuses it for++ every file that thread processes. ``close_all()`` closes every repo++ the pool created; a worker thread abandoned mid-file (timeout) will++ see its repo closed underneath it and fall into the existing++ per-file exception path, which is the same partial-data outcome the++ old per-file construction produced on failure.++ """++ tls = threading.local()++ created: list[Any] = []++ lock = threading.Lock()++++ def get_thread_repo() -> Any:++ repo = getattr(tls, "repo", None)++ if repo is None:++ import git as gitpython++++ repo = gitpython.Repo(self.repo_path, search_parent_directories=True)++ tls.repo = repo++ with lock:++ created.append(repo)++ return repo++++ def close_all() -> None:++ with lock:++ repos, created[:] = list(created), []++ for repo in repos:++ with contextlib.suppress(Exception):++ repo.close()++++ return get_thread_repo, close_all+++ def _get_repo(self) -> Any | None:+ try:+ import git as gitpython+diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.py+index 420d3fda..b6050f70 100644+--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py++++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py+@@ -38,8 +38,10 @@ _FIELD_SEP = "\x1f"+ # ``%an``/``%ae``) so a repo's ``.mailmap`` folds a contributor's multiple+ # names/emails — personal vs. GitHub ``noreply``, a second machine's git config —+ # into one identity. Without this, ownership and "last touched" split one human+-# across several contributor buckets.+-_LOG_FORMAT = "%x00%H%x1f%aN%x1f%aE%x1f%ct%x1f%P%x1f%s%x1f%b"++# across several contributor buckets. Committer name/email (``%cN``/``%cE``)++# ride the same record for agent-provenance classification: a service identity++# as committer over a human author means an agent pushed/amended the change.++_LOG_FORMAT = "%x00%H%x1f%aN%x1f%aE%x1f%cN%x1f%cE%x1f%ct%x1f%P%x1f%s%x1f%b"++ # A git ``--numstat`` line: ``<added>\t<deleted>\t<path>`` where added/deleted+ # are decimal counts or ``-`` for binary files. Used to split the trailing+@@ -60,6 +62,10 @@ class _CommitRec:+ body: str = ""+ added: int = 0+ deleted: int = 0++ # Agent provenance (classified once per commit during the walk; carried on++ # the record so per-file rollups don't re-run the regex per touched file).++ agent: str | None = None++ agent_tier: int | None = None+++ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:+@@ -67,7 +73,7 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:++ A record (after the leading record separator is stripped) looks like::++- <sha>\\x1f<an>\\x1f<ae>\\x1f<ct>\\x1f<parents>\\x1f<subject>\\x1f<body>\\n<numstat...>++ <sha>\\x1f<an>\\x1f<ae>\\x1f<cn>\\x1f<ce>\\x1f<ct>\\x1f<parents>\\x1f<subject>\\x1f<body>\\n<numstat...>++ The body is multi-line, so the trailing ``--numstat`` block is identified+ by the first line matching :data:`_NUMSTAT_RE`; everything before it is+@@ -76,12 +82,12 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:+ fields except ``added``/``deleted`` (the caller attributes churn).+ """+ parts = record.split(_FIELD_SEP)+- if len(parts) < 7:++ if len(parts) < 9:+ return None+- sha, an, ae, ct, parents, subject = parts[:6]++ sha, an, ae, cn, ce, ct, parents, subject = parts[:8]+ # %b cannot contain the field separator, so the body + numstat tail is the+- # 7th field exactly (join is defensive against an unexpected stray sep).+- body_and_numstat = _FIELD_SEP.join(parts[6:])++ # 9th field exactly (join is defensive against an unexpected stray sep).++ body_and_numstat = _FIELD_SEP.join(parts[8:])++ body_lines: list[str] = []+ numstat_lines: list[str] = []+@@ -103,6 +109,8 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:+ "sha": sha,+ "author_name": an or "unknown",+ "author_email": ae,++ "committer_name": cn or "",++ "committer_email": ce or "",+ "ts": ts,+ "is_merge": len(parents.split()) > 1,+ "subject": subject,+diff --git a/packages/core/src/repowise/core/ingestion/graph/_betweenness.py b/packages/core/src/repowise/core/ingestion/graph/_betweenness.py+new file mode 100644+index 00000000..e2585c9e+--- /dev/null++++ b/packages/core/src/repowise/core/ingestion/graph/_betweenness.py+@@ -0,0 +1,155 @@++"""Parallel exact betweenness centrality (Brandes) over a process pool.++++``nx.betweenness_centrality`` is pure-Python Brandes: O(V·E) per run, single++threaded, and it does not release the GIL — on a ~11k-node symbol subgraph it++is by far the most expensive metric kernel (~54s isolated, measured on the++repowise repo itself). Brandes is embarrassingly parallel over *source*++nodes: each source's dependency accumulation is independent and the final++score is the plain sum of the per-source partials. This module fans the++source set out across a process pool and sums the partials, producing the++same values as the sequential call (the only difference is floating-point++summation order, bounded at ~1e-15 relative).++++Workers receive the graph once (pool initializer) as an integer edge list —++node attributes are irrelevant to betweenness, so the pickled payload stays++small even for graphs whose node ids are long symbol strings.++++Falls back to ``nx.betweenness_centrality`` whenever the graph is small++enough that pool startup would dominate, or the pool / NetworkX internals++are unavailable.++"""++++from __future__ import annotations++++import os++from concurrent.futures import ProcessPoolExecutor++++import networkx as nx++import structlog++++log = structlog.get_logger(__name__)++++# Parallelize only when the estimated Brandes cost (~nodes x edges) is large++# enough to amortize process startup (~2-3s for pool spawn + imports).++# Measured rates on the repowise graph: file subgraph (1.8k x 5.2k ~ 1e7)++# runs in ~0.4s sequentially; the symbol subgraph (11.3k x 12k ~ 1.4e8)++# takes ~54s. The threshold sits between the two.++_PARALLEL_COST_THRESHOLD = 4e7++++# ---------------------------------------------------------------------------++# Worker side (must be module-level + picklable for Windows spawn)++# ---------------------------------------------------------------------------++++_WORKER_GRAPH: nx.DiGraph | None = None++++++def _init_worker(n: int, edges: list[tuple[int, int]], directed: bool) -> None:++ """Pool initializer: build the (attribute-free) int-labeled graph once."""++ global _WORKER_GRAPH++ g: nx.DiGraph = nx.DiGraph() if directed else nx.Graph()++ g.add_nodes_from(range(n))++ g.add_edges_from(edges)++ _WORKER_GRAPH = g++++++def _partial_betweenness(sources: list[int]) -> dict[int, float]:++ """Accumulate Brandes dependencies for a chunk of source nodes.++++ Mirrors the per-source loop of ``nx.betweenness_centrality`` exactly++ (unweighted BFS + basic accumulation, no endpoints). Summing the++ partials over all chunks reproduces the sequential pre-rescale values.++ """++ from networkx.algorithms.centrality.betweenness import (++ _accumulate_basic,++ _single_source_shortest_path_basic,++ )++++ g = _WORKER_GRAPH++ assert g is not None, "worker pool initializer did not run"++ betweenness: dict[int, float] = dict.fromkeys(g, 0.0)++ for s in sources:++ S, P, sigma, _ = _single_source_shortest_path_basic(g, s) # noqa: N806 - NX naming++ betweenness, _ = _accumulate_basic(betweenness, S, P, sigma, s)++ # Only non-zero entries cross the process boundary.++ return {v: b for v, b in betweenness.items() if b != 0.0}++++++# ---------------------------------------------------------------------------++# Parent side++# ---------------------------------------------------------------------------++++++def _rescale(++ betweenness: dict[int, float], n: int, *, normalized: bool, directed: bool++) -> dict[int, float]:++ """Rescale raw accumulations exactly like NetworkX (k=None, no endpoints)."""++ if normalized:++ scale = None if n <= 2 else 1 / ((n - 1) * (n - 2))++ else:++ scale = None if directed else 0.5++ if scale is not None:++ for v in betweenness:++ betweenness[v] *= scale++ return betweenness++++++def betweenness_centrality_fast(++ g: nx.DiGraph,++ *,++ normalized: bool = True,++ max_workers: int | None = None,++) -> dict[str, float]:++ """Exact betweenness centrality, parallelized over sources when worthwhile.++++ Drop-in equivalent of ``nx.betweenness_centrality(g, normalized=...)``++ for unweighted graphs without endpoint counting. Small graphs (or any++ pool failure) take the sequential NetworkX path, so callers never need++ a fallback of their own.++ """++ n = g.number_of_nodes()++ e = g.number_of_edges()++ if n == 0:++ return {}++ workers = max_workers or os.cpu_count() or 1++ if n * e < _PARALLEL_COST_THRESHOLD or workers < 2:++ return nx.betweenness_centrality(g, normalized=normalized)++++ try:++ # Verify the NetworkX internals the workers rely on exist in this++ # version before paying for pool spawn.++ from networkx.algorithms.centrality.betweenness import ( # noqa: F401++ _accumulate_basic,++ _single_source_shortest_path_basic,++ )++ except ImportError: # pragma: no cover - depends on networkx version++ log.warning("betweenness_parallel_unavailable", reason="networkx internals moved")++ return nx.betweenness_centrality(g, normalized=normalized)++++ nodes = list(g)++ index = {node: i for i, node in enumerate(nodes)}++ edges = [(index[u], index[v]) for u, v in g.edges()]++++ # ~3 chunks per worker for load balancing without excessive IPC.++ chunk_count = max(1, workers * 3)++ chunk_size = max(1, (n + chunk_count - 1) // chunk_count)++ chunks = [list(range(i, min(i + chunk_size, n))) for i in range(0, n, chunk_size)]++++ totals = [0.0] * n++ try:++ with ProcessPoolExecutor(++ max_workers=workers,++ initializer=_init_worker,++ initargs=(n, edges, g.is_directed()),++ ) as pool:++ # ``map`` preserves chunk order, keeping float summation++ # deterministic for a given worker count.++ for partial in pool.map(_partial_betweenness, chunks):++ for v, b in partial.items():++ totals[v] += b++ except Exception as exc: # pragma: no cover - depends on host environment++ log.warning("betweenness_parallel_failed_falling_back", error=str(exc))++ return nx.betweenness_centrality(g, normalized=normalized)++++ raw = dict(enumerate(totals))++ _rescale(raw, n, normalized=normalized, directed=g.is_directed())++ return {nodes[i]: score for i, score in raw.items()}+diff --git a/packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py b/packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py+new file mode 100644+index 00000000..4d64ce54+--- /dev/null++++ b/packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py+@@ -0,0 +1,113 @@++"""Structure-keyed disk cache for betweenness centrality.++++Exact betweenness (Brandes) is the most expensive metric kernel on every++ingest — and an incremental ``repowise update`` recomputes it for the whole++graph even when the docstring-only edit it processed didn't change a single++edge. Betweenness is a pure function of the *structure* of the (unweighted)++subgraph it runs on, so values cache safely keyed by a signature over the++sorted node and edge sets: content edits that don't move call/heritage/import++edges hit; any structural change misses and recomputes.++++One entry per kind (``file`` / ``symbol``) — the cache answers "is the graph++still the one I last scored?", not a history. Thread-safe because the init++pipeline computes both kinds concurrently. Best-effort by design: any++load/save error degrades to a fresh computation.++++Note for the >30k-node sampled path (``nx.betweenness_centrality(k=...)``):++sampling is seedless, so recomputing the same graph yields slightly++different values run to run. A cache hit returns the previously sampled++values — deterministic where the status quo was not.++"""++++from __future__ import annotations++++import contextlib++import hashlib++import os++import pickle++import tempfile++import threading++from pathlib import Path++++import structlog++++log = structlog.get_logger(__name__)++++_CACHE_VERSION = 1++_CACHE_FILENAME = "centrality_cache.pkl"++++__all__ = ["CentralityCache", "subgraph_signature"]++++++def subgraph_signature(graph) -> str:++ """Hash the structure (sorted nodes + edges) of *graph*.++++ Attributes are deliberately excluded — betweenness on these subgraphs is++ unweighted, and the subgraph constructors already filtered edges by type.++ """++ h = hashlib.sha256()++ for node in sorted(graph.nodes()):++ h.update(node.encode("utf-8", "replace"))++ h.update(b"\x00")++ h.update(b"\x01")++ for u, v in sorted(graph.edges()):++ h.update(u.encode("utf-8", "replace"))++ h.update(b"\x00")++ h.update(v.encode("utf-8", "replace"))++ h.update(b"\x00")++ return h.hexdigest()++++++class CentralityCache:++ """Pickle-backed ``kind -> (signature, values)`` store."""++++ def __init__(self, cache_dir: Path | str) -> None:++ self._path = Path(cache_dir) / _CACHE_FILENAME++ self._entries: dict[str, tuple[str, dict[str, float]]] = {}++ self._lock = threading.Lock()++ self._loaded = False++++ def _ensure_loaded(self) -> None:++ if self._loaded:++ return++ self._loaded = True++ try:++ with self._path.open("rb") as fh:++ payload = pickle.load(fh)++ if payload.get("version") != _CACHE_VERSION:++ return++ self._entries = payload.get("entries", {})++ except FileNotFoundError:++ return++ except Exception as exc: # corrupt / unreadable cache -> recompute++ log.debug("centrality_cache_load_failed", error=str(exc))++++ def get(self, kind: str, signature: str) -> dict[str, float] | None:++ with self._lock:++ self._ensure_loaded()++ entry = self._entries.get(kind)++ if entry is None or entry[0] != signature:++ return None++ return dict(entry[1])++++ def put(self, kind: str, signature: str, values: dict[str, float]) -> None:++ """Store *values* for *kind* and persist atomically."""++ with self._lock:++ self._ensure_loaded()++ self._entries[kind] = (signature, dict(values))++ try:++ self._path.parent.mkdir(parents=True, exist_ok=True)++ payload = {"version": _CACHE_VERSION, "entries": self._entries}++ fd, tmp_name = tempfile.mkstemp(++ dir=str(self._path.parent), prefix=_CACHE_FILENAME, suffix=".tmp"++ )++ try:++ with os.fdopen(fd, "wb") as fh:++ pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)++ os.replace(tmp_name, self._path)++ except BaseException:++ with contextlib.suppress(OSError):++ os.unlink(tmp_name)++ raise++ except Exception as exc:++ log.debug("centrality_cache_save_failed", error=str(exc))+diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py+index 73789287..06748cd3 100644+--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py++++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py+@@ -62,6 +62,8 @@ class EdgesMixin:+ count += 1++ log.info("Co-change edges added", count=count)++ if count:++ self._invalidate_subgraph_caches()+ return count++ def update_co_change_edges(self, updated_meta: dict, min_count: int = 3) -> None:+@@ -72,6 +74,7 @@ class EdgesMixin:+ edges_to_remove.append((u, v))+ self._graph.remove_edges_from(edges_to_remove)+ self.add_co_change_edges(updated_meta, min_count)++ self._invalidate_subgraph_caches()++ def add_dynamic_edges(self, edges: list) -> None:+ """Add dynamic-hint edges to the graph. Each edge is a DynamicEdge."""+@@ -97,6 +100,8 @@ class EdgesMixin:+ # source file node as is_test so downstream consumers can filter it.+ if e.hint_source and e.hint_source.endswith(":test"):+ self._graph.nodes[e.source]["is_test"] = True++ if edges:++ self._invalidate_subgraph_caches()++ def add_framework_edges(self, tech_stack: list[str] | None = None) -> int:+ """Add synthetic edges for framework-mediated relationships.+@@ -124,4 +129,5 @@ class EdgesMixin:+ count = add_framework_edges(self._graph, self._parsed_files, ctx, tech_stack)+ if count:+ log.info("Framework edges added", count=count)++ self._invalidate_subgraph_caches()+ return count+diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.py+index 052a8de7..377c52f1 100644+--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py++++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py+@@ -76,17 +76,35 @@ class MetricsMixin:+ # ------------------------------------------------------------------++ def file_subgraph(self) -> nx.DiGraph:+- """Return a subgraph containing only file-level nodes and import edges."""+- g = self.graph()+- file_nodes = [+- n for n, d in g.nodes(data=True) if d.get("node_type", "file") in ("file", "external")+- ]+- sub = g.subgraph(file_nodes).copy()+- edges_to_remove = [+- (u, v) for u, v, d in sub.edges(data=True) if d.get("edge_type") in ("co_changes",)+- ]+- sub.remove_edges_from(edges_to_remove)+- return sub++ """Return a subgraph containing only file-level nodes and import edges.++++ Cached per build — five metric kernels (SCC, PageRank, betweenness,++ in/out degree) read it, and rebuilding the filtered copy per call is++ O(V+E) each time. The cache is guarded by ``_subgraph_lock`` because++ the init pipeline computes metrics concurrently via++ ``asyncio.to_thread``. Callers must treat the result as read-only.++ """++ cached = self._file_subgraph_cache++ if cached is not None:++ return cached++ with self._subgraph_lock:++ if self._file_subgraph_cache is not None:++ return self._file_subgraph_cache++ g = self.graph()++ file_nodes = [++ n++ for n, d in g.nodes(data=True)++ if d.get("node_type", "file") in ("file", "external")++ ]++ sub = g.subgraph(file_nodes).copy()++ edges_to_remove = [++ (u, v)++ for u, v, d in sub.edges(data=True)++ if d.get("edge_type") in ("co_changes",)++ ]++ sub.remove_edges_from(edges_to_remove)++ self._file_subgraph_cache = sub++ return sub++ def symbol_subgraph(self) -> nx.DiGraph:+ """Return a subgraph of symbol nodes connected by call + heritage edges.+@@ -94,17 +112,27 @@ class MetricsMixin:+ File-to-symbol ``defines`` edges and class-to-method ``has_method``+ ownership edges are dropped so that the resulting centrality+ scores reflect call/heritage flow rather than containment.++++ Cached per build (see :meth:`file_subgraph` for the locking++ rationale). Callers must treat the result as read-only.+ """+- g = self.graph()+- symbol_nodes = [n for n, d in g.nodes(data=True) if d.get("node_type") == "symbol"]+- sub = g.subgraph(symbol_nodes).copy()+- edges_to_remove = [+- (u, v)+- for u, v, d in sub.edges(data=True)+- if d.get("edge_type") not in ("calls", "extends", "implements")+- ]+- sub.remove_edges_from(edges_to_remove)+- return sub++ cached = self._symbol_subgraph_cache++ if cached is not None:++ return cached++ with self._subgraph_lock:++ if self._symbol_subgraph_cache is not None:++ return self._symbol_subgraph_cache++ g = self.graph()++ symbol_nodes = [n for n, d in g.nodes(data=True) if d.get("node_type") == "symbol"]++ sub = g.subgraph(symbol_nodes).copy()++ edges_to_remove = [++ (u, v)++ for u, v, d in sub.edges(data=True)++ if d.get("edge_type") not in ("calls", "extends", "implements")++ ]++ sub.remove_edges_from(edges_to_remove)++ self._symbol_subgraph_cache = sub++ return sub++ # ------------------------------------------------------------------+ # File-level metrics+@@ -136,15 +164,10 @@ class MetricsMixin:+ if self._betweenness_cache is not None:+ return self._betweenness_cache+ g = self.file_subgraph()+- n = g.number_of_nodes()+- if n == 0:++ if g.number_of_nodes() == 0:+ self._betweenness_cache = {}+ return self._betweenness_cache+- if n > _LARGE_REPO_THRESHOLD:+- k = min(500, n)+- self._betweenness_cache = nx.betweenness_centrality(g, k=k, normalized=True)+- else:+- self._betweenness_cache = nx.betweenness_centrality(g, normalized=True)++ self._betweenness_cache = self._betweenness_with_disk_cache("file", g)+ return self._betweenness_cache++ def in_degree(self) -> dict[str, int]:+@@ -239,16 +262,51 @@ class MetricsMixin:+ if self._symbol_betweenness_cache is not None:+ return self._symbol_betweenness_cache+ sub = self.symbol_subgraph()+- n = sub.number_of_nodes()+- if n == 0:++ if sub.number_of_nodes() == 0:+ self._symbol_betweenness_cache = {}+ return self._symbol_betweenness_cache++ self._symbol_betweenness_cache = self._betweenness_with_disk_cache("symbol", sub)++ return self._symbol_betweenness_cache++++ def _betweenness_with_disk_cache(self, kind: str, g: nx.DiGraph) -> dict[str, float]:++ """Compute betweenness for *g*, consulting the structure-keyed disk cache.++++ With a cache attached (see ``GraphBuilder(centrality_cache_dir=...)``)++ and an unchanged subgraph structure, the previous run's values are++ returned without re-running Brandes — the dominant metric cost of an++ incremental update whose change didn't move any edges. Structural++ changes, cache errors, or no cache all fall through to the exact++ computation used before.++ """++ cache = getattr(self, "_centrality_cache", None)++ signature: str | None = None++ if cache is not None:++ try:++ from ._centrality_cache import subgraph_signature++++ signature = subgraph_signature(g)++ hit = cache.get(kind, signature)++ if hit is not None:++ log.info("betweenness_reused_from_cache", kind=kind, nodes=len(hit))++ return hit++ except Exception as exc:++ log.debug("centrality_cache_lookup_failed", kind=kind, error=str(exc))++ signature = None++++ n = g.number_of_nodes()+ if n > _LARGE_REPO_THRESHOLD:+ k = min(500, n)+- self._symbol_betweenness_cache = nx.betweenness_centrality(sub, k=k, normalized=True)++ values = nx.betweenness_centrality(g, k=k, normalized=True)+ else:+- self._symbol_betweenness_cache = nx.betweenness_centrality(sub, normalized=True)+- return self._symbol_betweenness_cache++ from ._betweenness import betweenness_centrality_fast++++ values = betweenness_centrality_fast(g, normalized=True)++ if cache is not None and signature is not None:++ try:++ cache.put(kind, signature, values)++ except Exception as exc:++ log.debug("centrality_cache_store_failed", kind=kind, error=str(exc))++ return values++ # ------------------------------------------------------------------+ # Execution flows + bulk priming+diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py+index b0580416..62c94ae5 100644+--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py++++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py+@@ -16,6 +16,16 @@ log = structlog.get_logger(__name__)+ class ResolveMixin:+ """Symbol-level edge resolution passes run during ``build()``."""+++ def _shared_import_maps(self) -> Any:++ """Build the import-name maps once per build; both resolvers share them."""++ maps = getattr(self, "_import_name_maps", None)++ if maps is None:++ from ..import_index import build_import_name_maps++++ maps = build_import_name_maps(self._parsed_files)++ self._import_name_maps = maps++ return maps+++ def _resolve_heritage(+ self,+ import_targets: dict[str, set[str]],+@@ -24,7 +34,9 @@ class ResolveMixin:+ """Resolve heritage relations and add EXTENDS/IMPLEMENTS edges."""+ from ..heritage_resolver import HeritageResolver++- resolver = HeritageResolver(self._parsed_files, import_targets)++ resolver = HeritageResolver(++ self._parsed_files, import_targets, import_maps=self._shared_import_maps()++ )+ total_resolved = 0++ files_with_heritage = [+@@ -135,7 +147,12 @@ class ResolveMixin:+ """Run three-tier call resolution and add CALLS edges to the graph."""+ from ..call_resolver import CallResolver++- resolver = CallResolver(self._parsed_files, import_targets, repo_path=str(self._repo_path) if self._repo_path else None)++ resolver = CallResolver(++ self._parsed_files,++ import_targets,++ repo_path=str(self._repo_path) if self._repo_path else None,++ import_maps=self._shared_import_maps(),++ )+ total_resolved = 0++ files_with_calls = [+diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py+index 9f6223d4..862b5ef0 100644+--- a/packages/core/src/repowise/core/ingestion/graph/builder.py++++ b/packages/core/src/repowise/core/ingestion/graph/builder.py+@@ -45,12 +45,24 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd+ repo_path: Path | str | None = None,+ *,+ exclude_patterns: list[str] | None = None,++ centrality_cache_dir: Path | str | None = None,+ ) -> None:+ self._graph: nx.DiGraph = nx.DiGraph()+ self._parsed_files: dict[str, ParsedFile] = {} # path → ParsedFile+ self._built = False+ self._repo_path: Path | None = Path(repo_path) if repo_path else None+ self._tsconfig_resolver: Any | None = None # TsconfigResolver (lazy import)++ # Optional structure-keyed disk cache for betweenness (the most++ # expensive metric kernel). Opt-in via *centrality_cache_dir* — the++ # ingest paths pass ``<repo>/.repowise``; ad-hoc builders are unchanged.++ self._centrality_cache: Any | None = None++ if centrality_cache_dir is not None:++ try:++ from ._centrality_cache import CentralityCache++++ self._centrality_cache = CentralityCache(centrality_cache_dir)++ except Exception:++ self._centrality_cache = None++ import pathspec++@@ -68,6 +80,16 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd+ self._symbol_pagerank_cache: dict[str, float] | None = None+ self._symbol_betweenness_cache: dict[str, float] | None = None+ self._execution_flow_cache: Any | None = None++ # Filtered-subgraph caches — rebuilt lazily; guarded by a lock because++ # the init pipeline computes metrics concurrently (asyncio.to_thread).++ import threading++++ self._subgraph_lock = threading.Lock()++ self._file_subgraph_cache: nx.DiGraph | None = None++ self._symbol_subgraph_cache: nx.DiGraph | None = None++ # Shared import-name maps (built once per build(), injected into the++ # call + heritage resolvers; reset whenever files change).++ self._import_name_maps: Any | None = None++ def set_tsconfig_resolver(self, resolver: Any) -> None:+ """Attach a :class:`TsconfigResolver` for TS/JS path-alias resolution."""+@@ -86,6 +108,20 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd+ self._symbol_pagerank_cache = None+ self._symbol_betweenness_cache = None+ self._execution_flow_cache = None++ self._file_subgraph_cache = None++ self._symbol_subgraph_cache = None++ self._import_name_maps = None++++ def _invalidate_subgraph_caches(self) -> None:++ """Clear only the filtered-subgraph caches.++++ Called by graph mutations that historically did NOT clear the metric++ caches (co-change edge refresh, framework edges) — those keep their++ existing semantics, but a cached subgraph must never go stale++ structurally.++ """++ self._file_subgraph_cache = None++ self._symbol_subgraph_cache = None++ def release_graph(self) -> None:+ """Drop the in-memory NetworkX object after metrics are materialized.+@@ -102,6 +138,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd+ """+ self._graph = nx.DiGraph()+ self._built = True++ self._invalidate_subgraph_caches() # they hold the old structure — free it++ # ------------------------------------------------------------------+ # Building+diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.py+index 6b08f17d..62b7bbde 100644+--- a/packages/core/src/repowise/core/ingestion/heritage_resolver.py++++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py+@@ -23,6 +23,7 @@ from __future__ import annotations++ from collections import defaultdict+ from dataclasses import dataclass++from typing import Any++ import structlog++@@ -75,6 +76,8 @@ class HeritageResolver:+ self,+ parsed_files: dict[str, ParsedFile],+ import_targets: dict[str, set[str]],++ *,++ import_maps: Any | None = None,+ ) -> None:+ # Per-file class/interface/trait index: {file: {name: symbol_id}}+ self._file_types: dict[str, dict[str, str]] = {}+@@ -85,8 +88,19 @@ class HeritageResolver:+ # Import graph+ self._import_targets = import_targets++- # Import name mapping (reuses resolved_file from Import objects)+- self._import_names: dict[str, dict[str, str]] = defaultdict(dict)++ # Import name mapping — shared with CallResolver (built once per++ # GraphBuilder.build() and injected; standalone construction builds++ # it locally).++ if import_maps is None:++ from .import_index import build_import_name_maps++++ import_maps = build_import_name_maps(parsed_files)++ self._import_names: dict[str, dict[str, str]] = import_maps.import_names++++ # Lazy per-file merged view of imported files' type tables —++ # Tier-2b lookup; sorted-path merge order, first-wins (see++ # CallResolver for rationale).++ self._merged_import_types: dict[str, dict[str, str]] = {}++ # Keep reference for cross-language checks in Tier 3+ self._parsed_files = parsed_files+@@ -105,18 +119,18 @@ class HeritageResolver:++ self._file_types[path] = file_types++- # Build import name mapping using resolved_file+- for imp in parsed.imports:+- if imp.resolved_file is None:++ def _merged_types_for(self, file_path: str) -> dict[str, str]:++ """Merged ``{type_name → symbol_id}`` across every imported file."""++ merged = self._merged_import_types.get(file_path)++ if merged is None:++ merged = {}++ for imported_file in sorted(self._import_targets.get(file_path, ())):++ if imported_file.startswith("external:"):+ continue+- for binding in imp.bindings:+- if binding.local_name != "*":+- self._import_names[path][binding.local_name] = imp.resolved_file+- # Fallback for imports without bindings+- if not imp.bindings:+- for name in imp.imported_names:+- if name != "*":+- self._import_names[path][name] = imp.resolved_file++ for name, sym_id in self._file_types.get(imported_file, {}).items():++ merged.setdefault(name, sym_id)++ self._merged_import_types[file_path] = merged++ return merged++ def resolve_file(+ self, file_path: str, relations: list[HeritageRelation]+@@ -162,19 +176,16 @@ class HeritageResolver:+ line=rel.line,+ )++- # Tier 2b: scan all imported files+- for imported_file in self._import_targets.get(file_path, set()):+- if imported_file.startswith("external:"):+- continue+- imported_types = self._file_types.get(imported_file, {})+- if parent_name in imported_types:+- return ResolvedHeritage(+- child_id=child_id,+- parent_id=imported_types[parent_name],+- edge_type=edge_type,+- confidence=0.85,+- line=rel.line,+- )++ # Tier 2b: all imported files (pre-merged lookup)++ merged_types = self._merged_types_for(file_path)++ if parent_name in merged_types:++ return ResolvedHeritage(++ child_id=child_id,++ parent_id=merged_types[parent_name],++ edge_type=edge_type,++ confidence=0.85,++ line=rel.line,++ )++ # Tier 3: global unique match — only within the same language+ candidates = self._global_types.get(parent_name, [])+diff --git a/packages/core/src/repowise/core/ingestion/import_index.py b/packages/core/src/repowise/core/ingestion/import_index.py+new file mode 100644+index 00000000..89794c69+--- /dev/null++++ b/packages/core/src/repowise/core/ingestion/import_index.py+@@ -0,0 +1,65 @@++"""Shared import-name index construction for the call and heritage resolvers.++++Both resolvers used to derive the same ``{file → {local_name → source_file}}``++mapping independently from every file's imports. Build it once here and++inject it into both (the GraphBuilder does this during ``build()``); the++resolvers keep a backwards-compatible fallback that builds the maps++themselves when none are supplied.++"""++++from __future__ import annotations++++from collections import defaultdict++from dataclasses import dataclass, field++++from .models import NamedBinding, ParsedFile++++++@dataclass(slots=True)++class ImportNameMaps:++ """Per-file import-name lookups shared across resolution passes.++++ ``import_names`` — {file: {local_name: source_file}}++ ``import_bindings`` — {file: {local_name: NamedBinding}} (call resolver only)++ ``module_aliases`` — {file: {alias: source_file}} (call resolver only)++ """++++ import_names: dict[str, dict[str, str]] = field(++ default_factory=lambda: defaultdict(dict)++ )++ import_bindings: dict[str, dict[str, NamedBinding]] = field(++ default_factory=lambda: defaultdict(dict)++ )++ module_aliases: dict[str, dict[str, str]] = field(++ default_factory=lambda: defaultdict(dict)++ )++++++def build_import_name_maps(parsed_files: dict[str, ParsedFile]) -> ImportNameMaps:++ """Build the shared import-name maps from every file's resolved imports.++++ Mirrors the historical ``CallResolver._build_indices`` import loop,++ including the ``binding.source_file`` back-fill side effect that++ downstream barrel-origin chasing relies on.++ """++ maps = ImportNameMaps()++ for path, parsed in parsed_files.items():++ for imp in parsed.imports:++ if imp.resolved_file is None:++ continue++ resolved = imp.resolved_file++ if imp.bindings:++ for binding in imp.bindings:++ if binding.local_name == "*":++ continue++ binding.source_file = resolved++ maps.import_names[path][binding.local_name] = resolved++ maps.import_bindings[path][binding.local_name] = binding++ if binding.is_module_alias:++ maps.module_aliases[path][binding.local_name] = resolved++ else:++ # Fallback for imports without binding data++ for name in imp.imported_names:++ if name != "*":++ maps.import_names[path][name] = resolved++ return maps+diff --git a/packages/core/src/repowise/core/ingestion/parse_cache.py b/packages/core/src/repowise/core/ingestion/parse_cache.py+new file mode 100644+index 00000000..aec7d78f+--- /dev/null++++ b/packages/core/src/repowise/core/ingestion/parse_cache.py+@@ -0,0 +1,160 @@++"""Content-hash keyed cache for ParsedFile results.++++Parsing is the repo-proportional term of every ingest: ``repowise update``++re-parses the whole repo when one file changed, and large-repo inits pay++minutes of tree-sitter time. A ParsedFile is a pure function of the file++*bytes* and the parser itself, so it caches safely keyed by++``(relative path, content hash)`` under a parser fingerprint (the compiled++``.scm`` query sources + the package version) that invalidates the whole++cache when extraction rules change.++++Entries are stored as pickle *bytes* snapshotted at parse time — downstream++graph builds mutate ParsedFile in place (``Import.resolved_file``,++``NamedBinding.source_file`` are back-filled during resolution), so a hit++must deserialize a fresh object graph rather than share one. The path is++part of the key because symbol IDs embed it; a rename is a miss and++re-parses (producing IDs for the new path). On a hit the *current*++traversal ``FileInfo`` is rebound so git hash / mtime stay fresh.++++Best-effort by design: any load/save/deserialize error degrades to a full++parse. The cache file is rewritten with only the entries touched this run,++so deleted files age out naturally.++"""++++from __future__ import annotations++++import contextlib++import hashlib++import os++import pickle++import tempfile++from functools import lru_cache++from pathlib import Path++from typing import Any++++import structlog++++from .models import FileInfo, ParsedFile++++log = structlog.get_logger(__name__)++++_CACHE_VERSION = 1++_CACHE_FILENAME = "parse_cache.pkl"++++__all__ = ["ParseCache", "parser_fingerprint"]++++++@lru_cache(maxsize=1)++def parser_fingerprint() -> str:++ """Fingerprint of everything that determines a ParsedFile besides bytes.++++ Hashes every ``.scm`` query source (extraction rules) plus the package++ version (parser/extractor code changes ship as releases). A mismatch++ invalidates the whole cache — correctness over reuse.++ """++ h = hashlib.sha256()++ h.update(f"cache-version:{_CACHE_VERSION}".encode())++ try:++ from repowise.core import __version__++++ h.update(f"version:{__version__}".encode())++ except Exception:++ h.update(b"version:unknown")++ queries_dir = Path(__file__).parent / "queries"++ try:++ for scm in sorted(queries_dir.glob("*.scm")):++ h.update(scm.name.encode())++ h.update(scm.read_bytes())++ except Exception:++ h.update(b"queries:unreadable")++ return h.hexdigest()++++++class ParseCache:++ """Pickle-backed ``(path, content_hash) -> ParsedFile-bytes`` store."""++++ def __init__(self, cache_dir: Path | str) -> None:++ self._path = Path(cache_dir) / _CACHE_FILENAME++ self._fingerprint = parser_fingerprint()++ self._entries: dict[tuple[str, str], bytes] = {}++ self._fresh: dict[tuple[str, str], bytes] = {}++ self.hits = 0++ self.misses = 0++++ # -- lifecycle ---------------------------------------------------------++++ def load(self) -> None:++ try:++ with self._path.open("rb") as fh:++ payload = pickle.load(fh)++ if (++ payload.get("version") != _CACHE_VERSION++ or payload.get("fingerprint") != self._fingerprint++ ):++ return++ self._entries = payload.get("files", {})++ except FileNotFoundError:++ return++ except Exception as exc: # corrupt / unreadable cache -> full parse++ log.debug("parse_cache_load_failed", error=str(exc))++++ def save(self) -> None:++ """Atomically persist the entries used or created this run."""++ try:++ self._path.parent.mkdir(parents=True, exist_ok=True)++ payload = {++ "version": _CACHE_VERSION,++ "fingerprint": self._fingerprint,++ "files": self._fresh,++ }++ fd, tmp_name = tempfile.mkstemp(++ dir=str(self._path.parent), prefix=_CACHE_FILENAME, suffix=".tmp"++ )++ try:++ with os.fdopen(fd, "wb") as fh:++ pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)++ os.replace(tmp_name, self._path)++ except BaseException:++ with contextlib.suppress(OSError):++ os.unlink(tmp_name)++ raise++ except Exception as exc:++ log.debug("parse_cache_save_failed", error=str(exc))++++ # -- access ------------------------------------------------------------++++ def get(self, file_info: FileInfo, content_hash: str) -> ParsedFile | None:++ """Return a fresh ParsedFile for *content_hash* or None on miss.++++ Hits deserialize a new object graph (downstream resolution mutates++ ParsedFile in place) and rebind the current *file_info* so traversal++ metadata (git hash, mtime) stays current. *content_hash* is++ :func:`compute_content_hash` of the raw bytes — callers compute it++ once and reuse it for the matching :meth:`put`.++ """++ key = (file_info.path, content_hash)++ blob = self._entries.get(key)++ if blob is None:++ self.misses += 1++ return None++ try:++ parsed: Any = pickle.loads(blob)++ except Exception as exc: # corrupt entry -> re-parse this file++ log.debug("parse_cache_entry_corrupt", path=file_info.path, error=str(exc))++ self.misses += 1++ return None++ self.hits += 1++ self._fresh[key] = blob++ parsed.file_info = file_info++ return parsed++++ def put(self, parsed: ParsedFile, content_hash: str) -> None:++ """Snapshot *parsed* (call before any graph build mutates it)."""++ try:++ blob = pickle.dumps(parsed, protocol=pickle.HIGHEST_PROTOCOL)++ except Exception as exc:++ log.debug("parse_cache_put_failed", path=parsed.file_info.path, error=str(exc))++ return++ key = (parsed.file_info.path, content_hash)++ self._entries[key] = blob++ self._fresh[key] = blob+diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py+index c49f403f..d827a4a8 100644+--- a/packages/core/src/repowise/core/ingestion/parser.py++++ b/packages/core/src/repowise/core/ingestion/parser.py+@@ -257,7 +257,13 @@ class ASTParser:+ parse_errors = _collect_error_nodes(root)+ query = self._get_query(lang, language, grammar_tag)++- symbols = self._extract_symbols(tree, query, config, file_info, src)++ # Execute the compiled query ONCE per file. The five extraction++ # passes below all consume the same capture dicts read-only;++ # re-running ``cursor.matches()`` per pass multiplied the most++ # expensive part of parsing by five.++ matches = _run_query(query, root) if query is not None else []++++ symbols = self._extract_symbols(matches, config, file_info, src)+ # Per-language synthetic-symbol pass — recognises source-generator+ # attributes (e.g. CommunityToolkit.Mvvm) and adds the symbols the+ # generator would emit at compile time. No-op for languages+@@ -266,12 +272,12 @@ class ASTParser:+ if synthetic:+ existing_ids = {s.id for s in symbols}+ symbols.extend(s for s in synthetic if s.id not in existing_ids)+- imports = self._extract_imports(tree, query, config, file_info, src)+- calls = self._extract_calls(tree, query, config, file_info, src, symbols)+- heritage = extract_heritage(tree, query, config, file_info, src, run_query=_run_query)++ imports = self._extract_imports(matches, config, file_info, src)++ calls = self._extract_calls(matches, config, file_info, src, symbols)++ heritage = extract_heritage(matches, config, file_info, src)+ exports = self._derive_exports(symbols, config, src)+ docstring = extract_module_docstring(root, src, lang)+- type_refs = self._extract_type_refs(tree, query, src, lang)++ type_refs = self._extract_type_refs(matches, src, lang)++ if len(symbols) > _SYMBOL_COUNT_WARN_THRESHOLD:+ log.warning(+@@ -310,19 +316,15 @@ class ASTParser:++ def _extract_symbols(+ self,+- tree: object,+- query: object,++ matches: list[dict],+ config: LanguageConfig,+ file_info: FileInfo,+ src: str,+ ) -> list[Symbol]:+- if query is None:+- return []+-+ symbols: list[Symbol] = []+ seen: set[tuple[int, str]] = set() # (start_line, name) — dedup decorated dupes++- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]++ for capture_dict in matches:+ def_nodes = capture_dict.get("symbol.def", [])+ name_nodes = capture_dict.get("symbol.name", [])+ params_nodes = capture_dict.get("symbol.params", [])+@@ -502,19 +504,15 @@ class ASTParser:++ def _extract_imports(+ self,+- tree: object,+- query: object,++ matches: list[dict],+ config: LanguageConfig,+ file_info: FileInfo,+ src: str,+ ) -> list[Import]:+- if query is None:+- return []+-+ imports: list[Import] = []+ seen_raws: set[str] = set()++- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]++ for capture_dict in matches:+ stmt_nodes = capture_dict.get("import.statement", [])+ module_nodes = capture_dict.get("import.module", [])++@@ -588,17 +586,13 @@ class ASTParser:++ def _extract_calls(+ self,+- tree: object,+- query: object,++ matches: list[dict],+ config: LanguageConfig,+ file_info: FileInfo,+ src: str,+ symbols: list[Symbol],+ ) -> list[CallSite]:+ """Extract function/method call sites from the AST."""+- if query is None:+- return []+-+ from .language_data import get_builtin_calls++ _call_builtins = get_builtin_calls(file_info.language)+@@ -611,7 +605,7 @@ class ASTParser:+ calls: list[CallSite] = []+ seen: set[tuple[int, str, str | None]] = set()++- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]++ for capture_dict in matches:+ site_nodes = capture_dict.get("call.site", [])+ target_nodes = capture_dict.get("call.target", [])+ arg_nodes = capture_dict.get("call.arguments", [])+@@ -676,8 +670,7 @@ class ASTParser:++ def _extract_type_refs(+ self,+- tree: object,+- query: object,++ matches: list[dict],+ src: str,+ lang: str = "",+ ) -> list[TypeReference]:+@@ -697,15 +690,12 @@ class ASTParser:+ ``field_declaration`` → ``field_type``, ``composite_literal`` →+ ``composite_literal`` (Go).+ """+- if query is None:+- return []+-+ head_of = TYPE_HEAD_EXTRACTORS.get(lang, _head_type_identifier)++ refs: list[TypeReference] = []+ seen: set[tuple[str, int]] = set()++- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]++ for capture_dict in matches:+ type_nodes = capture_dict.get("param.type", [])+ if not type_nodes:+ continue+diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py+index 594db4d2..657e1ed8 100644+--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py++++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py+@@ -25,6 +25,7 @@ flattened to the first plausible source target. Packages without an+ from __future__ import annotations++ import json++import os+ from dataclasses import dataclass, field+ from pathlib import Path+ from typing import TYPE_CHECKING, Any+@@ -33,6 +34,81 @@ if TYPE_CHECKING:+ from .context import ResolverContext++++# ---------------------------------------------------------------------------++# Single pruned filesystem scan++# ---------------------------------------------------------------------------++# The mdx / vitest-config / package.json finders below all need to locate++# files by name across the repo. Doing that with per-finder ``rglob`` calls++# walked the ENTIRE tree (including node_modules, virtualenvs, .git) once++# per pattern — 12+ full walks, measured at ~6 min on a medium repo with a++# checked-in .venv. One ``os.walk`` with directory pruning, memoized on the++# resolver context, replaces all of them.++#++# The prune list is deliberately narrow: vendored/derived trees that can++# never contain *our* manifests or docs. ``.github`` and other dot-dirs that++# may hold real package.json files (custom actions) are NOT pruned wholesale.++_SCAN_PRUNE_DIRS: frozenset[str] = frozenset({++ "node_modules",++ ".git",++ ".hg",++ ".svn",++ ".venv",++ "venv",++ ".tox",++ "__pycache__",++ ".repowise",++ ".repowise.prebench-bak",++ ".next",++ ".nuxt",++ ".turbo",++ ".cache",++ ".parcel-cache",++ ".yarn",++ ".pnpm-store",++})++++_VITEST_CONFIG_NAMES: frozenset[str] = frozenset({++ "vitest.config.ts", "vitest.config.js", "vitest.config.mts",++ "vitest.config.mjs", "vitest.config.cjs", "vitest.config.cts",++ "vite.config.ts", "vite.config.js", "vite.config.mts",++ "vite.config.mjs",++})++++++@dataclass++class _RepoFileScan:++ """File locations gathered by the single pruned walk."""++++ mdx_files: list[Path] = field(default_factory=list)++ vitest_configs: list[Path] = field(default_factory=list)++ package_jsons: list[Path] = field(default_factory=list)++++++def _scan_repo_files(repo_path: Path) -> _RepoFileScan:++ """One pruned ``os.walk`` collecting every finder's target files."""++ scan = _RepoFileScan()++ for dirpath, dirnames, filenames in os.walk(repo_path):++ dirnames[:] = [d for d in dirnames if d not in _SCAN_PRUNE_DIRS]++ for fname in filenames:++ if fname.endswith(".mdx"):++ scan.mdx_files.append(Path(dirpath) / fname)++ elif fname in _VITEST_CONFIG_NAMES:++ scan.vitest_configs.append(Path(dirpath) / fname)++ elif fname == "package.json":++ scan.package_jsons.append(Path(dirpath) / fname)++ return scan++++++def _get_repo_scan(ctx: "ResolverContext") -> _RepoFileScan:++ """Memoized accessor — one walk per resolver context."""++ cached = getattr(ctx, "_ts_repo_file_scan", None)++ if cached is not None:++ return cached++ scan = _scan_repo_files(ctx.repo_path) if ctx.repo_path is not None else _RepoFileScan()++ ctx._ts_repo_file_scan = scan # type: ignore[attr-defined]++ return scan+++++ # Order in which we collapse Node "conditional exports" objects down to+ # a single target. Source-pointing conditions come first so a TS-aware+ # static analyser sees the original ``.ts`` file rather than a built+@@ -453,7 +529,7 @@ def find_mdx_import_targets(ctx: "ResolverContext") -> set[str]:+ from .typescript import resolve_ts_js_import++ targets: set[str] = set()+- for mdx in ctx.repo_path.rglob("*.mdx"):++ for mdx in _get_repo_scan(ctx).mdx_files:+ try:+ text = mdx.read_text(encoding="utf-8", errors="ignore")+ except Exception:+@@ -537,34 +613,25 @@ def find_vitest_include_targets(ctx: "ResolverContext") -> set[str]:+ return set()++ targets: set[str] = set()+- config_globs = ("vitest.config.ts", "vitest.config.js", "vitest.config.mts",+- "vitest.config.mjs", "vitest.config.cjs", "vitest.config.cts",+- "vite.config.ts", "vite.config.js", "vite.config.mts",+- "vite.config.mjs")+- seen: set[Path] = set()+- for pattern in config_globs:+- for cfg in ctx.repo_path.rglob(pattern):+- if cfg in seen:+- continue+- seen.add(cfg)+- try:+- text = cfg.read_text(encoding="utf-8", errors="ignore")+- except Exception:+- continue+- cfg_dir = cfg.parent+- for inc_match in _VITEST_INCLUDE_RE.finditer(text):+- for str_match in _VITEST_STRING_RE.finditer(inc_match.group(1)):+- glob_pat = str_match.group(1)+- # Resolve glob relative to the config file's directory.+- base = (cfg_dir / glob_pat).as_posix()+- try:+- rel_glob = Path(base).relative_to(ctx.repo_path).as_posix()+- except ValueError:+- continue+- regex = _vitest_glob_to_regex(rel_glob)+- for candidate in ctx.path_set:+- if regex.match(candidate):+- targets.add(candidate)++ for cfg in _get_repo_scan(ctx).vitest_configs:++ try:++ text = cfg.read_text(encoding="utf-8", errors="ignore")++ except Exception:++ continue++ cfg_dir = cfg.parent++ for inc_match in _VITEST_INCLUDE_RE.finditer(text):++ for str_match in _VITEST_STRING_RE.finditer(inc_match.group(1)):++ glob_pat = str_match.group(1)++ # Resolve glob relative to the config file's directory.++ base = (cfg_dir / glob_pat).as_posix()++ try:++ rel_glob = Path(base).relative_to(ctx.repo_path).as_posix()++ except ValueError:++ continue++ regex = _vitest_glob_to_regex(rel_glob)++ for candidate in ctx.path_set:++ if regex.match(candidate):++ targets.add(candidate)+ return targets+++@@ -640,7 +707,10 @@ def find_npm_script_entry_targets(ctx: "ResolverContext") -> set[str]:+ if ctx.repo_path is None:+ return set()++- repo_root = ctx.repo_path.resolve()++ # NOTE: not .resolve()d — the shared scan walks ctx.repo_path as given,++ # so relative_to() below must use the same base or it silently drops++ # every manifest.++ repo_root = ctx.repo_path+ path_set = ctx.path_set+ targets: set[str] = set()++@@ -656,10 +726,8 @@ def find_npm_script_entry_targets(ctx: "ResolverContext") -> set[str]:+ dirs_in_repo.setdefault(p[:slash], []).append(p)+ idx = slash + 1++- for pkg_file in repo_root.rglob("package.json"):+- # Skip node_modules — those are dependency manifests, not ours.+- if "node_modules" in pkg_file.parts:+- continue++ for pkg_file in _get_repo_scan(ctx).package_jsons:++ # node_modules manifests are already pruned by the shared scan.+ try:+ data = json.loads(pkg_file.read_text(encoding="utf-8", errors="ignore"))+ except Exception:+diff --git a/packages/core/src/repowise/core/persistence/crud/_shared.py b/packages/core/src/repowise/core/persistence/crud/_shared.py+index 617afcfe..0e291191 100644+--- a/packages/core/src/repowise/core/persistence/crud/_shared.py++++ b/packages/core/src/repowise/core/persistence/crud/_shared.py+@@ -1,8 +1,9 @@+ """Shared internals for the ``crud`` package.++ Holds the datetime parser, batch-size constant, the job-status whitelist, and+-the generic SELECT-then-INSERT/UPDATE loop (:func:`_batch_upsert`) that the+-per-domain batch upserts delegate to. Private to the package.++the generic keyed SELECT-once-then-INSERT/UPDATE loop++(:func:`_batch_upsert_keyed`) that the per-domain batch upserts delegate to.++Private to the package.+ """++ from __future__ import annotations+@@ -28,39 +29,53 @@ def _parse_dt(ts: str) -> datetime:+ return dt+++-async def _batch_upsert(++async def _batch_upsert_keyed(+ session: AsyncSession,+ model: type[Any],+ items: Iterable[Any],+ *,+- key_fn: Callable[[Any], tuple[Any, ...]],++ prefilter: tuple[Any, ...],++ item_key_fn: Callable[[Any], Any],++ row_key_fn: Callable[[Any], Any],+ update_fn: Callable[[Any, Any], None],+ insert_fn: Callable[[Any], Any],+ batch_size: int | None = None,+ ) -> None:+- """Generic SELECT-then-INSERT/UPDATE loop shared by the batch upserts.++ """Generic batch upsert with ONE existence query for the whole batch.++- For each item, look up the existing row with the filter expressions from+- ``key_fn(item)``; if found, mutate it via ``update_fn(existing, item)``,+- otherwise ``session.add(insert_fn(item))``.++ The previous generic loop issued a SELECT round-trip per item; on bulk writes++ (graph nodes/edges, symbols, git metadata) that is 10k-30k SELECTs per++ persist and dominated the whole persist step (measured: 9.3s for a++ 13k-node ``persist_graph_nodes``). Here all candidate rows matching++ *prefilter* (typically ``repository_id == X``) are fetched once and++ matched in memory: ``item_key_fn(item)`` must equal ``row_key_fn(row)``++ exactly when the legacy ``key_fn`` filter would have found that row.++- Flushes once after the whole sequence, or once per ``batch_size`` chunk when+- *batch_size* is given (matching the SELECT-then-write semantics the callers+- relied on before this was extracted — including no flush at all on an empty+- batched sequence).++ Within-batch duplicate keys keep the legacy outcome: the first item++ inserts, later ones update the pending object (the per-item SELECT used++ to see the autoflushed insert).+ """++ materialized = list(items)++ if not materialized:++ if batch_size is None:++ await session.flush()++ return++++ existing_rows = (await session.execute(select(model).where(*prefilter))).scalars().all()++ by_key: dict[Any, Any] = {row_key_fn(row): row for row in existing_rows}+++ if batch_size is None:+- chunks: list[list[Any]] = [list(items)]++ chunks: list[list[Any]] = [materialized]+ else:+- materialized = list(items)+ chunks = [materialized[i : i + batch_size] for i in range(0, len(materialized), batch_size)]+ for chunk in chunks:+ for item in chunk:+- existing = (+- await session.execute(select(model).where(*key_fn(item)))+- ).scalar_one_or_none()++ key = item_key_fn(item)++ existing = by_key.get(key)+ if existing is not None:+ update_fn(existing, item)+ else:+- session.add(insert_fn(item))++ obj = insert_fn(item)++ session.add(obj)++ by_key[key] = obj+ await session.flush()+diff --git a/packages/core/src/repowise/core/persistence/crud/external_systems.py b/packages/core/src/repowise/core/persistence/crud/external_systems.py+index 97107fda..5766e39e 100644+--- a/packages/core/src/repowise/core/persistence/crud/external_systems.py++++ b/packages/core/src/repowise/core/persistence/crud/external_systems.py+@@ -18,7 +18,7 @@ from ..models import (+ _new_uuid,+ _now_utc,+ )+-from ._shared import _batch_upsert++from ._shared import _batch_upsert_keyed++ # ---------------------------------------------------------------------------+ # ExternalSystem CRUD+@@ -153,14 +153,13 @@ async def batch_upsert_symbols(++ Accepts ingestion.models.Symbol dataclass instances (duck-typed).+ """+- await _batch_upsert(++ await _batch_upsert_keyed(+ session,+ WikiSymbol,+ symbols,+- key_fn=lambda sym: (+- WikiSymbol.repository_id == repository_id,+- WikiSymbol.symbol_id == _symbol_id(sym),+- ),++ prefilter=(WikiSymbol.repository_id == repository_id,),++ item_key_fn=_symbol_id,++ row_key_fn=lambda row: row.symbol_id,+ update_fn=_update_wiki_symbol,+ insert_fn=lambda sym: WikiSymbol(+ id=_new_uuid(),+diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py+index dc2ef020..04877177 100644+--- a/packages/core/src/repowise/core/persistence/crud/git.py++++ b/packages/core/src/repowise/core/persistence/crud/git.py+@@ -16,7 +16,7 @@ from ..models import (+ _new_uuid,+ _now_utc,+ )+-from ._shared import _BATCH_SIZE, _batch_upsert++from ._shared import _BATCH_SIZE, _batch_upsert_keyed++ # ---------------------------------------------------------------------------+ # GitMetadata CRUD+@@ -106,14 +106,13 @@ async def upsert_git_metadata_bulk(+ metadata_list: list[dict],+ ) -> None:+ """Bulk upsert git metadata rows in batches."""+- await _batch_upsert(++ await _batch_upsert_keyed(+ session,+ GitMetadata,+ metadata_list,+- key_fn=lambda meta: (+- GitMetadata.repository_id == repository_id,+- GitMetadata.file_path == meta.get("file_path", ""),+- ),++ prefilter=(GitMetadata.repository_id == repository_id,),++ item_key_fn=lambda meta: meta.get("file_path", ""),++ row_key_fn=lambda row: row.file_path,+ update_fn=_update_git_metadata,+ insert_fn=lambda meta: GitMetadata(+ id=_new_uuid(),+@@ -219,14 +218,13 @@ async def upsert_git_commits_bulk(+ commit_rows: list[dict],+ ) -> None:+ """Bulk upsert per-commit rows (keyed on ``repository_id`` + ``sha``)."""+- await _batch_upsert(++ await _batch_upsert_keyed(+ session,+ GitCommit,+ commit_rows,+- key_fn=lambda row: (+- GitCommit.repository_id == repository_id,+- GitCommit.sha == row.get("sha", ""),+- ),++ prefilter=(GitCommit.repository_id == repository_id,),++ item_key_fn=lambda row: row.get("sha", ""),++ row_key_fn=lambda row: row.sha,+ update_fn=_update_git_commit,+ insert_fn=lambda row: GitCommit(+ id=_new_uuid(),+@@ -338,14 +336,13 @@ async def upsert_git_function_blame_bulk(+ rows: list[dict],+ ) -> None:+ """Bulk upsert per-function blame rows (keyed ``repository_id`` + ``symbol_id``)."""+- await _batch_upsert(++ await _batch_upsert_keyed(+ session,+ GitFunctionBlame,+ rows,+- key_fn=lambda row: (+- GitFunctionBlame.repository_id == repository_id,+- GitFunctionBlame.symbol_id == row.get("symbol_id", ""),+- ),++ prefilter=(GitFunctionBlame.repository_id == repository_id,),++ item_key_fn=lambda row: row.get("symbol_id", ""),++ row_key_fn=lambda row: row.symbol_id,+ update_fn=_update_git_function_blame,+ insert_fn=lambda row: GitFunctionBlame(+ id=_new_uuid(),+diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py+index 977d429a..3ded527e 100644+--- a/packages/core/src/repowise/core/persistence/crud/graph.py++++ b/packages/core/src/repowise/core/persistence/crud/graph.py+@@ -17,7 +17,7 @@ from ..models import (+ GraphNode,+ _new_uuid,+ )+-from ._shared import _BATCH_SIZE, _batch_upsert++from ._shared import _BATCH_SIZE, _batch_upsert_keyed++ # ---------------------------------------------------------------------------+ # Graph CRUD (batch)+@@ -59,14 +59,13 @@ async def batch_upsert_graph_nodes(++ Uses SELECT-then-INSERT/UPDATE for dialect portability.+ """+- await _batch_upsert(++ await _batch_upsert_keyed(+ session,+ GraphNode,+ nodes,+- key_fn=lambda n: (+- GraphNode.repository_id == repository_id,+- GraphNode.node_id == n.get("node_id", ""),+- ),++ prefilter=(GraphNode.repository_id == repository_id,),++ item_key_fn=lambda n: n.get("node_id", ""),++ row_key_fn=lambda row: row.node_id,+ update_fn=_update_graph_node,+ insert_fn=lambda n: GraphNode(+ id=_new_uuid(),+@@ -89,16 +88,17 @@ async def batch_upsert_graph_edges(+ The unique constraint is (repository_id, source, target, edge_type),+ allowing multiple edge types between the same pair of nodes.+ """+- await _batch_upsert(++ await _batch_upsert_keyed(+ session,+ GraphEdge,+ edges,+- key_fn=lambda e: (+- GraphEdge.repository_id == repository_id,+- GraphEdge.source_node_id == e.get("source_node_id", ""),+- GraphEdge.target_node_id == e.get("target_node_id", ""),+- GraphEdge.edge_type == e.get("edge_type", "imports"),++ prefilter=(GraphEdge.repository_id == repository_id,),++ item_key_fn=lambda e: (++ e.get("source_node_id", ""),++ e.get("target_node_id", ""),++ e.get("edge_type", "imports"),+ ),++ row_key_fn=lambda row: (row.source_node_id, row.target_node_id, row.edge_type),+ update_fn=_update_graph_edge,+ insert_fn=lambda e: GraphEdge(+ id=_new_uuid(),+@@ -125,14 +125,13 @@ async def batch_upsert_graph_metrics(+ ``GraphBuilder.load_metrics_from_sql`` on large repos. SELECT-then-write+ for dialect portability (SQLite + Postgres).+ """+- await _batch_upsert(++ await _batch_upsert_keyed(+ session,+ GraphMetric,+ list(metrics.items()),+- key_fn=lambda kv: (+- GraphMetric.repository_id == repository_id,+- GraphMetric.node_id == kv[0],+- ),++ prefilter=(GraphMetric.repository_id == repository_id,),++ item_key_fn=lambda kv: kv[0],++ row_key_fn=lambda row: row.node_id,+ update_fn=lambda existing, kv: _update_graph_metric(existing, kv[1]),+ insert_fn=lambda kv: GraphMetric(+ id=_new_uuid(),+diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py+index 69edaece..82dc0190 100644+--- a/packages/core/src/repowise/core/persistence/models.py++++ b/packages/core/src/repowise/core/persistence/models.py+@@ -403,6 +403,16 @@ class GitMetadata(Base):+ change_entropy: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ change_entropy_pct: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+++ # Agent-provenance rollup: how much of this file's indexed history is++ # agent-attributed (deterministic local-channel classification — identity++ # fields, message footers, co-author trailers; see++ # ingestion.git_indexer.agent_provenance). agent_tier_counts_json maps++ # autonomy tier ("1" near-autonomous / "2" human-driven / "3" assisted)++ # to commit counts. agent_authored_pct stays NULL until the next reindex.++ agent_commit_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)++ agent_authored_pct: Mapped[float | None] = mapped_column(Float, nullable=True)++ agent_tier_counts_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+@@ -463,6 +473,16 @@ class GitCommit(Base):+ change_risk_score: Mapped[float | None] = mapped_column(Float, nullable=True)+ change_risk_level: Mapped[str | None] = mapped_column(String(16), nullable=True)+++ # Agent provenance: which coding agent (if any) authored this commit, at++ # what autonomy tier (1 near-autonomous bot account · 2 human-driven agent++ # · 3 assisted/co-authored), via which attribution channel, and with what++ # confidence band. NULL throughout = human-authored (or pre-migration rows;++ # back-populated on the next index). Deterministic local-git channels only.++ agent_name: Mapped[str | None] = mapped_column(String(32), nullable=True)++ agent_autonomy_tier: Mapped[int | None] = mapped_column(Integer, nullable=True)++ agent_channel: Mapped[str | None] = mapped_column(String(32), nullable=True)++ agent_confidence: Mapped[str | None] = mapped_column(String(8), nullable=True)+++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+diff --git a/packages/core/src/repowise/core/persistence/vector_store/_base.py b/packages/core/src/repowise/core/persistence/vector_store/_base.py+index 95507eb2..e5d1d970 100644+--- a/packages/core/src/repowise/core/persistence/vector_store/_base.py++++ b/packages/core/src/repowise/core/persistence/vector_store/_base.py+@@ -52,6 +52,28 @@ class VectorStore(ABC):+ """Embed *query* and return the *limit* nearest pages."""+ ...+++ async def search_many(++ self, queries: list[str], limit: int = 10++ ) -> list[list[SearchResult]]:++ """Batch variant of :meth:`search` — one result list per query, aligned++ by index.++++ The default implementation fires the per-query searches concurrently++ via ``asyncio.gather``; a failed query yields an empty list (matching++ the caller-side behaviour of swallowing a single failed search).++ Backends override this to embed *all* queries in a single embedder++ call — the network round-trip dominates each search, so batching the++ embedding turns N round-trips into 1.++ """++ import asyncio as _asyncio++++ if not queries:++ return []++ results = await _asyncio.gather(++ *(self.search(q, limit=limit) for q in queries), return_exceptions=True++ )++ return [r if isinstance(r, list) else [] for r in results]+++ @abstractmethod+ async def delete(self, page_id: str) -> None:+ """Remove the vector for *page_id* from the store."""+diff --git a/packages/core/src/repowise/core/persistence/vector_store/in_memory.py b/packages/core/src/repowise/core/persistence/vector_store/in_memory.py+index b97e0463..02188d18 100644+--- a/packages/core/src/repowise/core/persistence/vector_store/in_memory.py++++ b/packages/core/src/repowise/core/persistence/vector_store/in_memory.py+@@ -34,12 +34,7 @@ class InMemoryVectorStore(VectorStore):+ for (page_id, _text, metadata), vector in zip(items, vectors, strict=True):+ self._store[page_id] = (vector, dict(metadata))++- async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+- if not self._store:+- return []+- q_vecs = await self._embedder.embed([query])+- q_vec = q_vecs[0]+-++ def _search_by_vector(self, q_vec: list[float], limit: int) -> list[SearchResult]:+ scored: list[tuple[float, str, dict]] = []+ for pid, (vec, meta) in self._store.items():+ score = cosine_similarity(q_vec, vec)+@@ -63,6 +58,23 @@ class InMemoryVectorStore(VectorStore):+ )+ return results+++ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:++ if not self._store:++ return []++ q_vecs = await self._embedder.embed([query])++ return self._search_by_vector(q_vecs[0], limit)++++ async def search_many(++ self, queries: list[str], limit: int = 10++ ) -> list[list[SearchResult]]:++ """One embedder call for all queries, then local scoring per query."""++ if not queries:++ return []++ if not self._store:++ return [[] for _ in queries]++ q_vecs = await self._embedder.embed(list(queries))++ return [self._search_by_vector(q_vec, limit) for q_vec in q_vecs]+++ async def delete(self, page_id: str) -> None:+ self._store.pop(page_id, None)++diff --git a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py+index 84f1f415..4d521c1b 100644+--- a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py++++ b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py+@@ -10,6 +10,17 @@ from ._base import VectorStore+ __all__ = ["LanceDBVectorStore"]++++def _paths_in_filter(paths: list[str]) -> str:++ """Build an SQL-injection-safe ``target_path IN (...)`` LanceDB filter.++++ LanceDB's ``.where()`` takes a DataFusion SQL string with no bind++ parameters, so each path is quoted with the same quote-doubling escape++ the single-path lookup uses.++ """++ quoted = ", ".join("'" + p.replace("'", "''") + "'" for p in paths)++ return f"target_path IN ({quoted})"+++++ class LanceDBVectorStore(VectorStore):+ """Vector store backed by LanceDB (embedded, local file storage).++@@ -154,14 +165,7 @@ class LanceDBVectorStore(VectorStore):+ ]+ await self._upsert_rows(rows)++- async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+- await self._ensure_connected()+- if self._table is None:+- return []+-+- q_vecs = await self._embedder.embed([query])+- q_vec = [float(v) for v in q_vecs[0]]+-++ async def _search_by_vector(self, q_vec: list[float], limit: int) -> list[SearchResult]:+ # Query with explicit cosine distance so ``_distance`` is a cosine+ # distance (1 - cos); we return ``1 - _distance`` = cosine similarity.+ # This makes the score semantics match the other backends+@@ -185,6 +189,32 @@ class LanceDBVectorStore(VectorStore):+ for r in raw+ ]+++ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:++ await self._ensure_connected()++ if self._table is None:++ return []++++ q_vecs = await self._embedder.embed([query])++ return await self._search_by_vector([float(v) for v in q_vecs[0]], limit)++++ async def search_many(++ self, queries: list[str], limit: int = 10++ ) -> list[list[SearchResult]]:++ """One embedder call for all queries; the vector lookups are local."""++ if not queries:++ return []++ await self._ensure_connected()++ if self._table is None:++ return [[] for _ in queries]++ q_vecs = await self._embedder.embed(list(queries))++ out: list[list[SearchResult]] = []++ for q_vec in q_vecs:++ try:++ out.append(await self._search_by_vector([float(v) for v in q_vec], limit))++ except Exception:++ out.append([])++ return out+++ async def delete(self, page_id: str) -> None:+ await self._ensure_connected()+ if self._table is not None:+@@ -230,3 +260,35 @@ class LanceDBVectorStore(VectorStore):++ summary = rows[0].get("content_snippet") or ""+ return {"summary": str(summary), "key_exports": []}++++ async def get_page_summaries_by_paths(self, paths: list[str]) -> dict[str, dict]:++ """One ``IN``-filtered scan instead of one filtered query per path.++++ Mirrors the single-path semantics (first row per path wins, empty++ summaries dropped, ``key_exports`` not stored in this schema).++ """++ if not paths:++ return {}++ await self._ensure_connected()++ if self._table is None:++ return {}++++ try:++ rows = (++ await self._table.query() # type: ignore[union-attr]++ .where(_paths_in_filter(paths))++ .select(["target_path", "content_snippet"])++ .to_list()++ )++ except Exception:++ return {}++++ out: dict[str, dict] = {}++ for r in rows:++ tp = str(r.get("target_path") or "")++ if not tp or tp in out:++ continue++ summary = r.get("content_snippet") or ""++ if summary:++ out[tp] = {"summary": str(summary), "key_exports": []}++ return out+diff --git a/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py b/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py+index 4a5f7f40..8c441ed3 100644+--- a/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py++++ b/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py+@@ -20,6 +20,23 @@ def _encode(vector: list[float]) -> str:+ return "[" + ",".join(str(v) for v in vector) + "]"++++def _summary_payload(content: object, metadata: object) -> dict:++ """Build the ``{'summary', 'key_exports'}`` payload from a wiki_pages row."""++ key_exports: list[str] = []++ if metadata and isinstance(metadata, dict):++ key_exports = list(metadata.get("exports", []))++ elif metadata and isinstance(metadata, str):++ import json++++ try:++ meta = json.loads(metadata)++ key_exports = list(meta.get("exports", []))++ except (json.JSONDecodeError, AttributeError):++ pass++++ return {"summary": str(content or "")[:500], "key_exports": key_exports}+++++ class PgVectorStore(VectorStore):+ """Vector store that writes embeddings to the ``wiki_pages.embedding`` column.++@@ -71,8 +88,9 @@ class PgVectorStore(VectorStore):+ "UPDATE wiki_pages SET embedding = CAST(:emb AS vector) WHERE id = :pid"+ )+ async with self._session_factory() as session:+- for p in params:+- await session.execute(stmt, p)++ # executemany: one driver round-trip batch instead of one UPDATE++ # round-trip per row.++ await session.execute(stmt, params)+ await session.commit()++ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:+@@ -108,6 +126,51 @@ class PgVectorStore(VectorStore):+ for r in raw+ ]+++ async def search_many(++ self, queries: list[str], limit: int = 10++ ) -> list[list[SearchResult]]:++ """One embedder call for all queries; per-query SELECTs share a session."""++ if not queries:++ return []++ q_vecs = await self._embedder.embed(list(queries))++++ from sqlalchemy.sql import text as sa_text++++ stmt = sa_text(++ "SELECT id, title, content, page_type, target_path, "++ " 1 - (embedding <=> CAST(:q AS vector)) AS score "++ "FROM wiki_pages "++ "WHERE embedding IS NOT NULL "++ "ORDER BY embedding <=> CAST(:q AS vector) "++ "LIMIT :lim"++ )++ out: list[list[SearchResult]] = []++ async with self._session_factory() as session:++ for q_vec in q_vecs:++ try:++ rows = await session.execute(++ stmt, {"q": _encode(q_vec), "lim": limit}++ )++ raw = rows.fetchall()++ except Exception:++ out.append([])++ continue++ out.append(++ [++ SearchResult(++ page_id=r[0],++ title=r[1],++ page_type=r[3],++ target_path=r[4],++ score=float(r[5]),++ snippet=str(r[2])[:200].rstrip(),++ search_type="vector",++ )++ for r in raw++ ]++ )++ return out+++ async def delete(self, page_id: str) -> None:+ from sqlalchemy.sql import text as sa_text++@@ -153,17 +216,36 @@ class PgVectorStore(VectorStore):+ if row is None:+ return None++- content = str(row[0] or "")[:500]+- key_exports: list[str] = []+- if row[1] and isinstance(row[1], dict):+- key_exports = list(row[1].get("exports", []))+- elif row[1] and isinstance(row[1], str):+- import json++ return _summary_payload(row[0], row[1])++++ async def get_page_summaries_by_paths(self, paths: list[str]) -> dict[str, dict]:++ """One ``IN``-filtered SELECT instead of one query per path.++++ Like the single-path variant (``LIMIT 1`` with no ``ORDER BY``), when++ several pages share a ``target_path`` an arbitrary one wins — here the++ first row returned per path.++ """++ if not paths:++ return {}++++ from sqlalchemy import bindparam++ from sqlalchemy.sql import text as sa_text++++ stmt = sa_text(++ "SELECT target_path, content, metadata FROM wiki_pages "++ "WHERE target_path IN :paths"++ ).bindparams(bindparam("paths", expanding=True))++- try:+- meta = json.loads(row[1])+- key_exports = list(meta.get("exports", []))+- except (json.JSONDecodeError, AttributeError):+- pass++ async with self._session_factory() as session:++ rows = await session.execute(stmt, {"paths": list(paths)})++ raw = rows.fetchall()++- return {"summary": content, "key_exports": key_exports}++ out: dict[str, dict] = {}++ for r in raw:++ tp = str(r[0])++ if tp in out:++ continue++ payload = _summary_payload(r[1], r[2])++ if payload.get("summary"):++ out[tp] = payload++ return out+diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py+index 454dac6b..fc71d80d 100644+--- a/packages/core/src/repowise/core/pipeline/persist.py++++ b/packages/core/src/repowise/core/pipeline/persist.py+@@ -108,6 +108,114 @@ async def persist_graph_nodes(+ logger.warning("graph_metrics_materialize_skipped", error=str(exc))++++# Chunk size for IN (...) deletes — stays under SQLite's host-parameter limit.++_PRUNE_CHUNK = 500++++++async def _prune_stale_file_rows(++ session: Any,++ repo_id: str,++ current_graph_file_paths: set[str],++ current_git_file_paths: set[str],++) -> None:++ """Delete file-scoped rows for files absent from the latest full pipeline run.++++ The parser and git indexer disagree on the file set — a file can be++ git-tracked yet absent from ``parsed_files`` (parse failure, unparsed++ extension, skipped) — so the tables use different sources of truth.++ *current_graph_file_paths* (from ``parsed_files``) governs graph/analysis++ tables; *current_git_file_paths* (from ``git_metadata_list``) governs++ ``git_metadata`` only. Each set independently no-ops when empty to avoid++ wiping rows on a broken run. FULL persistence only — not incremental paths.++ """++ from sqlalchemy import delete, or_, select++++ from repowise.core.persistence.models import (++ DeadCodeFinding,++ GitMetadata,++ GraphEdge,++ GraphMetric,++ GraphNode,++ HealthFileMetric,++ HealthFinding,++ SecurityFinding,++ WikiSymbol,++ )++++ async def _delete_stale_by_paths(model: Any, column: Any, current: set[str]) -> None:++ # Diff persisted paths against *current* in Python so the IN (...) is++ # bounded by the stale set, not the whole repo (SQLite param limit).++ if not current:++ return++ existing = set(++ (await session.execute(select(column).where(model.repository_id == repo_id).distinct()))++ .scalars()++ .all()++ )++ stale = [p for p in existing if p not in current]++ for i in range(0, len(stale), _PRUNE_CHUNK):++ await session.execute(++ delete(model).where(++ model.repository_id == repo_id,++ column.in_(stale[i : i + _PRUNE_CHUNK]),++ )++ )++++ # ---- Graph nodes + edges -------------------------------------------------++ # File nodes key on node_id; symbol nodes on file_path. Delete edges before++ # nodes (no FK cascade between the tables).++ if current_graph_file_paths:++ node_rows = (++ await session.execute(++ select(GraphNode.node_id, GraphNode.node_type, GraphNode.file_path).where(++ GraphNode.repository_id == repo_id++ )++ )++ ).all()++ stale_node_ids = [++ node_id++ for node_id, node_type, file_path in node_rows++ if (node_type == "file" and node_id not in current_graph_file_paths)++ or (++ node_type != "file"++ and file_path is not None++ and file_path not in current_graph_file_paths++ )++ ]++ for i in range(0, len(stale_node_ids), _PRUNE_CHUNK):++ batch = stale_node_ids[i : i + _PRUNE_CHUNK]++ await session.execute(++ delete(GraphEdge).where(++ GraphEdge.repository_id == repo_id,++ or_(++ GraphEdge.source_node_id.in_(batch),++ GraphEdge.target_node_id.in_(batch),++ ),++ )++ )++ await session.execute(++ delete(GraphNode).where(++ GraphNode.repository_id == repo_id,++ GraphNode.node_id.in_(batch),++ )++ )++++ # GraphMetric is file-level only (node_id == path).++ await _delete_stale_by_paths(GraphMetric, GraphMetric.node_id, current_graph_file_paths)++ await _delete_stale_by_paths(WikiSymbol, WikiSymbol.file_path, current_graph_file_paths)++ await _delete_stale_by_paths(++ SecurityFinding, SecurityFinding.file_path, current_graph_file_paths++ )++ await _delete_stale_by_paths(++ DeadCodeFinding, DeadCodeFinding.file_path, current_graph_file_paths++ )++ await _delete_stale_by_paths(++ HealthFileMetric, HealthFileMetric.file_path, current_graph_file_paths++ )++ await _delete_stale_by_paths(HealthFinding, HealthFinding.file_path, current_graph_file_paths)++ await _delete_stale_by_paths(GitMetadata, GitMetadata.file_path, current_git_file_paths)+++++ async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:+ """Persist ingestion-phase outputs: graph nodes/edges, external systems,+ symbols, and the per-file security scan.+@@ -412,6 +520,18 @@ async def persist_pipeline_result(+ This function mutates ``sym.file_path`` on parsed-file symbols that+ lack one. Callers should treat *result* as consumed after this call.+ """++ # Prune rows for files absent from this full result before the phase++ # persisters re-upsert. graph/analysis tables key off parsed_files;++ # git_metadata keys off the git indexer's set (a file can be git-tracked++ # but unparsed). Runs only here, never in the reusable phase persisters.++ current_graph_file_paths = {pf.file_info.path for pf in result.parsed_files}++ current_git_file_paths = {++ (gm if isinstance(gm, dict) else dataclasses.asdict(gm)).get("file_path", "")++ for gm in result.git_metadata_list++ }++ current_git_file_paths.discard("")++ await _prune_stale_file_rows(session, repo_id, current_graph_file_paths, current_git_file_paths)+++ symbol_count = await persist_ingestion(result, session, repo_id)+ await persist_git(result, session, repo_id)+ await persist_analysis(result, session, repo_id)+diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py+index 8a099766..5e07fcaa 100644+--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py++++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py+@@ -106,6 +106,7 @@ async def _run_health_analysis(+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ module_map=module_map,++ duplication_cache_dir=(repo_path / ".repowise") if repo_path is not None else None,+ )++ # Load per-file override rules from `.repowise/health-rules.json`.+diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.py+index 693acf59..525a5a36 100644+--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py++++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py+@@ -7,6 +7,7 @@ orchestrator.py) imports these phase functions. No CLI/click/rich imports.+ from __future__ import annotations++ import asyncio++import contextlib+ import os+ import time+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor+@@ -85,6 +86,85 @@ def _parse_one(path_and_fi_and_bytes: tuple) -> Any:+ return (fi.abs_path, str(exc))++++def _split_cached(++ repo_path: Path,++ fi_and_bytes: list[tuple],++ progress: ProgressCallback | None,++) -> tuple[Any, dict[int, Any], list[tuple[int, tuple, str]]]:++ """Partition pre-read files into parse-cache hits and misses.++++ Returns ``(cache, hits, misses)`` where *hits* maps the position in++ *fi_and_bytes* to a cached ParsedFile and *misses* keeps ``(position,++ (FileInfo, bytes), content_hash)`` triples that still need a real parse++ (the hash rides along so the post-parse ``put`` doesn't re-digest).++ Positions let the caller reassemble results in traversal order. Hits++ tick the parse progress bar here (misses tick when their worker++ finishes). Cache failures degrade to all-miss.++ """++ from repowise.core.ingestion import compute_content_hash++ from repowise.core.ingestion.parse_cache import ParseCache++++ cache = None++ hits: dict[int, Any] = {}++ misses: list[tuple[int, tuple, str]] = []++ try:++ cache = ParseCache(repo_path / ".repowise")++ cache.load()++ except Exception as exc:++ logger.debug("parse_cache_init_failed", error=str(exc))++ return None, hits, [(idx, item, "") for idx, item in enumerate(fi_and_bytes)]++++ for idx, (fi, source) in enumerate(fi_and_bytes):++ content_hash = compute_content_hash(source)++ parsed = cache.get(fi, content_hash)++ if parsed is not None:++ hits[idx] = parsed++ if progress:++ progress.on_item_done("parse")++ else:++ misses.append((idx, (fi, source), content_hash))++ if hits:++ logger.info("parse_cache_used", hits=cache.hits, misses=cache.misses)++ return cache, hits, misses++++++def _cache_parsed(cache: Any, parsed: Any, content_hash: str) -> None:++ """Best-effort put of a freshly parsed file into the parse cache."""++ if cache is None or not content_hash:++ return++ # Cache failures must never fail the parse phase.++ with contextlib.suppress(Exception):++ cache.put(parsed, content_hash)++++++def _read_sources(++ file_infos: list[Any],++ progress: ProgressCallback | None,++) -> list[tuple]:++ """Read source bytes for *file_infos* with a thread pool (I/O-bound).++++ Returns ``(FileInfo, bytes)`` tuples in the same order as the input —++ the parse aggregation loop indexes positionally. Files that fail to++ read are dropped, ticking the parse bar once each (matching the old++ sequential loop's behavior).++ """++++ def _read_one(fi: Any) -> tuple | None:++ try:++ return (fi, Path(fi.abs_path).read_bytes())++ except Exception:++ if progress:++ progress.on_item_done("parse")++ return None++++ if not file_infos:++ return []++ workers = min(32, max(4, (os.cpu_count() or 4) * 2))++ with ThreadPoolExecutor(max_workers=workers) as pool:++ results = list(pool.map(_read_one, file_infos))++ return [r for r in results if r is not None]+++++ async def _run_ingestion(+ repo_path: Path,+ *,+@@ -156,70 +236,82 @@ async def _run_ingestion(+ if progress:+ progress.on_phase_start("parse", len(file_infos))++- # Read source bytes up front (I/O, sequential — fast enough; keeps worker++ # Read source bytes up front in a thread pool (I/O-bound; keeps worker+ # args small: FileInfo + bytes, both picklable plain dataclasses/bytes).+- fi_and_bytes: list[tuple] = []+- for fi in file_infos:+- try:+- source = Path(fi.abs_path).read_bytes()+- fi_and_bytes.append((fi, source))+- except Exception:+- if progress:+- progress.on_item_done("parse")++ fi_and_bytes: list[tuple] = _read_sources(file_infos, progress)++ parsed_files: list[Any] = []+ source_map: dict[str, bytes] = {}+- graph_builder = GraphBuilder(repo_path=repo_path, exclude_patterns=exclude_patterns)++ graph_builder = GraphBuilder(++ repo_path=repo_path,++ exclude_patterns=exclude_patterns,++ centrality_cache_dir=repo_path / ".repowise",++ )++ loop = asyncio.get_running_loop()+- workers = max(1, os.cpu_count() or 4)++- _use_process_pool = True++ # Content-hash parse cache: unchanged files skip the worker pool++ # entirely (an incremental update re-ingests the whole repo for one++ # changed file). Misses parse exactly as before.++ parse_cache, cached_hits, to_parse = _split_cached(repo_path, fi_and_bytes, progress)++ workers = max(1, min(os.cpu_count() or 4, len(to_parse) or 1))+++ parse_results: list[Any] = []++- try:+- with ProcessPoolExecutor(max_workers=workers) as pool:+- tasks = [loop.run_in_executor(pool, _parse_one, item) for item in fi_and_bytes]+- # Tick the parse-progress bar as each worker finishes —+- # ``asyncio.gather`` would otherwise hold every event back+- # until the last file is done, which on PowerToys-scale+- # repos looked like a hang at ``0/N`` for many minutes.+- # Per-task done-callbacks fire on the event loop thread and+- # preserve gather's ordered results, so the aggregation+- # loop below still indexes ``fi_and_bytes`` correctly.+- if progress is not None:+- _parse_tick = lambda _fut: progress.on_item_done("parse") # noqa: E731+- for fut in tasks:+- fut.add_done_callback(_parse_tick)+- parse_results = await asyncio.gather(*tasks, return_exceptions=True)+- except Exception as pool_exc:+- logger.warning(+- "process_pool_parse_failed_falling_back",+- error=str(pool_exc),+- )+- _use_process_pool = False+- # Fallback: in-process sequential parse+- _fallback_parser = ASTParser()+- for i, (fi, source) in enumerate(fi_and_bytes):+- try:+- result = _fallback_parser.parse_file(fi, source)+- parse_results.append(result)+- except Exception as exc:+- parse_results.append((fi.abs_path, str(exc)))+- if progress:+- progress.on_item_done("parse")+- if i % 50 == 49:+- await asyncio.sleep(0)++ if to_parse:++ try:++ with ProcessPoolExecutor(max_workers=workers) as pool:++ tasks = [++ loop.run_in_executor(pool, _parse_one, item) for _idx, item, _h in to_parse++ ]++ # Tick the parse-progress bar as each worker finishes —++ # ``asyncio.gather`` would otherwise hold every event back++ # until the last file is done, which on PowerToys-scale++ # repos looked like a hang at ``0/N`` for many minutes.++ # Per-task done-callbacks fire on the event loop thread and++ # preserve gather's ordered results, so the aggregation++ # loop below still indexes ``to_parse`` correctly.++ if progress is not None:++ _parse_tick = lambda _fut: progress.on_item_done("parse") # noqa: E731++ for fut in tasks:++ fut.add_done_callback(_parse_tick)++ parse_results = await asyncio.gather(*tasks, return_exceptions=True)++ except Exception as pool_exc:++ logger.warning(++ "process_pool_parse_failed_falling_back",++ error=str(pool_exc),++ )++ # Fallback: in-process sequential parse++ parse_results = []++ _fallback_parser = ASTParser()++ for i, (_idx, (fi, source), _h) in enumerate(to_parse):++ try:++ result = _fallback_parser.parse_file(fi, source)++ parse_results.append(result)++ except Exception as exc:++ parse_results.append((fi.abs_path, str(exc)))++ if progress:++ progress.on_item_done("parse")++ if i % 50 == 49:++ await asyncio.sleep(0)++++ # Merge fresh parses back into traversal order alongside cache hits.++ merged: dict[int, Any] = dict(cached_hits)++ for (idx, _item, content_hash), result in zip(to_parse, parse_results, strict=True):++ merged[idx] = result++ if not isinstance(result, tuple | Exception):++ _cache_parsed(parse_cache, result, content_hash)++ # Aggregate results into GraphBuilder on the main loop (not thread-safe).+- for idx, result in enumerate(parse_results):++ for idx in range(len(fi_and_bytes)):+ fi, source = fi_and_bytes[idx]++ result = merged.get(idx)+ if isinstance(result, tuple) and len(result) == 2 and isinstance(result[1], str):+ # Error tuple: (abs_path_str, error_str)+ logger.debug("parse_error_in_worker", path=result[0], error=result[1])+ elif isinstance(result, Exception):+ logger.debug("parse_exception_in_worker", path=fi.abs_path, error=str(result))+- else:++ elif result is not None:+ parsed_files.append(result)+ source_map[fi.path] = source+ graph_builder.add_file(result)+@@ -227,6 +319,8 @@ async def _run_ingestion(+ # attached above; only the fallback path ticks here (handled in+ # its own loop). No tick needed in aggregation.+++ if parse_cache is not None:++ parse_cache.save()+ _phase_done(progress, "parse")++ # ---- tsconfig path-alias resolver (before graph build) ------------------+@@ -434,51 +528,60 @@ async def reparse_for_resume(+ if progress:+ progress.on_phase_start("parse", len(file_infos))++- fi_and_bytes: list[tuple] = []+- for fi in file_infos:+- try:+- source = Path(fi.abs_path).read_bytes()+- fi_and_bytes.append((fi, source))+- except Exception:+- if progress:+- progress.on_item_done("parse")++ fi_and_bytes: list[tuple] = _read_sources(file_infos, progress)++ parsed_files: list[Any] = []+ source_map: dict[str, bytes] = {}+ loop = asyncio.get_running_loop()+- workers = max(1, os.cpu_count() or 4)+- parse_results: list[Any] = []++- try:+- with ProcessPoolExecutor(max_workers=workers) as pool:+- tasks = [loop.run_in_executor(pool, _parse_one, item) for item in fi_and_bytes]+- if progress is not None:+- _tick = lambda _fut: progress.on_item_done("parse") # noqa: E731+- for fut in tasks:+- fut.add_done_callback(_tick)+- parse_results = await asyncio.gather(*tasks, return_exceptions=True)+- except Exception as pool_exc:+- logger.warning("resume_reparse_pool_failed_falling_back", error=str(pool_exc))+- _fallback_parser = ASTParser()+- for i, (fi, source) in enumerate(fi_and_bytes):+- try:+- parse_results.append(_fallback_parser.parse_file(fi, source))+- except Exception as exc:+- parse_results.append((fi.abs_path, str(exc)))+- if progress:+- progress.on_item_done("parse")+- if i % 50 == 49:+- await asyncio.sleep(0)++ parse_cache, cached_hits, to_parse = _split_cached(repo_path, fi_and_bytes, progress)++ workers = max(1, min(os.cpu_count() or 4, len(to_parse) or 1))++ parse_results: list[Any] = []++- for idx, result in enumerate(parse_results):++ if to_parse:++ try:++ with ProcessPoolExecutor(max_workers=workers) as pool:++ tasks = [++ loop.run_in_executor(pool, _parse_one, item) for _idx, item, _h in to_parse++ ]++ if progress is not None:++ _tick = lambda _fut: progress.on_item_done("parse") # noqa: E731++ for fut in tasks:++ fut.add_done_callback(_tick)++ parse_results = await asyncio.gather(*tasks, return_exceptions=True)++ except Exception as pool_exc:++ logger.warning("resume_reparse_pool_failed_falling_back", error=str(pool_exc))++ parse_results = []++ _fallback_parser = ASTParser()++ for i, (_idx, (fi, source), _h) in enumerate(to_parse):++ try:++ parse_results.append(_fallback_parser.parse_file(fi, source))++ except Exception as exc:++ parse_results.append((fi.abs_path, str(exc)))++ if progress:++ progress.on_item_done("parse")++ if i % 50 == 49:++ await asyncio.sleep(0)++++ merged: dict[int, Any] = dict(cached_hits)++ for (idx, _item, content_hash), result in zip(to_parse, parse_results, strict=True):++ merged[idx] = result++ if not isinstance(result, tuple | Exception):++ _cache_parsed(parse_cache, result, content_hash)++++ for idx in range(len(fi_and_bytes)):+ fi, source = fi_and_bytes[idx]++ result = merged.get(idx)+ if isinstance(result, tuple) and len(result) == 2 and isinstance(result[1], str):+ logger.debug("parse_error_in_worker", path=result[0], error=result[1])+ elif isinstance(result, Exception):+ logger.debug("parse_exception_in_worker", path=fi.abs_path, error=str(result))+- else:++ elif result is not None:+ parsed_files.append(result)+ source_map[fi.path] = source++++ if parse_cache is not None:++ parse_cache.save()+ _phase_done(progress, "parse")++ tech_items: list = []diff --git a/tests/fixtures/distill/git_log_full.txt b/tests/fixtures/distill/git_log_full.txtnew file mode 100644index 000000000..6282fad34--- /dev/null+++ b/tests/fixtures/distill/git_log_full.txt@@ -0,0 +1,1357 @@+commit 2ef3f76cfd79821109155d06be961dff54a78b60+Author: Raghav Chamadiya <[email protected]>+Date: Fri Jun 5 01:06:10 2026 +0530++ perf: cache parsing and betweenness across incremental updates (#369)++ * perf(cli): keep the generation stack out of index-only updates++ Index-only updates (the post-commit hook hot path) imported+ ContextAssembler/PageGenerator before the index-only branch, and even+ leaf imports like generation.report paid for the full package __init__.+ Move the generation import + GenerationConfig construction below the+ index-only return, and make the package exports lazy (PEP 562) so light+ leaves no longer pull the assembler/generator/editor_files stack.+ Guarded by a subprocess test asserting generation.report leaves the+ heavy modules unloaded.++ * fix(cli): honor the persisted git tier on incremental updates++ update_cmd constructed GitIndexer without a tier, so every update ran+ FULL per-file blame — even for fast-mode (ESSENTIAL) repos whose index+ deliberately skipped it. Thread state.json's git_tier through+ _rebuild_graph_and_git; unknown/missing values keep the historical FULL+ behavior for legacy state files.++ * perf(ingestion): content-hash parse cache for unchanged files++ Parsing is the repo-proportional term of every ingest: repowise update+ re-parses the whole repo when one file changed, and large-repo inits pay+ minutes of tree-sitter time for files that haven't moved. Cache+ ParsedFiles keyed by (path, content hash) under a parser fingerprint+ (.scm query sources + package version), stored as pickle snapshots taken+ at parse time — graph builds mutate ParsedFile in place, so hits+ deserialize a fresh object graph and rebind the current FileInfo.++ Wired into the init pipeline (_run_ingestion + reparse_for_resume; hits+ skip the worker pool entirely) and the update path's _build_repo_graph.+ Best-effort throughout: corrupt cache, stale fingerprint, or any cache+ error degrades silently to a full parse; the cache file is rewritten+ with only entries touched per run so deleted files age out.++ Update-path ingest on this repo: 6.8s cold -> 2.7s warm (isolated).+ Equivalence suite: cached run is ParsedFile-equal + graph-isomorphic to+ a from-scratch build after edit/add/delete/rename/import-changing edit.++ * perf(graph): reuse betweenness when the subgraph structure is unchanged++ Exact Brandes betweenness was the largest remaining block of an+ incremental update (~8s on this repo, recomputed every run even for+ docstring-only edits). Betweenness is a pure function of the unweighted+ subgraph structure, so cache the values on disk keyed by a signature+ over the sorted node + edge sets: content edits that don't move+ call/heritage/import edges reuse the previous run's exact values; any+ structural change misses and recomputes as before.++ Opt-in via GraphBuilder(centrality_cache_dir=...) — wired from the init+ pipeline and the update path; ad-hoc builders are unchanged. Thread-safe+ (file + symbol kinds compute concurrently) and best-effort: corrupt or+ missing cache falls back to a fresh computation. For >30k-node graphs+ the sampled-betweenness path also caches, which makes its previously+ seedless (run-to-run varying) values stable for an unchanged graph.++ Update wall on this repo: both kinds reused, ~31s -> ~19s with warm+ parse + centrality caches.++commit d0f2315c87ea43683e719af73e48b3ae31b96345+Author: Raghav Chamadiya <[email protected]>+Date: Fri Jun 5 00:08:38 2026 +0530++ perf: make indexing & incremental update scale with change size (#368)++ * perf(pipeline): read source bytes with a thread pool before parsing++ The parse phase read every file sequentially before handing bytes to the+ ProcessPoolExecutor. Extract the loop into _read_sources() backed by a+ ThreadPoolExecutor (I/O-bound), preserving input order, per-file error+ handling, and parse-bar ticks. Applies to both _run_ingestion and+ reparse_for_resume.++ * perf(graph): cache file/symbol subgraphs across metric kernels++ file_subgraph()/symbol_subgraph() were rebuilt (full filtered copy,+ O(V+E)) on every metric call - seven kernels between them. Cache the+ filtered copies per build behind a lock (init computes metrics+ concurrently via asyncio.to_thread), invalidate on every structural+ mutation (build/add_file, co-change refresh, dynamic + framework edges)+ and on release_graph so the memory release stays effective.++ Also fold compute_percentiles' is_hotspot + entropy-default passes into+ the rank-assignment loop (one scan instead of three; same output).++ * perf(ingestion): one pruned walk for ts_workspace file discovery++ The mdx / vitest-config / package.json finders each rglob'd the entire+ tree - 12+ full walks with no pruning of node_modules, virtualenvs or+ .git. Measured at ~365s of a 737s --index-only init on a medium repo+ with a checked-in .venv; any repo with node_modules installed pays the+ same on every init and update.++ Replace them with a single os.walk (memoized per ResolverContext) that+ prunes vendored/derived dirs and collects all three target sets in one+ pass: 365s -> 0.02s on the same tree. The npm-script finder now derives+ package-relative paths against the unresolved repo_path to match the+ shared scan's base.++ * perf(update): pre-compute graph metrics with fan-out parallelism++ The update path's persist_graph_nodes computed pagerank/betweenness/+ symbol variants/communities lazily and sequentially. Reuse the init+ path's compute_metrics_parallel() at the end of _rebuild_graph_and_git+ (after the co-change edge refresh so cached subgraphs see the final+ structure) and in the config-triggered full health rescore. Best-effort:+ all metrics still fall back to lazy computation.++ * perf(graph): O(1) Tier-2b resolution + shared import-name index++ Tier-2b in both resolvers scanned every imported file's symbol dict per+ unresolved call/heritage ref, and the trait-dispatch fallback scanned+ every file in the repo per unresolved member call. Replace with:++ - lazy per-file merged {name -> symbol_id} / {(class,method) -> id} /+ {type -> id} views of the imported files' tables, merged in sorted+ path order with first-wins. The old set iteration order was+ hash-randomized per process, so shadowed names resolved+ non-deterministically; sorted order makes the winner stable.+ - a global {(class,method) -> [(path, id)]} index in file-insertion+ order for trait dispatch, preserving the old first-match identity+ and the skip-own-file rule.++ The byte-identical import-name maps both resolvers built independently+ now come from import_index.build_import_name_maps, constructed once per+ GraphBuilder.build() and injected (constructors keep a build-it-locally+ fallback, and the builder resets the memo whenever files change). The+ binding.source_file back-fill side effect moves with it.++ * perf(git): reuse per-thread Repo handles; batch the update commit walk++ Isolated measurement showed the git phase cost was NOT the repo-wide+ walks (commit index 1.1s, co-change 0.4s, prior-defects 0.4s on a 1.9k+ file repo) but constructing a fresh gitpython.Repo per FILE in the+ worker threads (~40ms each, ~64s serial). Reuse one Repo per worker+ thread via a small pool (closed when the index pass completes):+ index_repo FULL drops 101.6s -> 18.4s isolated (ESSENTIAL 77.7s -> 3.1s).++ index_changed_files (the update path) now also reads from the batched+ repo-wide commit index instead of spawning one `git log -- <file>` per+ changed file, making update metadata identical to a fresh full index --+ including the agent-provenance rollup, which the per-file fallback never+ classified (updates silently zeroed agent_commit_count/agent_authored_pct+ for changed files).++ Equivalence-tested: update-path metadata == full-index metadata per file.++ * perf(generation): batch RAG prefetch for level-2 file pages++ Each tier-1 file page used to fire its own vector_store.search() inside+ the LLM semaphore -- one embedder round-trip (50-200ms network) per page,+ serialized against generation slots, plus a per-page list_page_ids()+ store-size probe.++ Add VectorStore.search_many (default: concurrent per-query gather;+ InMemory/LanceDB/PgVector override to embed ALL queries in one embedder+ call -- N network round-trips become 1) and resolve RAG context for the+ whole level in one prefetch before level 2 starts, outside the semaphore.+ The store is static for the level (pages embed in one batch at level+ end), so prefetched results are identical to per-page fetches. On batch+ failure pages fall back to the unchanged per-page path.++ * perf(persistence): batch pgvector embed UPDATEs + IN-filtered summary lookups++ - PgVectorStore.embed_batch: pass the param list to one execute()+ (executemany) instead of looping one UPDATE round-trip per row.+ - PgVectorStore.get_page_summaries_by_paths: one parameterized+ expanding-IN SELECT instead of the base-class per-path gather+ (N queries -> 1 for the level-2 dependency-summary prefetch).+ - LanceDBVectorStore.get_page_summaries_by_paths: one IN-filtered scan+ with the same quote-doubling escape the single-path lookup uses.++ Both overrides keep the single-path semantics: first row per path wins,+ empty summaries dropped.++ * perf(generation): index symbol nodes once for call-graph/heritage extraction++ extract_call_graph and extract_heritage each scanned EVERY graph node per+ file, and level-2 context assembly runs them for every code file --+ O(files x nodes) per generation run (8s+ at 2k files / 30k symbol nodes,+ growing quadratically with repo size). Build a file_path -> symbol-nodes+ index in one pass and share it across the level (8s -> 0.27s measured on+ a synthetic 2k-file graph).++ Buckets preserve graph node iteration order, so extraction results are+ byte-identical to the scan (equivalence-tested); the scan path remains+ the default for single-file callers.++ * style: fix lint in new phase-2 files (docstring glyph, import order)++ * perf(graph): parallelize exact betweenness centrality over a process pool++ nx.betweenness_centrality is single-threaded pure-Python Brandes; on the+ ~11k-node symbol subgraph it was 54s isolated - the single largest block+ of both init's graph.metrics phase and every incremental update. Brandes+ is embarrassingly parallel over source nodes, so fan the source set out+ across a ProcessPoolExecutor (attribute-free int-relabeled edge list per+ worker) and sum the partials. Values are identical to the sequential+ call modulo float summation order (equivalence-tested at rel 1e-9).++ Small graphs and any pool failure fall back to the sequential NetworkX+ path. Measured: symbol betweenness 54.0s -> 8.3s isolated.++ * perf(dead-code): compile never-flag globs into one alternation regex++ _should_never_flag ran fnmatch.fnmatch per (node x pattern) - ~540+ patterns x 27k calls = 14.6M fnmatch invocations, each normcasing both+ sides (29M normcase calls; LCMapStringEx dominates on Windows). Profiled+ at 50.7s of a 51.5s dead-code analyze() on the repowise graph.++ Pre-normcase and translate each glob once, join into a single compiled+ alternation, and match the normcased path - byte-for-byte the same+ semantics fnmatch implements internally (equivalence-tested per glob+ and against a probe-path corpus). Measured: dead-code pass 20.7s ->+ 3.7s isolated.++ * perf(persistence): replace per-item SELECTs in batch upserts with one keyed query++ The generic _batch_upsert issued a SELECT round-trip per item; persisting+ 13k graph nodes meant 13k SELECTs (9.3s isolated), and the same pattern+ taxed edges (31k), symbols (11k), git metadata, commits, and function+ blame on every init and update. The keyed variant fetches all candidate+ rows for the repo once, matches natural keys in memory, and keeps the+ ORM update/insert + flush semantics (within-batch duplicate keys still+ converge to one row, equivalent to the old autoflush-visible behavior).++ All seven callers converted; the per-item loop had no remaining users+ and is removed. Measured: persist_graph_nodes 9.3s -> 2.5s isolated.++ * perf(parser): execute the compiled tree-sitter query once per file++ parse_file ran cursor.matches() over the whole tree five times - once+ each for symbols, imports, calls, heritage, and type refs - against the+ same compiled query. The plan's 3.2 ambiguity resolves to the contained+ case: one query, re-iterated; no .scm changes needed. Materialize the+ capture list once and route it through all five extraction passes+ (read-only consumers, verified). extract_heritage drops its tree/query/+ run_query params for the shared match list.++ Output is identical by construction (same capture dicts in the same+ order); the per-language fixture suites pin correctness and a new guard+ test asserts the query executes exactly once per file. Measured:+ sequential full-repo parse 4.7s -> 2.7s.++ * perf(health): cache duplication token streams + windows by content hash++ The duplication pass re-tokenized every file (a second tree-sitter parse+ plus a pure-Python leaf walk) and re-rolled 1.2M window hashes on every+ run - ~11s isolated on the repowise repo, paid in full by incremental+ updates that changed one file. Both outputs are pure functions of the+ file bytes given a fixed window size, so cache them per content hash in+ .repowise/duplication_cache.pkl: unchanged files replay their cached+ kind sequence + window tuples (WindowHash is rebuilt with the current+ path, making hits rename-proof); changed files tokenize as before.++ The minified/token-cap/window-budget gates stay live against cached+ lengths, the verifier now compares per-file kind lists (the only Token+ field it ever read), and any cache error degrades to a full re-tokenize.+ Cache equivalence, hit/miss/invalidation, and corrupt-file fallback are+ unit-tested; wired through HealthAnalyzer for init, update, rescore, and+ the health CLI.++commit bd1f1f1d3f27d0cb47c6fe73e3876520f45e2a5f+Author: Raghav Chamadiya <[email protected]>+Date: Thu Jun 4 20:26:41 2026 +0530++ feat(git): deterministic agent-provenance layer in the git indexer (#366)++ Classify every walked commit {agent, autonomy_tier, channel, confidence}+ from local-git attribution channels (bot/service identities, message+ footers, co-author trailers), riding the existing commit-index walk with+ no extra git pass (~20 us/commit). Persist per-commit columns on+ git_commits and per-file rollups (agent_commit_count, agent_authored_pct,+ agent_tier_counts_json) on git_metadata, with an Alembic migration.++ Patterns are precision-first (anchored to service identities, never bare+ names; service committer over a human author is tier 2, not 1) and+ config-extensible via an agent_provenance block in .repowise/config.yaml.+ Surfaced in the /git-metadata file view, the wiki At-a-glance panel, and+ the MCP get_context ownership block.++commit d30c3752085cbb63921f4356f60f00f28edbabce+Author: Swati Ahuja <[email protected]>+Date: Thu Jun 4 17:46:37 2026 +0530++ feat(cli): owl mascot init banner with repo-seeded heatmap wordmark (#364)++ * feat(cli): owl mascot banner with repo-seeded heatmap wordmark++ New ui/mascot.py: owl art, REPOWISE block wordmark (full + compact),+ GitHub-heatmap colouring seeded from the repo name (zlib.crc32 — stable+ across processes), and owl spinner frames registered with rich.++ print_banner keeps its signature but now renders the owl banner,+ width-adaptive: full design >= 82 cols, same design at 1-char strokes+ below. Facade gains banner_text/mini/OWL_SPINNER/THINKING_FRAMES+ (additive only).++ * feat(cli): owl spinner everywhere + completion/interrupt mascot moments++ All 10 spinner sites (4 SpinnerColumn, 6 console.status) now use+ OWL_SPINNER — the eye-roll owl frames, falling back to "dots" if rich's+ private spinner registry ever moves. Completion panels get a happy owl+ {^ ^} in the title; the Ctrl-C interrupt message a sleepy {─ ─}.+ Provider/validation errors stay sober on purpose.++ * fix(cli): review fixes — escape repo name, brand status spinners, derive width threshold++ - print_banner escapes repo_name before markup interpolation: a directory+ name containing a closing-tag sequence (e.g. 'evil[/bold]name') crashed+ with MarkupError; now renders literally (pre-existing, exposed by review)+ - the 6 console.status sites pass spinner_style=BRAND_STYLE so the owl is+ brand orange everywhere, matching the SpinnerColumn sites+ - full/compact switch threshold now derives from mascot.banner_width()+ (+4-col margin) instead of a hardcoded 82 in brand.py — font changes+ can't silently desync the layout; width pinned by a new test++ * polish(cli): nitpick fixes from review++ - status spinners back to rich's default green (owl frames kept) — the+ orange was only ever specified for the Progress columns+ - happy-owl prefix moves into build_completion_panel so future panels+ can't forget it; reporting.py reverts to plain titles+ - drop _LOGO: hand-pasted duplicate of art mascot.py owns (drift risk),+ and nothing reads it+ - seed-parity test rewritten behaviorally: asserts rendered span colors+ equal heat_grid(seed_for(repo)) predictions for both sizes, instead of+ monkeypatch-spying on seed_for+ - EYES_ERROR documented as reserved (errors stay sober by design)++commit 08cf155c5b43742eca351cc870c183efb05730e4+Author: Raghav Chamadiya <[email protected]>+Date: Thu Jun 4 17:45:14 2026 +0530++ fix(generation): close never-started page coroutines on cancellation (#365)++ Ctrl+C during generation cancels the run_level gather; pages still+ queued on the concurrency semaphore never start their inner coroutine.+ CancelledError is a BaseException, so it bypassed the except-Exception+ handler in guarded_named and the coroutine objects leaked, spraying one+ "coroutine ... was never awaited" RuntimeWarning per pending page at+ interpreter shutdown (~980 with default concurrency on a 985-page run).++ Add a BaseException handler that closes the inner coroutine before+ re-raising. close() is a no-op on a coroutine that already ran, so the+ in-flight page is unaffected. No behaviour change beyond silencing the+ teardown warnings - completed pages were already persisted and --resume+ already picked up cleanly.++ Fixes the RuntimeWarning reported in #358.++commit dafde049092267cb696e64cf1704e812df95d2b0+Author: joptimus <[email protected]>+Date: Thu Jun 4 06:57:05 2026 -0500++ fix(server): honor exclude_patterns in server jobs; prune stale rows (#354)++ Server-triggered jobs (web sync/full-resync, workspace sync, webhooks,+ scheduler) ran the shared pipeline without exclude_patterns, so excluded+ paths kept getting re-indexed even when set in repo settings or+ .repowise/config.yaml. execute_job() now resolves excludes from both+ sources and passes them into run_pipeline().++ Full pipeline persistence also did not remove rows for files that+ disappeared from the latest result, so a directory newly added to+ exclude_patterns left stale graph/dead-code/health/git data behind.+ persist_pipeline_result() now prunes file-scoped rows before re-upserting,+ using parsed_files as the source of truth for graph/analysis tables and+ git_metadata_list for git_metadata (a file can be git-tracked but unparsed).++commit 61b84e29191b4a1154d35ee160b5310031a613ed+Author: joptimus <[email protected]>+Date: Thu Jun 4 06:46:11 2026 -0500++ fix(web): decode breadcrumb path labels (#359)++commit b6bbe1f8856ca004bbc7214b093689fcb3e29dc7+Author: Raghav Chamadiya <[email protected]>+Date: Thu Jun 4 16:47:55 2026 +0530++ fix(health): calibrate hotspot + ownership signals for small teams and quiet repos (#361) (#363)++ Hotspot classification was purely repo-relative (top-quartile decayed churn+ + any 90d activity), so on a quiet repo a single drive-by maintenance commit+ was enough to flag a file as a hotspot - inflating the hotspot table, the+ hotspot-health KPI, and the HIGH->CRITICAL severity escalations that key off+ the flag. Ownership signals had no team-size awareness, so 1-3 person repos+ saw bus-factor/concentration warnings for what is simply their normal+ operating model.++ Three changes:++ 1. Absolute activity floors on is_hotspot (both classification paths -+ enrich.compute_percentiles and the SQL PERCENT_RANK recompute): a hotspot+ now also needs >= 3 commits in 90d AND real line movement+ (temporal_hotspot_score >= 0.5, with a >= 8-commits escape hatch for+ files whose numstat carries no line counts).++ 2. Repo-level active-contributor count (90d, bot-filtered, anchored to the+ repo's own most recent activity so historical checkouts stay correct),+ computed once per health run from per-author timestamps already in+ top_authors_json and exposed on FileContext.++ 3. Small-team severity gating: with <= 3 active contributors,+ concentration-only ownership_risk / knowledge_loss findings are capped at+ LOW (kept, annotated as informational) unless corroborated by hotspot+ activity; the get_risk bus-factor-risk label gets the same gate. Unknown+ team size (pre-timestamp indexes) keeps historical behaviour.++ Validated against the 21-repo / 9-language defect benchmark at T0+ (t0_floor_experiment.py, re-scoring cached findings through the product+ scorer with the demoted-flag transformations): corpus pooled AUC+ 0.7319 -> 0.7334 (keyword labels; bootstrap CI [-0.0022, +0.0045]) and+ 0.7446 -> 0.7473 under SZZ labels (CI [+0.0003, +0.0049] - excludes zero),+ mean Popt up on both. On quiet repos the floors demote ~70% of flags, all+ with 1-2 drive-by commits; the small-team gate touches no corpus repo+ (all have > 3 active contributors).++commit 413e82905e2d48b8699c7a61c2b98920c2fc555a+Author: Raghav Chamadiya <[email protected]>+Date: Wed Jun 3 22:05:53 2026 +0530++ feat(plugin): Claude Code plugin + root marketplace, refreshed to current surface (#356)++ Distribute the Claude Code plugin through a marketplace manifest at the repo+ root and bring it up to date with the shipped product.++ - Add .claude-plugin/marketplace.json (source: ./plugins/claude-code) so users+ install with `/plugin marketplace add repowise-dev/repowise`.+ - Correct the MCP surface to the nine exposed tools; drop references to the+ unexposed get_dependency_path / get_architecture_diagram.+ - Add commands: health, risk, dead-code, decision, doctor.+ - Add skills: code-health and change-review; refresh the existing four.+ - Bundle a PostToolUse hook (repowise-augment) and de-duplicate emissions so+ the bundled hook and the init-installed settings.json hook never double-fire.+ - Document the fifth layer (Code Health) across commands and docs.+ - README + Quickstart: add the plugin install path and fix stale+ PreToolUse/PostToolUse wording (hooks are PostToolUse-only).++commit 4a280c4b7eb0ecf547f3a2b899dbd2e588bd5040+Author: Raghav Chamadiya <[email protected]>+Date: Wed Jun 3 17:34:36 2026 +0530++ release: v0.16.0 (#350)++commit a57d7958aa5576adae9f98ec2e9e5e0dbace7a6f+Author: Raghav Chamadiya <[email protected]>+Date: Wed Jun 3 17:22:49 2026 +0530++ fix(git): make "last touched" the contributor's own last commit + honor .mailmap (#349)++ Owner "last touched" showed a file's last commit by *anyone* among files the+ person co-owns, so a teammate's commit to a shared file bumped your timestamp.+ Two fixes:++ - Record each author's own first/last commit timestamp in top_authors_json and+ aggregate "last touched" / "first commit" from that, falling back to the+ file-level value for indexes built before the field existed.+ - Read author identity through git's mailmap (%aN/%aE instead of %an/%ae) so a+ repo's .mailmap folds one person's multiple names/emails (personal vs. GitHub+ noreply, second machine) into a single contributor bucket.++ Adds a .mailmap coalescing the duplicated identities in this repo.++commit 2e21dad38c7ea4c2da00d0191b0a62c1eeed2b96+Author: Raghav Chamadiya <[email protected]>+Date: Wed Jun 3 14:36:15 2026 +0530++ Add Codex CLI provider and project integration (#348)++ * feat: add Codex CLI provider and project integration (#195)++ Add a local Codex CLI LLM provider built on authenticated `codex exec`+ sessions: argv-based subprocess (no shell), JSONL parsing tolerant of+ non-JSON noise, an async semaphore, a 600s exec timeout with kill, reasoning+ mapped to `model_reasoning_effort`, and zero-cost subscription usage tracking+ (flagged `estimated` when Codex omits usage).++ Add project-local Codex setup: `.codex/config.toml` MCP server, `.codex`+ lifecycle hooks (SessionStart / UserPromptSubmit / PostToolUse) installed via+ the import-isolated `repowise-augment` entry point, `.codex-plugin` metadata,+ skills, a plugin marketplace entry, and managed `AGENTS.md` generation reusing+ the existing marker-merge generator.++ Wire reasoning across all LLM providers (base interface + per-provider model+ discovery and supported reasoning modes) and add a richer interactive+ provider / model / reasoning selection flow to `repowise init`, with new+ `--codex/--no-codex` and `--agents/--no-agents` flags. Codex setup is opt-in:+ interactive runs prompt (default no); non-interactive runs require `--codex`.++ Squashes the six commits from #195 and rebases them onto current main,+ resolving conflicts from the init_cmd/ and ui/ package splits, the+ editor-setup integration abstraction, and the provider cost-tracker+ inline-await change:+ - feat: add Codex editor integration+ - docs: document Codex setup+ - Reasoning work+ - Add provider model discovery to init+ - Accept cache hints in Codex provider+ - Close Codex subprocess transport++ * fix(codex): address review — event-loop blocking, TOML safety, hook gating++ Follow-up fixes from a post-merge review of the Codex integration:++ - Run the Codex `_build_command` reasoning-catalog load and Gemini's lazy+ model discovery via `asyncio.to_thread`, so a cold `codex debug models`+ call or a paginated Gemini `/models` fetch can't stall every concurrent+ generation coroutine on the event loop.+ - Re-validate the merged `.codex/config.toml` with `tomllib` before writing+ in `save_codex_mcp_config` / `enable_codex_hooks_feature`. The table-rewrite+ regex only matches the bare key spelling; a quoted or inline `repowise`/+ `features` entry would otherwise append a duplicate-key block and corrupt+ the user's file. Now it aborts cleanly, original file untouched.+ - Gate the edit-tool PostToolUse freshness notice on `client == "codex"` so a+ future widening of the Claude installer's matcher can't emit Codex banners+ to existing Claude Code users. Adds a regression test.++ ---------++ Co-authored-by: Selene29 <[email protected]>++commit b0c8954031ec98eece57bdd595f8fa6ef90414db+Author: joptimus <[email protected]>+Date: Wed Jun 3 02:40:10 2026 -0500++ feat(cli): add advisory update check to doctor (#346)++ Surface when the installed repowise CLI is out of date and the exact+ command to update it, without ever auto-updating the user's environment.++ - Add `repowise.cli.update_check`: a conservative, never-raising helper+ that reads the current version, queries the PyPI JSON endpoint via the+ bundled httpx (short timeout), and suggests an install-method-aware+ upgrade command (uv tool / pipx / pip / editable checkout).+ - Add a `CLI version` row to `repowise doctor`: advisory only — it shows+ current vs latest plus both the resolved PATH executable and the full+ running command (these can differ), never flips doctor's pass/fail, and+ swallows network errors. Reminds the user to restart their MCP client+ when an update is available.+ - Treat an unparsable PyPI version as "unknown" rather than "up to date".+ - Document the check in CLI_REFERENCE.md and USER_GUIDE.md.++ Closes #338++commit bbb568d87c8b5e0b046e6e016d20b0f90b4dab67+Author: Raghav Chamadiya <[email protected]>+Date: Tue Jun 2 22:48:37 2026 +0530++ docs: fix broken README and CONTRIBUTING links (#345)++ The repowise-bench repo uses `master` as its default branch, but the README linked its reports via /blob/main/, producing four 404s (COMPARISON_REPORT, BENCHMARK_REPORT, flask48, sklearn48). Point them at /blob/master/. Also fix the root CONTRIBUTING link to its actual path under .github/.++ Refresh CONTRIBUTING.md while here: use the workspace-correct `uv sync --all-packages`, run tests via `uv run pytest`, list the types and ui packages, fix the LICENSE link, and add Conventional Commits and language/provider-recipe pointers.++commit 034876b053cf70b889979d2552c6a2bf9763df37+Author: Raghav Chamadiya <[email protected]>+Date: Tue Jun 2 22:34:38 2026 +0530++ refactor(cli): split init_cmd into a structured package (#344)++ Break the 2k-line init_cmd.py into a cohesive init_cmd/ package —+ command, workspace, generation, persistence, reporting, and the+ interactive prompts — and collapse the duplicated single-repo and+ per-repo workspace generation paths into one shared core (coverage+ selection, cost gate, generation + KG enrichment + cost flush).++ Also replace the two hand-rolled config.yaml yaml.dump writes with+ save_config_partial (extended to take arbitrary keys), and route the+ DB-engine setup through the existing open_repo_db helper.++ The public import surface is preserved: init_command plus the+ leading-underscore names sibling commands (search/reindex) and the+ test-suite import from repowise.cli.commands.init_cmd still resolve.++commit f433e4c970301829d57f9cd10184f48768bf056e+Author: Raghav Chamadiya <[email protected]>+Date: Tue Jun 2 21:40:51 2026 +0530++ feat(pipeline): make `repowise init --resume` actually resume (#343)++ * refactor(pipeline): split persist_pipeline_result into per-phase persisters++ Decompose the monolithic persist recipe into four independently-callable,+ phase-scoped functions — persist_ingestion (graph nodes/edges, external+ systems, symbols, security), persist_git (metadata, commits),+ persist_analysis (dead code, health, decisions, governance), and+ persist_generation (pages, KG). persist_pipeline_result now just composes+ them in dependency order.++ This is the backbone for incremental, resumable persistence: the+ orchestrator can persist a single phase's outputs the moment it completes+ instead of holding everything in memory until one terminal write. Public+ API (persist_pipeline_result, persist_graph_nodes) is unchanged and the+ end-state is identical — verified against the persistence + pipeline+ integration suites (235 tests green).++ * fix(init): persist + restore git tier across resume; honor fast mode in workspaces++ Two related fixes so `--resume` and multi-repo init respect the fast/index+ tier instead of silently doing more work than asked:++ - Record `run_mode`/`git_tier` in state.json on every init (both index-only+ and full paths). On `--resume`, continue the prior run's tier via+ `_effective_run_mode_for_resume` so a resumed fast index no longer falls+ back to STANDARD and redoes the FULL git indexing (per-file blame ++ co-change) the first run deliberately skipped. An explicit `--mode fast`+ on the resume still wins.+ - Thread `run_mode` through `_workspace_init` → `_WorkspaceCtx` → the+ per-repo `run_pipeline` call, mapping it to `OrchestratorMode.FAST`.+ Previously the multi-repo flow never passed `mode=`, so `--mode fast` was+ silently ignored for workspaces.++ Adds unit coverage for the resume tier-restore logic.++ * feat(pipeline): add resume building blocks — ledger, rehydration, controller++ Introduce a modular `pipeline/resume/` package, the foundation for skipping+ already-completed work on `repowise init --resume`. Nothing imports it yet,+ so this is behaviour-neutral; the orchestrator/CLI wiring follows.++ - phases.py: coarse checkpoint vocabulary (INDEX → ANALYSIS → GENERATION)+ chosen for resume value; INDEX bundles the expensive git history ++ graph centrality so a health-phase interrupt resumes cheaply.+ - ledger.py: ResumeLedger — durable "which phases completed" record over the+ existing pipeline_jobs table / SqlJobStore. Each write commits its own+ session so a completion survives the process being killed. Best-effort.+ - rehydrate.py: rehydrate_git_meta_map rebuilds git_meta_map from persisted+ rows via column introspection (graph side reuses rehydrate_graph_builder).+ Documents that the transient BlameIndex is intentionally not persisted.+ - controller.py: ResumeController — the single object the orchestrator will+ consult at phase boundaries (can_skip with a prefix rule, checkpoint_index,+ rehydrate_index). Builds its ledger from the session factory; requires a+ real Repository.id (fixes the old str(repo_path) FK violation).++ Unit-tested against in-memory SQLite: ledger lifecycle + cross-process+ visibility, git_meta_map round-trip, and the controller skip/prefix logic.++ * feat(pipeline): wire resume fast-path into the orchestrator++ run_pipeline now accepts an opt-in ResumeController. When a prior run+ persisted the INDEX phase, the resumed run rehydrates the graph + git+ metadata from the DB and only re-parses source (new parse-only+ `reparse_for_resume`), skipping the git-history walk and the four graph+ centrality kernels — the minutes-long work behind the "safe to Ctrl-C,+ then --resume" message. When not resuming, the freshly-built index is+ checkpointed right after external-systems extraction so an interrupt+ during analysis can resume.++ Strictly opt-in: with resume_controller=None (every current caller) the+ gather path and behaviour are byte-identical. Verified by a new+ integration test that runs the real pipeline twice on the sample repo and+ asserts the resumed run never calls _run_ingestion / _run_git_indexing yet+ still produces a rehydrated graph + re-parsed files.++ * feat(init): wire resume controller into `repowise init`++ `repowise init` now creates the repository row + engine before the pipeline+ (in the same event loop) and passes a ResumeController, so the index is+ checkpointed to the DB the moment it's built. An interrupt during analysis+ now leaves a resumable, persisted index; `repowise init --resume`+ rehydrates the graph + git metadata and only re-parses source, skipping the+ git-history walk and graph centrality — making the long-standing "safe to+ Ctrl-C, then --resume" message true.++ Details:+ - ResumeController tracks whether the INDEX was *actually* persisted+ (checkpoint success) or rehydrated; PipelineResult.index_persisted_+ incrementally reflects that. The final persist then writes only analysis ++ generation when the index is already on disk — avoiding a redundant write+ and never re-persisting a rehydrated graph. A best-effort checkpoint+ failure leaves the flag False, so the full persist still runs (no data+ loss).+ - Repository row created up front fixes the pipeline_jobs.repository_id FK+ (was str(repo_path), now the real Repository.id).+ - Dry runs skip all of this — they must not touch the database.++ Verified: full CLI integration suite (16) green, including dry-run and+ init-twice; resume integration + unit suites green.++ * feat(init): persist generated pages incrementally + reuse prior pages on resume++ Generation buffered every page in memory and only wrote them to the DB once,+ at the very end of the run. An interrupt mid-generation therefore lost the+ whole batch: pages already embedded into the vector store are skipped on the+ next resume (the store is the resume ground truth) yet were never written to+ the pages table, so the wiki stayed permanently incomplete.++ Wrap init's generation in run_generation_with_persistence, which:+ - loads persisted pages up front and hands them to the generator as+ prior_pages, so unchanged pages skip the LLM call (same reuse as update);+ - flushes each page to the DB the instant it is generated via the on_page_ready+ sink, on a dedicated engine (the sole wiki.db writer during generation, since+ cost rows are buffered until afterwards), so an interrupt leaves a usable+ partial wiki the next resume reuses.++ upsert_page is now a no-op when content, source_hash and model are unchanged,+ so the end-of-run persist of the same pages neither bumps the version nor+ archives a redundant PageVersion.++ * feat(init): make long synchronous index phases interruptible with Ctrl-C++ The #341 repro had two halves: the duplication-detector hang (fixed in #342)+ and 'Ctrl-C didn't return the terminal.' The latter is structural — heavy CPU+ phases run in asyncio.to_thread workers, and a bare SIGINT frees the event+ loop's main thread while the non-daemon worker keeps grinding, so the process+ never exits.++ Add cooperative cancellation: a process-global CancellationToken, armed for the+ run by a cancellation_scope() context manager in 'repowise init'. The first+ Ctrl-C flips the token (and the long duplication loops, which now poll+ check_cancelled() once per file / per hash bucket, unwind promptly); a second+ forces a hard quit. The token's PipelineCancelled subclasses BaseException so+ the pipeline's broad 'except Exception' phase guards can't swallow it — it+ always propagates to the CLI, which prints a 'run --resume' hint and exits.++ The interrupted run keeps its INDEX checkpoint on disk, so --resume reuses the+ expensive graph + git index rather than rebuilding it.++ * feat(pipeline): skip analysis recompute on a generation-interrupted resume++ Resume previously skipped only the INDEX phase; a run interrupted during the+ long generation phase still re-ran dead-code, health and (the costly,+ LLM-backed) decision extraction on resume.++ Checkpoint ANALYSIS mid-run — after decision extraction, before generation —+ via ResumeController.checkpoint_analysis, mirroring the existing INDEX+ checkpoint, so a generation interrupt leaves ANALYSIS marked complete. On+ resume, can_skip(ANALYSIS) rehydrates thin dead-code + decision reports+ (rehydrate_dead_code_report / rehydrate_decision_report) as generation input+ only and skips the recompute entirely.++ The rehydrated views carry just the fields the page generator reads and are+ never written back: the persisted analysis rows are authoritative, and+ persist_analysis (guarded on truthy reports) no-ops on the result's None+ reports while still folding harvested decisions + governance. Falls back to a+ full recompute if rehydration errors — the default (no controller) path is+ unchanged.++ * fix(init): forward repo_path to run_generation in the persistence wrapper++ run_generation_with_persistence consumed repo_path as its own parameter+ (to build the incremental-flush engine) but never forwarded it to+ run_generation, which requires it keyword-only. Every full (non+ index-only) init crashed at the generation phase with a missing-argument+ TypeError; index-only runs skip the wrapper and were unaffected.++ The unit fakes accepted **_kw, silently swallowing the unforwarded+ argument and hiding the broken contract. Harden all three to take+ repo_path as a required parameter and assert it, so a regression fails+ the test.++ * feat(ingestion): honour nested .gitignore files, not just the repo root++ FileTraverser only loaded the repo-root .gitignore; nested .gitignore+ files in subdirectories were ignored. In a monorepo or yarn/npm+ workspace, a package keeping its own .gitignore (excluding its build+ output, generated bundles, coverage, etc.) was not respected, so that+ generated content got pulled into the index.++ Git reads a .gitignore in every directory, not just the root. The+ per-directory ignore machinery already existed for .repowiseIgnore, so+ _get_dir_ignore now merges each directory's nested .gitignore and+ .repowiseIgnore into one spec. The root stays handled by the existing+ full-path self._gitignore / self._extra_ignore (no double-reads), and+ matching semantics are unchanged from the existing per-directory+ .repowiseIgnore handling.++ Also documents .gitignore / .repowiseIgnore / exclude precedence in+ docs/CONFIG.md. Adds TestNestedGitignore (4 cases).++commit 8cad94696a992500300565eb29926eea2e773c88+Author: joptimus <[email protected]>+Date: Tue Jun 2 09:50:10 2026 -0500++ fix(update): re-run health on config change even when git is unchanged (#337)++ * fix(update): re-run health on config change even when git is unchanged++ `repowise update` only re-scored health for files that changed in git, so+ editing `.repowise/config.yaml` (exclude_patterns) or `health-rules.json` had no+ effect until a code change happened to touch each file. Issue 3 of #296.++ - Add `config_fingerprint(repo_path)` (sha256 of config.yaml + health-rules.json)+ to helpers; `repowise init` stores it in state after the config is written so+ the first update does not false-positive.+ - `repowise update` compares the stored fingerprint to the current one. A real+ change triggers `_run_full_health_rescore`: rebuild the graph with current+ exclude_patterns, load GitMetadata from the DB (so biomarkers keep accurate+ churn/ownership data, including the newer prior_defect_count / change_entropy+ columns), drop excluded git rows, full-replace health metrics/findings, and+ refresh graph nodes. A missing prior fingerprint is backfilled, not treated as+ a change.+ - The config-change path takes precedence over the partial update (so unchanged+ files are re-scored under the new rules), is skipped under `--dry-run`, and+ does not advance the fingerprint if the re-score fails (so it retries).++ Tests: config_fingerprint, _git_metadata_to_dict, a failed-rescore-keeps-old-+ fingerprint unit test, and integration tests covering init storage, the+ unchanged/changed/dry-run paths, and config-change-with-source-diffs.++ Closes #296 (issue 3)++ * refactor(update): share rebuild path between incremental update and health re-score++ Maintainer feedback on #337:++ - Extract the traverse/parse/graph-build (+ framework-aware synthetic edges)+ into a shared _build_repo_graph helper, used by both _rebuild_graph_and_git+ and _run_full_health_rescore — instead of a second graph-rebuild copy inside+ the re-score. The config re-score now includes the framework-edge step it+ was previously missing, so both paths build the same graph. (Not routed+ through _persist_index_only: config re-score needs full health replacement,+ not partial upsert.)+ - Drop the unused cfg parameter from _run_full_health_rescore (git metadata is+ loaded from the DB, not re-indexed, so commit_limit/follow_renames are moot).+ - Replace the silent 'except Exception: pass' parse swallow with a skipped-file+ count warning in the shared helper.++ Adds TestBuildRepoGraph covering the parse-skip warning and the framework-edge+ step; updates the existing re-score test for the new signature.++commit 5ecff5aa00a4f4788df197acf2f9e5a3bb3f7ffa+Author: Raghav Chamadiya <[email protected]>+Date: Tue Jun 2 18:00:51 2026 +0530++ fix(health): bound duplication detection so minified bundles can't wedge `init` (#342)++ Clone detection tokenized every file and compared all window pairs within+ each hash bucket — an O(k^2) loop guarded only by the assumption that+ "buckets are small in practice." Minified/generated bundles (e.g. a+ checked-in `storybook-static/` chunk) collapse into hundreds of thousands+ of near-identical windows, so one bucket explodes into billions of+ comparisons. Because this runs before the per-file progress loop, `init`+ sat at `health 0/N` indefinitely (#341).++ Add layered, independent resource guards in a new `duplication/limits.py`:++ - skip minified/generated files via a cheap pre-tokenize byte scan+ (average / longest line length);+ - cap per-file tokens and the repo-wide window budget;+ - skip degenerate hash buckets larger than a threshold (the direct+ O(k^2) cap — oversized buckets are boilerplate noise, never real+ clones);+ - a soft wall-clock deadline as the final backstop.++ Any single layer suffices, so no repo shape can wedge the run again.+ `detect_clones` is refactored into bounded named stages, and the engine+ logs `health_duplication_limits` when a guard fires so skipped bundles+ are no longer invisible.++commit 8f9fc1ba5837af59f2e216c511549f19d5773bbc+Author: joptimus <[email protected]>+Date: Tue Jun 2 05:26:55 2026 -0500++ fix(mcp): exclude_patterns filtering for context, answer, and federated search (PR 4b) (#340)++ * fix(mcp): filter exclude_patterns from MCP tool responses++ Excluded files are skipped at ingest time, but rows may predate an+ exclude_patterns change, so MCP tools now also filter their results against the+ repo's exclude_patterns at query time. Issue 5 of #296.++ Adds per-repo filter helpers to _helpers.py (a compiled PathSpec from the repo+ config plus shape-specific filters: ORM rows by attribute, GraphNode file vs+ symbol nodes, result dicts by key, path lists, and "path::Name" node ids), each+ covered by parametrized tests, then wires them into the structured tools:++ - health, overview, dead_code, community, metrics, callers, symbol, diagram,+ dependency, risk, flows, why, decision_records+ - search (single-repo path)++ Single-file/target tools (annotate, dependency, metrics, callers, symbol, why,+ risk) reject or omit excluded targets; list/aggregate tools drop excluded rows+ before KPIs/rollups so excluded files never affect the numbers.++ Includes an end-to-end test proving get_health honors exclude_patterns from+ .repowise/config.yaml.++ Out of scope (follow-up): tool_context enrichment, tool_answer retrieval, and the+ federated ("all repos") search path, which need filtering inside their+ context/retrieval pipelines rather than a result-level helper call.++ Part of #296 (issue 5)++ * fix(mcp): filter exclude_patterns in context, answer, and federated search++ PR 4b — the custom-logic MCP surfaces deferred from PR 4a (#339), where+ filtering must happen inside each pipeline rather than at a single result list.++ - get_context: gate excluded file/symbol-id targets; filter imported_by,+ used_by, module child files, candidates, callers/callees, community+ members, and fuzzy not-found suggestions.+ - get_answer: drop excluded hits after hydration and after 1-hop graph+ expansion; bypass a cached answer to re-synthesis when it references a+ now-excluded path (in its fields or prose).+ - search (federated): attach target_path inside _search_single_repo and+ filter each repo by its own exclude_patterns before RRF aggregation.++ Adds tests for all three surfaces plus the cache-bypass and suggestion+ regressions.++commit 1fd50a5a663805cc28368cee0a07daf70cc22995+Author: joptimus <[email protected]>+Date: Tue Jun 2 05:26:07 2026 -0500++ fix(mcp): filter exclude_patterns from MCP tool responses (#339)++ Excluded files are skipped at ingest time, but rows may predate an+ exclude_patterns change, so MCP tools now also filter their results against the+ repo's exclude_patterns at query time. Issue 5 of #296.++ Adds per-repo filter helpers to _helpers.py (a compiled PathSpec from the repo+ config plus shape-specific filters: ORM rows by attribute, GraphNode file vs+ symbol nodes, result dicts by key, path lists, and "path::Name" node ids), each+ covered by parametrized tests, then wires them into the structured tools:++ - health, overview, dead_code, community, metrics, callers, symbol, diagram,+ dependency, risk, flows, why, decision_records+ - search (single-repo path)++ Single-file/target tools (annotate, dependency, metrics, callers, symbol, why,+ risk) reject or omit excluded targets; list/aggregate tools drop excluded rows+ before KPIs/rollups so excluded files never affect the numbers.++ Includes an end-to-end test proving get_health honors exclude_patterns from+ .repowise/config.yaml.++ Out of scope (follow-up): tool_context enrichment, tool_answer retrieval, and the+ federated ("all repos") search path, which need filtering inside their+ context/retrieval pipelines rather than a result-level helper call.++ Part of #296 (issue 5)++commit 24ab62156b4d941c9c6224728d838c82d17e01af+Author: Raghav Chamadiya <[email protected]>+Date: Mon Jun 1 23:47:26 2026 +0530++ fix(mcp): deep-merge per-server entry so user-added `env` survives re-registration (#336)++ `merge_mcp_entry()` and `save_root_mcp_config()` did a shallow+ `servers.update(new_entry)`, which replaced the entire `repowise` server+ value. Since `generate_mcp_config()` emits no `env` key, any user-added+ `env` block (BYOK provider/embedder keys for the stdio server) was+ silently wiped on every re-registration — `repowise init`, `update`, and+ anything calling `register_with_claude_*`. That dropped the configured+ embedder back to a mock and quietly degraded semantic search.++ Merge each server definition into the existing dict instead: generated+ `command`/`args`/`description` are refreshed, but other keys the user+ added (notably `env`) are preserved.++ Fixes #307.++commit b6b7a93bd59c42a8641859de1d7620515e71b813+Author: biggiesmallcap-blip <[email protected]>+Date: Tue Jun 2 00:16:39 2026 +1000++ feat(embeddings): add native ollama embedder (#331)++commit 03a268940a331352557009e19ab407a0a115e7ad+Author: biggiesmallcap-blip <[email protected]>+Date: Mon Jun 1 22:58:54 2026 +1000++ fix(dead-code): keep rust sibling test modules live (#332)++commit 43f09e322a54568487c86abd5c7d0658c594d6b6+Author: biggiesmallcap-blip <[email protected]>+Date: Mon Jun 1 22:58:25 2026 +1000++ fix(cli): use shared database engine for reindex (#333)++commit 604d2429026eafaa6be0d65ce396d826d7dadf14+Author: Raghav Chamadiya <[email protected]>+Date: Mon Jun 1 18:21:31 2026 +0530++ docs: sharpen tagline, reframe layer positioning, lift dashboard (#335)++ * docs: reframe layer positioning — stop calling our own layers commodity++ Drop the 'table stakes' / 'graph and wiki have competition' framing,+ which devalued genuinely strong layers. Elevate the differentiators+ (Decisions, Code Health) with a positive 'Edge' column instead of+ labeling the others as commodities.++ * docs: sharpen tagline, reframe layer positioning, lift dashboard++ - Tagline now leads with the code-health proof point instead of+ restating the banner.+ - Drop 'table stakes' / 'graph and wiki have competition' framing that+ devalued strong layers; rename the column to 'Edge' with positive+ one-liners and star the two true differentiators.+ - Move the Local dashboard section up to right after Benchmarks so the+ web-UI visual lands higher on the page.++commit 21dffbb47be9f799968f77f055b05db849383a51+Author: Raghav Chamadiya <[email protected]>+Date: Mon Jun 1 17:33:16 2026 +0530++ docs: revamp README and align linked docs for accuracy (#334)++ Rewrite the README into a tighter, more skimmable form: a five-layer+ overview table, a dedicated Code Health section leading with the+ head-to-head defect-prediction results, a visual language showcase,+ persona-based routing, and condensed MCP/CLI/dashboard sections. Deep+ prose moves into a new docs/INTELLIGENCE_LAYERS.md.++ Correct stale figures across README and linked docs:+ - code-health biomarkers 12/15 -> 25+ - Full-tier languages 8 -> 9, total AST languages 14 -> 15+ - MCP tools 7 -> 9 (document the missing get_symbol and get_health)+ - health-defect benchmark -> 21 repos / 9 languages / mean ROC AUC 0.74+ - add the undocumented risk and delete CLI commands; add init --mode++ Add docs/CONFIG.md (the README linked to a file that did not exist) and+ docs/INTELLIGENCE_LAYERS.md.++commit b55e3c5a66cd0b889a1f431661f7ec3efefa2106+Author: Raghav Chamadiya <[email protected]>+Date: Sun May 31 20:09:16 2026 +0530++ fix(cost-tracking): stop second cost engine from wedging `repowise update` on 'database is locked' (#326) (#330)++ * fix(cost-tracking): stop second cost engine from wedging update on 'database is locked'++ DB-backed cost tracking opens a second SQLAlchemy engine on wiki.db and does an+ INSERT INTO llm_costs per LLM call. During doc generation a writer is held on+ the same file, so each cost insert loses WAL's single-writer race and blocks the+ full 30s busy_timeout before failing — turning a minutes-long `repowise update`+ into an effectively non-terminating one (issue #326).++ Two guards:++ 1. Opt-out: `--no-cost-tracking` flag on `repowise update` and the+ REPOWISE_NO_COST_TRACKING env var (honored by build_cost_tracker, so init and+ the --full upgrade path respect it too). When set, no second engine is opened+ — an in-memory CostTracker still powers the live cost readout.++ 2. Best-effort persistence when tracking is enabled: the cost engine now uses a+ short (2s) busy_timeout via a new create_engine(busy_timeout_ms=...) override,+ threaded through open_repo_db. A contended cost insert fails fast and is+ dropped by _persist instead of stalling the generation writer. The default+ 30s headroom for legitimate bulk graph-edge writes is unchanged.++ Tests: per-engine busy_timeout override, env/flag resolution, in-memory+ fallback, and an end-to-end held-write-lock contention test proving record()+ never raises and drops the row under contention while persisting uncontended.++ * fix(cost-tracking): defer cost writes out of the generation window by default++ Make the default `repowise update` / `init` path safe without requiring the+ opt-out flag. The DB-backed CostTracker used by the CLI is now *buffered*: each+ per-call row is held in memory and persisted in a single transaction by a new+ `flush()` after generation (and KG enrichment) completes — so cost INSERTs never+ land inside the contended generation window at all, for every flow including the+ streaming on_page_ready path. This removes the contention by construction rather+ than merely bounding it.++ - CostTracker gains `buffered` (opt-in; default False so external callers such+ as the hosted backend keep immediate writes) and `flush()`; `record()` appends+ to an in-memory buffer when buffered. `_persist_rows` writes the batch in one+ transaction.+ - make_cost_tracker / upgrade_flow build buffered trackers; update_cmd, init_cmd+ (x2) and upgrade_flow flush after generation via a new flush_cost_tracker+ helper. The live cost readout (session_cost) is unaffected.++ The short cost-engine busy_timeout and the --no-cost-tracking /+ REPOWISE_NO_COST_TRACKING opt-out from the previous commit remain as defense and+ convenience. Rows still live in wiki.db, so repowise costs and the web/hosted+ readers are unchanged.++ Tests: buffered record() writes nothing until flush; flush persists the batch+ after a held writer releases; flush is a no-op for in-memory trackers; the sync+ flush_cost_tracker helper works across asyncio.run loops.++commit 61fce0ab87b3612f465c37ed0b55d5eade12da8f+Author: Raghav Chamadiya <[email protected]>+Date: Sun May 31 16:59:19 2026 +0530++ release: v0.15.2 — on_page_ready streaming callback (#329)++ * release: v0.15.2++ * docs(changelog): add 0.15.2 entry++commit 5a776a4b27532ae555b35b8ef246d5100c4db04d+Author: Raghav Chamadiya <[email protected]>+Date: Sun May 31 16:52:05 2026 +0530++ feat(generation): add on_page_ready streaming callback (#328)++ Thread an optional on_page_ready callback through run_pipeline ->+ run_generation -> generate_all -> the level orchestrator, invoked with+ each GeneratedPage the moment it completes (alongside the existing+ on_page_done, which only receives the page type).++ This lets callers persist or stream pages incrementally instead of+ waiting for the whole run to return — e.g. flushing pages to storage+ per page so a generation cut-off yields a partial-but-usable set rather+ than nothing. The callback is best-effort: a sink exception is logged+ and swallowed so it can never drop a page or abort a level.++ Additive and fully backward-compatible (defaults to None).++commit 2deede96466abfb5e09a9a2f36e2df5fdce03307+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 18:55:46 2026 +0530++ release: v0.15.1 (#325)++ Bump version to 0.15.1 across pyproject, package __init__ files, web+ footer, and uv.lock; add changelog entry.++ Patch release shipping two fixes:+ - mcp: surface embedder init failure instead of silent mock fallback (#324)+ - pipeline: drop transient BlameIndex before serialization (#323)++commit 910d374805d2685dcfbb4fa278400a6151f0ead0+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 18:48:31 2026 +0530++ fix(mcp): surface embedder init failure instead of silent mock fallback (#324)++ When an embedder is explicitly configured (REPOWISE_EMBEDDER or+ .repowise/config.yaml) but fails to initialise at runtime — most often a+ missing API key — the MCP server swallowed the exception, fell back to+ MockEmbedder with a single WARNING, then reported ready and listed every+ tool. Semantic search (search_codebase, get_answer) silently ran on 8-dim+ mock vectors that cannot match a real index, returning empty/irrelevant+ results with no signal to the caller (#306).++ Two fixes:++ - Resolve through the shared embedder registry (get_embedder) so every+ backend is honoured — openai, gemini, openrouter, and any custom embedder+ registered via register_embedder. The old code hardcoded only the gemini+ and openai branches, so an explicit `embedder: openrouter` (or any custom+ name) was silently treated as mock with no warning at all.++ - Stop pretending to be healthy on failure. An explicitly-configured+ embedder that fails to initialise now logs at ERROR with the missing key+ and remediation, and records the degradation in _state._embedder_status.+ build_meta() surfaces `embedder: "mock"`, `embedder_degraded: true`, and a+ human-readable `embedder_warning` in every tool's _meta envelope so an+ agent can detect the misconfiguration programmatically. MockEmbedder is+ still returned so non-RAG tools keep working; an unconfigured embedder (or+ an explicit `mock`) is the intended default and is never flagged degraded.++commit 9a435b9bdf2ffdac7ceefa9c19e0c4b0e17aeed2+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 18:34:24 2026 +0530++ fix(pipeline): drop transient BlameIndex before serialization (#323)++ The per-file BlameIndex is an in-memory-only signal consumed by the health+ biomarkers (function_hotspot / code_age_volatility); its own docstring notes+ it must never round-trip through the DB or artifacts. It was being attached to+ the git-metadata dicts that escape the pipeline in PipelineResult.git_metadata_list,+ so any JSON serialization of git metadata raised "Object of type BlameIndex is+ not JSON serializable", aborting the whole artifact build.++ Strip it once the health phase has consumed it, in both the full pipeline+ (orchestrator) and the incremental `update` path, via a shared+ drop_transient_git_signals() helper. DB persistence already filtered it out by+ column, so this is behaviour-preserving for OSS DB users and fixes JSON+ artifact writers (e.g. the hosted backend's git_metadata.json).++commit 300bd5d369992ca9aa3b40c968da56dacfc8826c+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 16:32:10 2026 +0530++ release: v0.15.0 (#321)++commit 23f6cb94095ca00f478558c30bbcddb611d8b3ff+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 16:25:33 2026 +0530++ fix(ui): use extensionless relative imports across package (#320)++ The commits/git feature files imported relative modules with explicit+ .js extensions (e.g. "./priority-badge.js"), but the rest of the ui+ package — and the web app's webpack resolution — use extensionless+ relative imports. With no .js->.tsx extension alias configured, those+ specifiers failed to resolve and broke the web build.++ Strip the .js extension from all relative import/export specifiers so+ the new files match the package convention and the build resolves.++commit f00e7995d581069d78b45419dbf98868f3f84afe+Author: joptimus <[email protected]>+Date: Sat May 30 03:04:24 2026 -0500++ fix(exclude-patterns): enforce exclude_patterns in git indexer and dynamic edges (#308)++ exclude_patterns was honored by file traversal but bypassed by the git indexer+ and by dynamic-edge creation, so excluded files still appeared in git metadata+ and as phantom graph nodes (issues 1 and 2 of #296).++ - GitIndexer accepts exclude_patterns and filters them out of `git ls-files`;+ threaded through _run_git_indexing and the orchestrator git stage (init path).+ - The incremental update path passes exclude_patterns to GitIndexer and filters+ changed paths via a new _build_filtered_changed_paths helper.+ - GraphBuilder accepts exclude_patterns; add_dynamic_edges no longer creates+ phantom nodes for excluded targets. Threaded into the ingestion phase and the+ update rebuild path.++ Tests: GitIndexer ls-files filtering, _build_filtered_changed_paths, and+ dynamic-edge phantom-node skipping.++ Closes #296 (issues 1 and 2)++commit 950269f5dd79d96343633c90927392670881da51+Author: joptimus <[email protected]>+Date: Sat May 30 02:59:06 2026 -0500++ feat(typescript): support .mts/.cts as TypeScript (#310)++ Files with the .mts (ESM) and .cts (CommonJS) TypeScript module extensions+ were skipped by the indexer because the TypeScript language spec only mapped+ .ts/.tsx, so they were detected as unknown (issue #288). .cts is included+ because it is the paired CommonJS module extension and shares the parser and+ resolver path.++ - Register .mts/.cts in the TypeScript language spec; they propagate to+ EXTENSION_TO_LANGUAGE automatically and route to the plain TypeScript grammar+ (only .tsx needs the JSX variant).+ - Resolve extensionless imports to .mts/.cts across all three resolvers: the+ relative resolver (probe list, directory-barrel /index.mts and /index.cts,+ and the fake-extension fallback), tsconfig path-alias resolution+ (_TS_EXTENSIONS, _INDEX_FILES), and workspace exports (_PROBE_EXTENSIONS).+ - Recognize .mts/.cts test files (.test.mts, .spec.cts, etc.) in every+ test-classification list: dead-code never-flag, health engine _is_test_file+ and _has_paired_test_file, hidden_coupling, coverage detector+ (_TEST_FILE_SUFFIXES and paired_test_file), and coverage_gap.++ Out of scope (follow-up): framework-edge route detection for module-script+ extensions (next_app, remix), and full Node ESM/CJS output-mapping semantics.++ Closes #288++commit 1ae19dac192fe82aea9afccb80095ccbfaf9c41f+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 13:18:21 2026 +0530++ feat(git): add commits change-risk page, per-function blame, coverage-gradient breakdown (#319)++ Surfaces and captures git/health signals the engine produced but never exposed.++ Commits / change-risk page (the per-commit table payoff):+ - GET /api/repos/{id}/commits (paginated, sort=risk|date) + /commits/{sha}+ drill-down with an exact per-feature risk-driver breakdown.+ - Normalize change-risk for display: a repo-relative percentile + tercile+ review_priority (RiskNormalizer), so the ranking is portable across repos+ rather than skewing high on repos with large typical commits. The raw+ calibrated score/level are kept but de-emphasized.+ - Persist author_experience on git_commits (migration 0028) so the breakdown+ reproduces the stored score exactly.+ - New packages/ui/src/commits module (review-priority queue, driver breakdown,+ priority badge, credibility strip) + web /commits page + nav entry.++ Per-function blame rollup:+ - New git_function_blame table (migration 0029) + rollup builder, persisting the+ per-function modification count, median line age, recent-mod count, and blame+ owner derived from the FULL-tier blame index (previously discarded).++ Coverage-gradient surfacing + score breakdown:+ - The score-breakdown endpoint now reads each finding's stored health_impact+ (continuous, weighted, capped) instead of recomputing from the severity band,+ so it reproduces the file score and shows the coverage gradient. coverage_gradient+ records its base deduction; the UI biomarker glossary gains the gradient category.++ Incremental / backfill commit capture:+ - Backfill (essential->full) and repowise update now keep git_commits current:+ a bounded walk captures only commits newer than the newest persisted one and+ idempotently upserts; the partial blame rollup is persisted too.++commit dfeeb705539f732449ac0f77381196741c6ecc0c+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 12:05:22 2026 +0530++ feat(git): surface change-complexity and defect-history signals (#318)++ Several per-file git signals were computed on every index but never left the+ database: change entropy (Hassan's History Complexity Metric) and its+ percentile, prior bug-fix count, rename lineage, and the temporal hotspot+ score / commit-cap flag (the latter two were already on the hotspots+ endpoint but missing from git-metadata).++ Expose them on the git-metadata and hotspots responses (change_entropy_pct+ normalized to 0-100 like churn_percentile), thread them through the shared+ and web TypeScript types, and add a "Change Complexity & Defect History"+ card to the per-file git panel: change entropy as a percentile bar, prior+ bug-fix count, and rename lineage when present. The card renders nothing when+ a file has no such signal.++ Pure read-path — no new capture, no re-index. Adds response-shape tests for+ the surfaced fields.++commit 5be3cdadfefe52459bd3582698037074a068a40e+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 11:36:32 2026 +0530++ feat(git): persist per-commit change-risk history (#317)++ Add a per-commit `git_commits` table capturing one row per commit in the+ indexed window: author, timestamp, subject, Kamei change features+ (lines/files/dirs/subsystems touched, churn entropy, fix-flag) and a+ calibrated just-in-time change-risk score/level.++ The rows are collected during the existing repo-wide commit-index walk via+ an optional sink (no extra git pass) and scored by the existing linear,+ interpretable change-risk model — pure arithmetic, no LLM or blame at+ runtime. Author experience, the one change-risk feature that costs a+ subprocess in the live `repowise risk` path, is reconstructed in-memory as a+ cumulative per-author commit tally, so the whole pass stays zero-extra-git+ (~14 ms for 273 commits on this repo).++ Wiring is additive and non-breaking: rows ride on `GitIndexSummary` and are+ upserted alongside file-level git metadata. Includes the model, an Alembic+ migration, bulk-upsert/delete/paginated CRUD (sortable by risk or date), and+ unit + integration coverage.++commit be3ea565161fb94788ebe8b5fe523d2a9f9d94a4+Author: Raghav Chamadiya <[email protected]>+Date: Sat May 30 10:46:16 2026 +0530++ feat(health): extend code-health biomarkers to Kotlin, C++, and C# (#316)++ The code-health complexity walker shipped per-language node maps for+ Python, TypeScript, JavaScript, Go, Java, and Rust, but Kotlin, C++, and+ C# had no map — so files in those languages produced no complexity,+ cohesion, or test-quality biomarkers even though they are listed as+ Full-tier. This adds their LanguageNodeMap entries so all nine Full-tier+ languages compute the same biomarker set.++ - Kotlin / C++ / C#: control-flow, class-level (LCOM4 / god-class), and+ assertion-block node maps, with handcrafted fixtures and walker tests+ asserting nesting, cyclomatic complexity, class cohesion, and+ assertion-run detection.+ - Walker generalizations (additive; existing languages unchanged):+ follow C/C++ declarator chains to recover the function name; match an+ assertion call that is itself the statement (grammars without an+ expression-statement wrapper); consult the receiver `expression` field+ used by C# member access.+ - Document the implicit-receiver limit (bare `field` vs `this.field`+ degrades cohesion to "no signal", never a false positive).+ - LANGUAGE_SUPPORT.md gains a code-health-biomarker support row plus a+ per-language coverage checklist, and reconciles Go as the one gap+ (no class-grouping node, so no class-level metrics).++ No scoring constants change; the snapshot test is untouched.diff --git a/tests/fixtures/distill/git_status_dirty.txt b/tests/fixtures/distill/git_status_dirty.txtnew file mode 100644index 000000000..a0df9fa63--- /dev/null+++ b/tests/fixtures/distill/git_status_dirty.txt@@ -0,0 +1,30 @@+On branch feat/distill+Changes to be committed:+ (use "git restore --staged <file>..." to unstage)+ new file: packages/core/src/repowise/core/distill/__init__.py+ new file: packages/core/src/repowise/core/distill/budget.py+ new file: packages/core/src/repowise/core/distill/filters/__init__.py+ new file: packages/core/src/repowise/core/distill/filters/base.py+ new file: packages/core/src/repowise/core/distill/filters/build_output.py+ new file: packages/core/src/repowise/core/distill/filters/file_listing.py+ new file: packages/core/src/repowise/core/distill/filters/git_diff.py+ new file: packages/core/src/repowise/core/distill/filters/git_log.py+ new file: packages/core/src/repowise/core/distill/filters/git_status.py+ new file: packages/core/src/repowise/core/distill/filters/logs.py+ new file: packages/core/src/repowise/core/distill/filters/test_output.py+ new file: packages/core/src/repowise/core/distill/markers.py+ new file: packages/core/src/repowise/core/distill/registry.py+ new file: packages/core/src/repowise/core/distill/router.py+ new file: packages/core/src/repowise/core/distill/store.py+ new file: packages/core/src/repowise/core/distill/tracking.py++Changes not staged for commit:+ (use "git add <file>..." to update what will be committed)+ (use "git restore <file>..." to discard changes in working directory)+ modified: README.md++Untracked files:+ (use "git add <file>..." to include in what will be committed)+ repowise-backend-llmcost/+ tests/fixtures/distill/+diff --git a/tests/fixtures/distill/go_test_fail.txt b/tests/fixtures/distill/go_test_fail.txtnew file mode 100644index 000000000..31ac69b37--- /dev/null+++ b/tests/fixtures/distill/go_test_fail.txt@@ -0,0 +1,295 @@+=== RUN TestParseManifest+=== RUN TestParseManifest/npm_basic+=== RUN TestParseManifest/npm_workspaces+=== RUN TestParseManifest/pypi_requirements+--- PASS: TestParseManifest (0.02s)+ --- PASS: TestParseManifest/npm_basic (0.00s)+ --- PASS: TestParseManifest/npm_workspaces (0.01s)+ --- PASS: TestParseManifest/pypi_requirements (0.00s)+=== RUN TestGraphBuilder+--- PASS: TestGraphBuilder (0.11s)+=== RUN TestResolveImports+=== RUN TestResolveImports/relative+=== RUN TestResolveImports/aliased+--- FAIL: TestResolveImports (0.04s)+ --- FAIL: TestResolveImports/aliased (0.02s)+ resolver_test.go:84: ResolveImport("@core/graph") = "", want "packages/core/graph.go"+ resolver_test.go:85: unexpected error: alias map not initialized+=== RUN TestParserPython1+=== RUN TestParserPython1/basic+=== RUN TestParserPython1/edge_cases+--- PASS: TestParserPython1 (0.08s)+ --- PASS: TestParserPython1/basic (0.00s)+ --- PASS: TestParserPython1/edge_cases (0.01s)+=== RUN TestParserPython2+=== RUN TestParserPython2/basic+=== RUN TestParserPython2/edge_cases+--- PASS: TestParserPython2 (0.08s)+ --- PASS: TestParserPython2/basic (0.00s)+ --- PASS: TestParserPython2/edge_cases (0.01s)+=== RUN TestParserPython3+=== RUN TestParserPython3/basic+=== RUN TestParserPython3/edge_cases+--- PASS: TestParserPython3 (0.08s)+ --- PASS: TestParserPython3/basic (0.00s)+ --- PASS: TestParserPython3/edge_cases (0.01s)+=== RUN TestParserPython4+=== RUN TestParserPython4/basic+=== RUN TestParserPython4/edge_cases+--- PASS: TestParserPython4 (0.08s)+ --- PASS: TestParserPython4/basic (0.00s)+ --- PASS: TestParserPython4/edge_cases (0.01s)+=== RUN TestParserPython5+=== RUN TestParserPython5/basic+=== RUN TestParserPython5/edge_cases+--- PASS: TestParserPython5 (0.08s)+ --- PASS: TestParserPython5/basic (0.00s)+ --- PASS: TestParserPython5/edge_cases (0.01s)+=== RUN TestParserPython6+=== RUN TestParserPython6/basic+=== RUN TestParserPython6/edge_cases+--- PASS: TestParserPython6 (0.08s)+ --- PASS: TestParserPython6/basic (0.00s)+ --- PASS: TestParserPython6/edge_cases (0.01s)+=== RUN TestParserPython7+=== RUN TestParserPython7/basic+=== RUN TestParserPython7/edge_cases+--- PASS: TestParserPython7 (0.08s)+ --- PASS: TestParserPython7/basic (0.00s)+ --- PASS: TestParserPython7/edge_cases (0.01s)+=== RUN TestParserPython8+=== RUN TestParserPython8/basic+=== RUN TestParserPython8/edge_cases+--- PASS: TestParserPython8 (0.08s)+ --- PASS: TestParserPython8/basic (0.00s)+ --- PASS: TestParserPython8/edge_cases (0.01s)+=== RUN TestParserTypeScript1+=== RUN TestParserTypeScript1/basic+=== RUN TestParserTypeScript1/edge_cases+--- PASS: TestParserTypeScript1 (0.03s)+ --- PASS: TestParserTypeScript1/basic (0.00s)+ --- PASS: TestParserTypeScript1/edge_cases (0.01s)+=== RUN TestParserTypeScript2+=== RUN TestParserTypeScript2/basic+=== RUN TestParserTypeScript2/edge_cases+--- PASS: TestParserTypeScript2 (0.03s)+ --- PASS: TestParserTypeScript2/basic (0.00s)+ --- PASS: TestParserTypeScript2/edge_cases (0.01s)+=== RUN TestParserTypeScript3+=== RUN TestParserTypeScript3/basic+=== RUN TestParserTypeScript3/edge_cases+--- PASS: TestParserTypeScript3 (0.03s)+ --- PASS: TestParserTypeScript3/basic (0.00s)+ --- PASS: TestParserTypeScript3/edge_cases (0.01s)+=== RUN TestParserTypeScript4+=== RUN TestParserTypeScript4/basic+=== RUN TestParserTypeScript4/edge_cases+--- PASS: TestParserTypeScript4 (0.03s)+ --- PASS: TestParserTypeScript4/basic (0.00s)+ --- PASS: TestParserTypeScript4/edge_cases (0.01s)+=== RUN TestParserTypeScript5+=== RUN TestParserTypeScript5/basic+=== RUN TestParserTypeScript5/edge_cases+--- PASS: TestParserTypeScript5 (0.03s)+ --- PASS: TestParserTypeScript5/basic (0.00s)+ --- PASS: TestParserTypeScript5/edge_cases (0.01s)+=== RUN TestParserTypeScript6+=== RUN TestParserTypeScript6/basic+=== RUN TestParserTypeScript6/edge_cases+--- PASS: TestParserTypeScript6 (0.03s)+ --- PASS: TestParserTypeScript6/basic (0.00s)+ --- PASS: TestParserTypeScript6/edge_cases (0.01s)+=== RUN TestParserTypeScript7+=== RUN TestParserTypeScript7/basic+=== RUN TestParserTypeScript7/edge_cases+--- PASS: TestParserTypeScript7 (0.03s)+ --- PASS: TestParserTypeScript7/basic (0.00s)+ --- PASS: TestParserTypeScript7/edge_cases (0.01s)+=== RUN TestParserTypeScript8+=== RUN TestParserTypeScript8/basic+=== RUN TestParserTypeScript8/edge_cases+--- PASS: TestParserTypeScript8 (0.03s)+ --- PASS: TestParserTypeScript8/basic (0.00s)+ --- PASS: TestParserTypeScript8/edge_cases (0.01s)+=== RUN TestParserCSharp1+=== RUN TestParserCSharp1/basic+=== RUN TestParserCSharp1/edge_cases+--- PASS: TestParserCSharp1 (0.08s)+ --- PASS: TestParserCSharp1/basic (0.00s)+ --- PASS: TestParserCSharp1/edge_cases (0.01s)+=== RUN TestParserCSharp2+=== RUN TestParserCSharp2/basic+=== RUN TestParserCSharp2/edge_cases+--- PASS: TestParserCSharp2 (0.08s)+ --- PASS: TestParserCSharp2/basic (0.00s)+ --- PASS: TestParserCSharp2/edge_cases (0.01s)+=== RUN TestParserCSharp3+=== RUN TestParserCSharp3/basic+=== RUN TestParserCSharp3/edge_cases+--- PASS: TestParserCSharp3 (0.08s)+ --- PASS: TestParserCSharp3/basic (0.00s)+ --- PASS: TestParserCSharp3/edge_cases (0.01s)+=== RUN TestParserCSharp4+=== RUN TestParserCSharp4/basic+=== RUN TestParserCSharp4/edge_cases+--- PASS: TestParserCSharp4 (0.08s)+ --- PASS: TestParserCSharp4/basic (0.00s)+ --- PASS: TestParserCSharp4/edge_cases (0.01s)+=== RUN TestParserCSharp5+=== RUN TestParserCSharp5/basic+=== RUN TestParserCSharp5/edge_cases+--- PASS: TestParserCSharp5 (0.08s)+ --- PASS: TestParserCSharp5/basic (0.00s)+ --- PASS: TestParserCSharp5/edge_cases (0.01s)+=== RUN TestParserCSharp6+=== RUN TestParserCSharp6/basic+=== RUN TestParserCSharp6/edge_cases+--- PASS: TestParserCSharp6 (0.08s)+ --- PASS: TestParserCSharp6/basic (0.00s)+ --- PASS: TestParserCSharp6/edge_cases (0.01s)+=== RUN TestParserCSharp7+=== RUN TestParserCSharp7/basic+=== RUN TestParserCSharp7/edge_cases+--- PASS: TestParserCSharp7 (0.08s)+ --- PASS: TestParserCSharp7/basic (0.00s)+ --- PASS: TestParserCSharp7/edge_cases (0.01s)+=== RUN TestParserCSharp8+=== RUN TestParserCSharp8/basic+=== RUN TestParserCSharp8/edge_cases+--- PASS: TestParserCSharp8 (0.08s)+ --- PASS: TestParserCSharp8/basic (0.00s)+ --- PASS: TestParserCSharp8/edge_cases (0.01s)+=== RUN TestParserGo1+=== RUN TestParserGo1/basic+=== RUN TestParserGo1/edge_cases+--- PASS: TestParserGo1 (0.04s)+ --- PASS: TestParserGo1/basic (0.00s)+ --- PASS: TestParserGo1/edge_cases (0.01s)+=== RUN TestParserGo2+=== RUN TestParserGo2/basic+=== RUN TestParserGo2/edge_cases+--- PASS: TestParserGo2 (0.04s)+ --- PASS: TestParserGo2/basic (0.00s)+ --- PASS: TestParserGo2/edge_cases (0.01s)+=== RUN TestParserGo3+=== RUN TestParserGo3/basic+=== RUN TestParserGo3/edge_cases+--- PASS: TestParserGo3 (0.04s)+ --- PASS: TestParserGo3/basic (0.00s)+ --- PASS: TestParserGo3/edge_cases (0.01s)+=== RUN TestParserGo4+=== RUN TestParserGo4/basic+=== RUN TestParserGo4/edge_cases+--- PASS: TestParserGo4 (0.04s)+ --- PASS: TestParserGo4/basic (0.00s)+ --- PASS: TestParserGo4/edge_cases (0.01s)+=== RUN TestParserGo5+=== RUN TestParserGo5/basic+=== RUN TestParserGo5/edge_cases+--- PASS: TestParserGo5 (0.04s)+ --- PASS: TestParserGo5/basic (0.00s)+ --- PASS: TestParserGo5/edge_cases (0.01s)+=== RUN TestParserGo6+=== RUN TestParserGo6/basic+=== RUN TestParserGo6/edge_cases+--- PASS: TestParserGo6 (0.04s)+ --- PASS: TestParserGo6/basic (0.00s)+ --- PASS: TestParserGo6/edge_cases (0.01s)+=== RUN TestParserGo7+=== RUN TestParserGo7/basic+=== RUN TestParserGo7/edge_cases+--- PASS: TestParserGo7 (0.04s)+ --- PASS: TestParserGo7/basic (0.00s)+ --- PASS: TestParserGo7/edge_cases (0.01s)+=== RUN TestParserGo8+=== RUN TestParserGo8/basic+=== RUN TestParserGo8/edge_cases+--- PASS: TestParserGo8 (0.04s)+ --- PASS: TestParserGo8/basic (0.00s)+ --- PASS: TestParserGo8/edge_cases (0.01s)+=== RUN TestParserRust1+=== RUN TestParserRust1/basic+=== RUN TestParserRust1/edge_cases+--- PASS: TestParserRust1 (0.06s)+ --- PASS: TestParserRust1/basic (0.00s)+ --- PASS: TestParserRust1/edge_cases (0.01s)+=== RUN TestParserRust2+=== RUN TestParserRust2/basic+=== RUN TestParserRust2/edge_cases+--- PASS: TestParserRust2 (0.06s)+ --- PASS: TestParserRust2/basic (0.00s)+ --- PASS: TestParserRust2/edge_cases (0.01s)+=== RUN TestParserRust3+=== RUN TestParserRust3/basic+=== RUN TestParserRust3/edge_cases+--- PASS: TestParserRust3 (0.06s)+ --- PASS: TestParserRust3/basic (0.00s)+ --- PASS: TestParserRust3/edge_cases (0.01s)+=== RUN TestParserRust4+=== RUN TestParserRust4/basic+=== RUN TestParserRust4/edge_cases+--- PASS: TestParserRust4 (0.06s)+ --- PASS: TestParserRust4/basic (0.00s)+ --- PASS: TestParserRust4/edge_cases (0.01s)+=== RUN TestParserRust5+=== RUN TestParserRust5/basic+=== RUN TestParserRust5/edge_cases+--- PASS: TestParserRust5 (0.06s)+ --- PASS: TestParserRust5/basic (0.00s)+ --- PASS: TestParserRust5/edge_cases (0.01s)+=== RUN TestParserRust6+=== RUN TestParserRust6/basic+=== RUN TestParserRust6/edge_cases+--- PASS: TestParserRust6 (0.06s)+ --- PASS: TestParserRust6/basic (0.00s)+ --- PASS: TestParserRust6/edge_cases (0.01s)+=== RUN TestParserRust7+=== RUN TestParserRust7/basic+=== RUN TestParserRust7/edge_cases+--- PASS: TestParserRust7 (0.06s)+ --- PASS: TestParserRust7/basic (0.00s)+ --- PASS: TestParserRust7/edge_cases (0.01s)+=== RUN TestParserRust8+=== RUN TestParserRust8/basic+=== RUN TestParserRust8/edge_cases+--- PASS: TestParserRust8 (0.06s)+ --- PASS: TestParserRust8/basic (0.00s)+ --- PASS: TestParserRust8/edge_cases (0.01s)+=== RUN TestPageRankConverges+--- PASS: TestPageRankConverges (0.31s)+=== RUN TestIncrementalUpdate+--- PASS: TestIncrementalUpdate (0.08s)+=== RUN TestBlameIndex+--- FAIL: TestBlameIndex (0.19s)+panic: runtime error: index out of range [3] with length 3 [recovered]+ panic: runtime error: index out of range [3] with length 3++goroutine 41 [running]:+testing.tRunner.func1.2({0x9f1d40, 0xc0003a4018})+ /usr/local/go/src/testing/testing.go:1545 +0x238+testing.tRunner.func1()+ /usr/local/go/src/testing/testing.go:1548 +0x397+panic({0x9f1d40?, 0xc0003a4018?})+ /usr/local/go/src/runtime/panic.go:914 +0x21f+repowise/internal/git.(*BlameIndex).rollup(...)+ /home/dev/repowise/internal/git/blame.go:142+repowise/internal/git.TestBlameIndex(0xc000339520)+ /home/dev/repowise/internal/git/blame_test.go:57 +0x445+testing.tRunner(0xc000339520, 0xa41208)+ /usr/local/go/src/testing/testing.go:1595 +0xff+created by testing.(*T).Run in goroutine 1+ /usr/local/go/src/testing/testing.go:1648 +0x3ad+=== RUN TestCoChangeWindow+--- PASS: TestCoChangeWindow (0.05s)+=== RUN TestHotspotFloors+--- PASS: TestHotspotFloors (0.02s)+=== RUN TestOwnershipRollup+--- PASS: TestOwnershipRollup (0.03s)+=== RUN TestChurnPercentiles+--- PASS: TestChurnPercentiles (0.01s)+FAIL+exit status 2+FAIL repowise/internal/git 1.137s+ok repowise/internal/graph 0.412s+ok repowise/internal/ingestion 0.288s+ok repowise/internal/health 0.157sdiff --git a/tests/fixtures/distill/jest_fail.txt b/tests/fixtures/distill/jest_fail.txtnew file mode 100644index 000000000..c07d11c40--- /dev/null+++ b/tests/fixtures/distill/jest_fail.txt@@ -0,0 +1,112 @@+> [email protected] test+> jest --ci++PASS src/components/graph/__tests__/layout.test.tsx+PASS src/components/docs/__tests__/docs-viewer.test.tsx+PASS src/lib/__tests__/format.test.ts+PASS src/lib/__tests__/cn.test.ts+PASS src/components/c4/__tests__/level-switch.test.tsx+PASS src/components/graph/__tests__/minimap.test.tsx+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+ ✓ cleans up subscriptions on unmount (17 ms)+ ✓ formats large numbers (20 ms)+ ✓ syncs state to the URL (23 ms)+PASS src/components/graph/__tests__/edge-bundling.test.tsx+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+ ✓ cleans up subscriptions on unmount (17 ms)+PASS src/components/health/__tests__/trend-chart.test.tsx+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+ ✓ cleans up subscriptions on unmount (17 ms)+ ✓ formats large numbers (20 ms)+PASS src/components/commits/__tests__/commit-table.test.tsx+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+ ✓ cleans up subscriptions on unmount (17 ms)+ ✓ formats large numbers (20 ms)+ ✓ syncs state to the URL (23 ms)+ ✓ debounces rapid updates (26 ms)+PASS src/components/decisions/__tests__/decision-card.test.tsx+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+PASS src/lib/__tests__/token-estimate.test.ts+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+ ✓ cleans up subscriptions on unmount (17 ms)+PASS src/lib/__tests__/url-state.test.ts+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+ ✓ cleans up subscriptions on unmount (17 ms)+ ✓ formats large numbers (20 ms)+ ✓ syncs state to the URL (23 ms)+PASS src/hooks/__tests__/use-repo-data.test.ts+ ✓ renders without crashing (2 ms)+ ✓ matches accessibility roles (5 ms)+ ✓ handles empty data (8 ms)+ ✓ responds to prop changes (11 ms)+ ✓ memoizes expensive layout (14 ms)+ ✓ cleans up subscriptions on unmount (17 ms)+ ✓ formats large numbers (20 ms)+FAIL src/components/chat/__tests__/chat-interface.test.tsx+ ● ChatInterface › renders streaming tokens incrementally++ expect(element).toHaveTextContent()++ Expected element to have text content:+ analyzing repository structure+ Received:+ analyzing repository structur++ 45 | await act(() => stream.push(chunk));+ 46 | const bubble = screen.getByTestId("assistant-bubble");+ > 47 | expect(bubble).toHaveTextContent("analyzing repository structure");+ | ^+ 48 | });+ 49 |+ 50 | it("retries on transient SSE disconnect", async () => {++ at Object.<anonymous> (src/components/chat/__tests__/chat-interface.test.tsx:47:20)++ ● ChatInterface › retries on transient SSE disconnect++ TypeError: Cannot read properties of undefined (reading 'reconnect')++ 58 | server.dropConnection();+ > 59 | await waitFor(() => expect(client.sse.reconnect).toHaveBeenCalled());+ | ^+ 60 | });++ at Object.<anonymous> (src/components/chat/__tests__/chat-interface.test.tsx:59:39)++PASS src/components/health/__tests__/biomarkers.test.tsx+PASS src/components/commits/__tests__/risk-badge.test.tsx+PASS src/app/repos/__tests__/page.test.tsx++Test Suites: 1 failed, 16 passed, 17 total+Tests: 2 failed, 117 passed, 119 total+Snapshots: 0 total+Time: 14.382 s+Ran all test suites.diff --git a/tests/fixtures/distill/ls_la.txt b/tests/fixtures/distill/ls_la.txtnew file mode 100644index 000000000..964045a80--- /dev/null+++ b/tests/fixtures/distill/ls_la.txt@@ -0,0 +1,129 @@+total 540+drwxr-xr-x 1 ragha 197609 0 Jun 3 17:28 .+drwxr-xr-x 1 ragha 197609 0 Jun 3 17:28 ..+-rwxr-xr-x 1 ragha 197609 379 Jun 3 17:28 acorn+-rw-r--r-- 1 ragha 197609 320 Jun 3 17:28 acorn.cmd+-rwxr-xr-x 1 ragha 197609 785 Jun 3 17:28 acorn.ps1+-rwxr-xr-x 1 ragha 197609 387 Jun 3 17:28 astring+-rw-r--r-- 1 ragha 197609 324 Jun 3 17:28 astring.cmd+-rwxr-xr-x 1 ragha 197609 801 Jun 3 17:28 astring.ps1+-rwxr-xr-x 1 ragha 197609 423 Jun 3 17:28 baseline-browser-mapping+-rw-r--r-- 1 ragha 197609 342 Jun 3 17:28 baseline-browser-mapping.cmd+-rwxr-xr-x 1 ragha 197609 873 Jun 3 17:28 baseline-browser-mapping.ps1+-rwxr-xr-x 1 ragha 197609 387 Jun 3 17:28 browserslist+-rw-r--r-- 1 ragha 197609 324 Jun 3 17:28 browserslist.cmd+-rwxr-xr-x 1 ragha 197609 801 Jun 3 17:28 browserslist.ps1+-rwxr-xr-x 1 ragha 197609 383 Jun 3 17:28 cssesc+-rw-r--r-- 1 ragha 197609 322 Jun 3 17:28 cssesc.cmd+-rwxr-xr-x 1 ragha 197609 793 Jun 3 17:28 cssesc.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 csv2json+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 csv2json.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 csv2json.ps1+-rwxr-xr-x 1 ragha 197609 391 Jun 3 17:28 csv2tsv+-rw-r--r-- 1 ragha 197609 326 Jun 3 17:28 csv2tsv.cmd+-rwxr-xr-x 1 ragha 197609 809 Jun 3 17:28 csv2tsv.ps1+-rwxr-xr-x 1 ragha 197609 391 Jun 3 17:28 dsv2dsv+-rw-r--r-- 1 ragha 197609 326 Jun 3 17:28 dsv2dsv.cmd+-rwxr-xr-x 1 ragha 197609 809 Jun 3 17:28 dsv2dsv.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 dsv2json+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 dsv2json.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 dsv2json.ps1+-rwxr-xr-x 1 ragha 197609 387 Jun 3 17:28 esbuild+-rw-r--r-- 1 ragha 197609 324 Jun 3 17:28 esbuild.cmd+-rwxr-xr-x 1 ragha 197609 801 Jun 3 17:28 esbuild.ps1+-rwxr-xr-x 1 ragha 197609 389 Jun 3 17:28 eslint+-rw-r--r-- 1 ragha 197609 325 Jun 3 17:28 eslint.cmd+-rwxr-xr-x 1 ragha 197609 805 Jun 3 17:28 eslint.ps1+-rwxr-xr-x 1 ragha 197609 391 Jun 3 17:28 jiti+-rw-r--r-- 1 ragha 197609 326 Jun 3 17:28 jiti.cmd+-rwxr-xr-x 1 ragha 197609 809 Jun 3 17:28 jiti.ps1+-rwxr-xr-x 1 ragha 197609 379 Jun 3 17:28 jsesc+-rw-r--r-- 1 ragha 197609 320 Jun 3 17:28 jsesc.cmd+-rwxr-xr-x 1 ragha 197609 785 Jun 3 17:28 jsesc.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 json2csv+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 json2csv.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 json2csv.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 json2dsv+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 json2dsv.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 json2dsv.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 json2tsv+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 json2tsv.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 json2tsv.ps1+-rwxr-xr-x 1 ragha 197609 381 Jun 3 17:28 json5+-rw-r--r-- 1 ragha 197609 321 Jun 3 17:28 json5.cmd+-rwxr-xr-x 1 ragha 197609 789 Jun 3 17:28 json5.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 js-yaml+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 js-yaml.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 js-yaml.ps1+-rwxr-xr-x 1 ragha 197609 373 Jun 3 17:28 katex+-rw-r--r-- 1 ragha 197609 317 Jun 3 17:28 katex.cmd+-rwxr-xr-x 1 ragha 197609 773 Jun 3 17:28 katex.ps1+-rwxr-xr-x 1 ragha 197609 387 Jun 3 17:28 loose-envify+-rw-r--r-- 1 ragha 197609 324 Jun 3 17:28 loose-envify.cmd+-rwxr-xr-x 1 ragha 197609 801 Jun 3 17:28 loose-envify.ps1+-rwxr-xr-x 1 ragha 197609 389 Jun 3 17:28 lz-string+-rw-r--r-- 1 ragha 197609 325 Jun 3 17:28 lz-string.cmd+-rwxr-xr-x 1 ragha 197609 805 Jun 3 17:28 lz-string.ps1+-rwxr-xr-x 1 ragha 197609 389 Jun 3 17:28 marked+-rw-r--r-- 1 ragha 197609 325 Jun 3 17:28 marked.cmd+-rwxr-xr-x 1 ragha 197609 805 Jun 3 17:28 marked.ps1+-rwxr-xr-x 1 ragha 197609 391 Jun 3 17:28 nanoid+-rw-r--r-- 1 ragha 197609 326 Jun 3 17:28 nanoid.cmd+-rwxr-xr-x 1 ragha 197609 809 Jun 3 17:28 nanoid.ps1+-rwxr-xr-x 1 ragha 197609 403 Jun 3 17:28 napi-postinstall+-rw-r--r-- 1 ragha 197609 332 Jun 3 17:28 napi-postinstall.cmd+-rwxr-xr-x 1 ragha 197609 833 Jun 3 17:28 napi-postinstall.ps1+-rwxr-xr-x 1 ragha 197609 385 Jun 3 17:28 next+-rw-r--r-- 1 ragha 197609 323 Jun 3 17:28 next.cmd+-rwxr-xr-x 1 ragha 197609 797 Jun 3 17:28 next.ps1+-rwxr-xr-x 1 ragha 197609 389 Jun 3 17:28 node-which+-rw-r--r-- 1 ragha 197609 325 Jun 3 17:28 node-which.cmd+-rwxr-xr-x 1 ragha 197609 805 Jun 3 17:28 node-which.ps1+-rwxr-xr-x 1 ragha 197609 415 Jun 3 17:28 parser+-rw-r--r-- 1 ragha 197609 338 Jun 3 17:28 parser.cmd+-rwxr-xr-x 1 ragha 197609 857 Jun 3 17:28 parser.ps1+-rwxr-xr-x 1 ragha 197609 387 Jun 3 17:28 resolve+-rw-r--r-- 1 ragha 197609 324 Jun 3 17:28 resolve.cmd+-rwxr-xr-x 1 ragha 197609 801 Jun 3 17:28 resolve.ps1+-rwxr-xr-x 1 ragha 197609 389 Jun 3 17:28 rolldown+-rw-r--r-- 1 ragha 197609 325 Jun 3 17:28 rolldown.cmd+-rwxr-xr-x 1 ragha 197609 805 Jun 3 17:28 rolldown.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 rollup+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 rollup.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 rollup.ps1+-rwxr-xr-x 1 ragha 197609 389 Jun 3 17:28 semver+-rw-r--r-- 1 ragha 197609 325 Jun 3 17:28 semver.cmd+-rwxr-xr-x 1 ragha 197609 805 Jun 3 17:28 semver.ps1+-rwxr-xr-x 1 ragha 197609 381 Jun 3 17:28 tldts+-rw-r--r-- 1 ragha 197609 321 Jun 3 17:28 tldts.cmd+-rwxr-xr-x 1 ragha 197609 789 Jun 3 17:28 tldts.ps1+-rwxr-xr-x 1 ragha 197609 385 Jun 3 17:28 tsc+-rw-r--r-- 1 ragha 197609 323 Jun 3 17:28 tsc.cmd+-rwxr-xr-x 1 ragha 197609 797 Jun 3 17:28 tsc.ps1+-rwxr-xr-x 1 ragha 197609 395 Jun 3 17:28 tsserver+-rw-r--r-- 1 ragha 197609 328 Jun 3 17:28 tsserver.cmd+-rwxr-xr-x 1 ragha 197609 817 Jun 3 17:28 tsserver.ps1+-rwxr-xr-x 1 ragha 197609 391 Jun 3 17:28 tsv2csv+-rw-r--r-- 1 ragha 197609 326 Jun 3 17:28 tsv2csv.cmd+-rwxr-xr-x 1 ragha 197609 809 Jun 3 17:28 tsv2csv.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 tsv2json+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 tsv2json.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 tsv2json.ps1+-rwxr-xr-x 1 ragha 197609 407 Jun 3 17:28 update-browserslist-db+-rw-r--r-- 1 ragha 197609 334 Jun 3 17:28 update-browserslist-db.cmd+-rwxr-xr-x 1 ragha 197609 841 Jun 3 17:28 update-browserslist-db.ps1+-rwxr-xr-x 1 ragha 197609 393 Jun 3 17:28 uuid+-rw-r--r-- 1 ragha 197609 327 Jun 3 17:28 uuid.cmd+-rwxr-xr-x 1 ragha 197609 813 Jun 3 17:28 uuid.ps1+-rwxr-xr-x 1 ragha 197609 381 Jun 3 17:28 vite+-rw-r--r-- 1 ragha 197609 321 Jun 3 17:28 vite.cmd+-rwxr-xr-x 1 ragha 197609 789 Jun 3 17:28 vite.ps1+-rwxr-xr-x 1 ragha 197609 383 Jun 3 17:28 vitest+-rw-r--r-- 1 ragha 197609 322 Jun 3 17:28 vitest.cmd+-rwxr-xr-x 1 ragha 197609 793 Jun 3 17:28 vitest.ps1+-rwxr-xr-x 1 ragha 197609 401 Jun 3 17:28 why-is-node-running+-rw-r--r-- 1 ragha 197609 331 Jun 3 17:28 why-is-node-running.cmd+-rwxr-xr-x 1 ragha 197609 829 Jun 3 17:28 why-is-node-running.ps1+-rwxr-xr-x 1 ragha 197609 373 Jun 3 17:28 yaml+-rw-r--r-- 1 ragha 197609 317 Jun 3 17:28 yaml.cmd+-rwxr-xr-x 1 ragha 197609 773 Jun 3 17:28 yaml.ps1diff --git a/tests/fixtures/distill/npm_build.txt b/tests/fixtures/distill/npm_build.txtnew file mode 100644index 000000000..ddbec66ea--- /dev/null+++ b/tests/fixtures/distill/npm_build.txt@@ -0,0 +1,99 @@++> [email protected] build+> npm run build --workspaces --if-present+++> [email protected] build+> next build++ ▲ Next.js 15.5.18+ - Environments: .env.local+ - Experiments (use with caution):+ · optimizePackageImports++ Creating an optimized production build ...+ ✓ Compiled successfully in 10.9s+ Linting and checking validity of types ...+ Collecting page data ...+ Generating static pages (0/8) ...+ Generating static pages (2/8)+node.exe : [TypeError: fetch failed] {+At line:1 char:1++ & "C:\Program Files\nodejs/node.exe" "C:\Program Files\nodejs/node_mo ...++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ + CategoryInfo : NotSpecified: ([TypeError: fetch failed] {:String) [], RemoteException+ + FullyQualifiedErrorId : NativeCommandError++ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+[TypeError: fetch failed] {+ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+[TypeError: fetch failed] {+ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+[TypeError: fetch failed] {+ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+[TypeError: fetch failed] {+ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+[TypeError: fetch failed] {+ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+[TypeError: fetch failed] {+ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+[TypeError: fetch failed] {+ [cause]: [AggregateError: ] { code: 'ECONNREFUSED' }+}+ Generating static pages (4/8)+ Generating static pages (6/8)+ ✓ Generating static pages (8/8)+ Finalizing page optimization ...+ Collecting build traces ...++Route (app) Size First Load JS Revalidate Expire+┌ ○ / 4.68 kB 147 kB 30s 1y+├ ○ /_not-found 1 kB 109 kB+├ ƒ /repos/[id] 19.9 kB 189 kB+├ ƒ /repos/[id]/blast-radius 9.85 kB 134 kB+├ ƒ /repos/[id]/c4 35.7 kB 723 kB+├ ƒ /repos/[id]/commits 9.91 kB 145 kB+├ ƒ /repos/[id]/costs 83.6 kB 320 kB+├ ƒ /repos/[id]/coverage 172 B 108 kB+├ ƒ /repos/[id]/dead-code 5.58 kB 170 kB+├ ƒ /repos/[id]/decisions 7.45 kB 620 kB+├ ƒ /repos/[id]/decisions/[decisionId] 9.58 kB 201 kB+├ ƒ /repos/[id]/docs 22 kB 221 kB+├ ƒ /repos/[id]/docs/coverage 9.52 kB 230 kB+├ ƒ /repos/[id]/graph 48 kB 677 kB+├ ƒ /repos/[id]/health 12.3 kB 144 kB+├ ƒ /repos/[id]/health/coverage 5.09 kB 158 kB+├ ƒ /repos/[id]/health/refactoring-targets 5.16 kB 158 kB+├ ƒ /repos/[id]/health/trend 6.09 kB 131 kB+├ ƒ /repos/[id]/hotspots 3.17 kB 256 kB+├ ƒ /repos/[id]/modules/[path] 8.45 kB 133 kB+├ ƒ /repos/[id]/overview 11.6 kB 332 kB+├ ƒ /repos/[id]/owners 8.78 kB 161 kB+├ ƒ /repos/[id]/owners/[owner] 9.77 kB 134 kB+├ ƒ /repos/[id]/ownership 13.1 kB 276 kB+├ ƒ /repos/[id]/risk 21 kB 341 kB+├ ƒ /repos/[id]/search 8.47 kB 140 kB+├ ƒ /repos/[id]/security 405 B 108 kB+├ ƒ /repos/[id]/settings 14.9 kB 191 kB+├ ƒ /repos/[id]/symbols 4.93 kB 177 kB+├ ƒ /repos/[id]/wiki/[...slug] 9.02 kB 179 kB+├ ○ /settings 7.4 kB 164 kB+├ ○ /workspace 11.7 kB 191 kB 30s 1y+├ ○ /workspace/co-changes 2.52 kB 126 kB+└ ○ /workspace/contracts 4.65 kB 126 kB++ First Load JS shared by all 108 kB+ ├ chunks/1255-87391423b0c57e83.js 45.9 kB+ ├ chunks/4bd1b696-100b9d70ed4e49c1.js 54.2 kB+ └ other shared chunks (total) 7.36 kB+++○ (Static) prerendered as static content+ƒ (Dynamic) server-rendered on demand+diff --git a/tests/fixtures/distill/pytest_fail.txt b/tests/fixtures/distill/pytest_fail.txtnew file mode 100644index 000000000..59265b68c--- /dev/null+++ b/tests/fixtures/distill/pytest_fail.txt@@ -0,0 +1,724 @@+============================= test session starts =============================+platform win32 -- Python 3.13.5, pytest-9.0.3, pluggy-1.6.0 -- C:\Users\ragha\Desktop\repowise\.venv\Scripts\python.exe+rootdir: C:\Users\ragha\Desktop\repowise+configfile: pyproject.toml+plugins: anyio-4.13.0, asyncio-1.3.0, cov-7.1.0, respx-0.22.0, time-machine-2.19.0+asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function+collecting ... collected 670 items++tests/unit/analysis/test_change_risk.py::test_score_is_bounded_and_levelled PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_logit_is_exact_sum_of_driver_contributions PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_larger_diff_scores_higher PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_author_experience_is_protective PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_unknown_experience_is_neutral PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_top_drivers_sorted_by_magnitude PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_features_from_file_changes_aggregates_diffusion PASSED [ 1%]+tests/unit/analysis/test_change_risk.py::test_extract_commit_features_counts_diffusion PASSED [ 1%]+tests/unit/analysis/test_change_risk.py::test_extract_filters_by_extension PASSED [ 1%]+tests/unit/analysis/test_change_risk.py::test_author_experience_accrues PASSED [ 1%]+tests/unit/analysis/test_change_risk.py::test_extract_range_features_aggregates PASSED [ 1%]+tests/unit/analysis/test_change_risk.py::test_score_change_on_real_commit PASSED [ 1%]+tests/unit/analysis/test_change_risk_normalize.py::test_empty_distribution_is_low_zero PASSED [ 1%]+tests/unit/analysis/test_change_risk_normalize.py::test_none_score_is_neutral PASSED [ 2%]+tests/unit/analysis/test_change_risk_normalize.py::test_none_values_dropped_from_distribution PASSED [ 2%]+tests/unit/analysis/test_change_risk_normalize.py::test_midrank_percentile_orders_monotonically PASSED [ 2%]+tests/unit/analysis/test_change_risk_normalize.py::test_ties_share_one_percentile PASSED [ 2%]+tests/unit/analysis/test_change_risk_normalize.py::test_priority_terciles PASSED [ 2%]+tests/unit/analysis/test_change_risk_normalize.py::test_priority_is_repo_relative_not_absolute PASSED [ 2%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_in_degree_positive_is_reachable PASSED [ 2%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_main_carrier_is_reachable PASSED [ 3%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_winmain_carrier_is_reachable PASSED [ 3%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_libfuzzer_entry_carrier_is_reachable PASSED [ 3%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_header_with_referenced_symbol_is_reachable PASSED [ 3%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_header_with_implements_edge_is_reachable PASSED [ 3%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_internal_header_rescued_by_sibling_with_importer PASSED [ 3%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_conditional_alt_pair_rescued PASSED [ 4%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_sibling_of_main_file_is_reachable PASSED [ 4%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_orphan_unrelated_header_is_unreachable PASSED [ 4%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_orphan_source_with_no_sibling_signal_is_unreachable PASSED [ 4%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_apps_tree_never_flagged PASSED [ 4%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_demos_tree_never_flagged PASSED [ 4%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_examples_tree_never_flagged PASSED [ 4%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_benchmarks_tree_never_flagged PASSED [ 5%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_tools_tree_never_flagged PASSED [ 5%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_tests_perf_fuzz_unit_manual_never_flagged PASSED [ 5%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_test_suffix_files_never_flagged PASSED [ 5%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_port_example_never_flagged PASSED [ 5%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_generated_qt_protobuf_grpc_globs PASSED [ 5%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_generated_yacc_flex_swig_globs PASSED [ 5%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_external_extern_contrib_submodules_globs PASSED [ 6%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_ordinary_source_not_flagged PASSED [ 6%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_operator_overloads_protected PASSED [ 6%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_stl_customization_points_protected PASSED [ 6%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_coroutine_machinery_protected PASSED [ 6%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_constructor_destructor_protected PASSED [ 6%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_conversion_operator_protected PASSED [ 7%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_unrelated_language_not_protected PASSED [ 7%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_random_user_function_not_protected PASSED [ 7%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEntryPointSymbols::test_libfuzzer_entry_recognised PASSED [ 7%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEntryPointSymbols::test_windows_main_variants_recognised PASSED [ 7%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_main_carrier_not_flagged_unreachable PASSED [ 7%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_public_header_with_type_use_not_flagged_unreachable PASSED [ 7%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_operator_overload_not_flagged_unused_export PASSED [ 8%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_apps_tree_never_flag_short_circuits PASSED [ 8%]+tests/unit/analysis/test_decision_provenance.py::test_source_rank_ladder_ordering PASSED [ 8%]+tests/unit/analysis/test_decision_provenance.py::test_git_archaeology_aliases_commit_rank PASSED [ 8%]+tests/unit/analysis/test_decision_provenance.py::test_unknown_source_lowest_rank PASSED [ 8%]+tests/unit/analysis/test_decision_provenance.py::test_cli_outranks_adr PASSED [ 8%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_rises_with_rank PASSED [ 8%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_rises_with_corroboration PASSED [ 9%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_decays_for_weak_verification PASSED [ 9%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_bounded PASSED [ 9%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_exact_ignores_whitespace_and_case PASSED [ 9%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_fuzzy_on_paraphrase PASSED [ 9%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_unverified_on_hallucination PASSED [ 9%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_unverified_without_source PASSED [ 10%]+tests/unit/analysis/test_decision_provenance.py::test_gate_keeps_grounded_decision PASSED [ 10%]+tests/unit/analysis/test_decision_provenance.py::test_gate_rejects_fully_hallucinated_decision PASSED [ 10%]+tests/unit/analysis/test_decision_provenance.py::test_gate_drops_only_the_hallucinated_field PASSED [ 10%]+tests/unit/analysis/test_decision_provenance.py::test_gate_keeps_unverifiable_when_no_source_text PASSED [ 10%]+tests/unit/analysis/test_decision_sources.py::test_discover_adrs_parses_nygard_template PASSED [ 10%]+tests/unit/analysis/test_decision_sources.py::test_discover_adrs_maps_superseded_status_from_frontmatter PASSED [ 10%]+tests/unit/analysis/test_decision_sources.py::test_mine_changelog_extracts_decision_sections PASSED [ 11%]+tests/unit/analysis/test_decision_sources.py::test_mine_changelog_finds_changelog_under_docs PASSED [ 11%]+tests/unit/analysis/test_decision_sources.py::test_extract_all_runs_deterministic_sources_and_gates PASSED [ 11%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_entry_package_sibling_is_reachable PASSED [ 11%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_imported_sibling_makes_package_reachable PASSED [ 11%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_orphaned_package_is_unreachable PASSED [ 11%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_func_init_alone_does_not_rescue_package PASSED [ 11%]+tests/unit/analysis/test_go_reachability.py::TestGoUnreachableFiles::test_entry_package_helper_not_flagged PASSED [ 12%]+tests/unit/analysis/test_go_reachability.py::TestGoUnreachableFiles::test_orphan_package_still_flagged PASSED [ 12%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_test_file PASSED [ 12%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_cmd_main PASSED [ 12%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_root_main PASSED [ 12%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_doc_and_docs_stubs PASSED [ 12%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_magefile PASSED [ 12%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_generated_code PASSED [ 13%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_ordinary_go_file_not_flagged PASSED [ 13%]+tests/unit/analysis/test_go_reachability.py::TestGoEntrySymbols::test_init_and_testmain_are_entry_symbols PASSED [ 13%]+tests/unit/analysis/test_go_reachability.py::TestGoDynamicMarkers::test_go_directives_present PASSED [ 13%]+tests/unit/analysis/test_go_reachability.py::TestGoUnusedInternals::test_uncalled_private_go_symbol_is_flagged PASSED [ 13%]+tests/unit/analysis/test_go_reachability.py::TestGoUnusedInternals::test_private_type_kinds_not_flagged_as_internal PASSED [ 13%]+tests/unit/analysis/test_go_reachability.py::TestGoUnusedInternals::test_called_private_go_symbol_not_flagged PASSED [ 14%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_bundle_outputs PASSED [ 14%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_minified PASSED [ 14%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_livereload_generated_and_shim PASSED [ 14%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_wasm_exec_glue PASSED [ 14%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_ordinary_js_not_flagged PASSED [ 14%]+tests/unit/analysis/test_js_never_flag.py::TestVendoredCNeverFlag::test_deps_vendor_third_party PASSED [ 14%]+tests/unit/analysis/test_js_never_flag.py::TestVendoredCNeverFlag::test_live_c_not_flagged PASSED [ 15%]+tests/unit/analysis/test_jsx_namespace_exempt.py::TestJsxNamespaceExemption::test_intrinsic_elements_in_jsx_namespace_not_flagged PASSED [ 15%]+tests/unit/analysis/test_jsx_namespace_exempt.py::TestJsxNamespaceExemption::test_whitelist_name_outside_jsx_namespace_still_flagged PASSED [ 15%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_in_degree_positive_is_reachable PASSED [ 15%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_sibling_with_importer_rescues PASSED [ 15%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_stereotype_annotated_class_is_reachable PASSED [ 15%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_spring_boot_application_is_reachable PASSED [ 15%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_main_method_is_reachable PASSED [ 16%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_fqn_qualified_annotation_recognised PASSED [ 16%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_orphan_non_annotated_class_is_unreachable PASSED [ 16%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_kotlin_object_with_companion_main_is_reachable PASSED [ 16%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_module_info_never_flagged PASSED [ 16%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_package_info_never_flagged PASSED [ 16%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_caffeine_test_source_sets_never_flagged PASSED [ 17%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_integration_test_source_set PASSED [ 17%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_test_suffix_files PASSED [ 17%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_generated_roots_never_flagged PASSED [ 17%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_ordinary_main_source_not_flagged PASSED [ 17%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_equals_hashcode_protected PASSED [ 17%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_serialization_protected PASSED [ 17%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_kotlin_data_class_synthesised_protected PASSED [ 18%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_enum_helpers_protected PASSED [ 18%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_unrelated_language_not_protected PASSED [ 18%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_spring_stereotypes_present PASSED [ 18%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_routing_annotations_present PASSED [ 18%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_test_markers_present PASSED [ 18%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_lifecycle_and_messaging_present PASSED [ 18%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmEndToEnd::test_service_annotated_class_not_flagged_unreachable PASSED [ 19%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmEndToEnd::test_module_info_not_flagged PASSED [ 19%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmEndToEnd::test_private_post_construct_method_not_flagged_internal PASSED [ 19%]+tests/unit/analysis/test_jvm_reachability.py::TestWorkspaceNeverFlag::test_is_never_flag_node_attr_short_circuits_findings PASSED [ 19%]+tests/unit/analysis/test_jvm_reachability.py::TestHeritageEdgeRescue::test_extended_only_class_is_not_unused_export PASSED [ 19%]+tests/unit/analysis/test_jvm_reachability.py::TestHeritageEdgeRescue::test_implemented_only_interface_is_not_unused_export PASSED [ 19%]+tests/unit/analysis/test_jvm_reachability.py::TestHeritageEdgeRescue::test_type_use_only_class_is_not_unused_export PASSED [ 20%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_loads_valid_json PASSED [ 20%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_returns_none_for_missing_file PASSED [ 20%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_returns_none_for_invalid_json PASSED [ 20%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_handles_minimal_json PASSED [ 20%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_fingerprint_not_loaded PASSED [ 20%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_same_graph_same_fingerprint PASSED [ 20%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_different_nodes_different_fingerprint PASSED [ 21%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_different_edges_different_fingerprint PASSED [ 21%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_different_communities_different_fingerprint PASSED [ 21%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_skip_when_fingerprint_matches PASSED [ 21%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_regenerate_when_fingerprint_differs PASSED [ 21%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_force_bypasses_fingerprint PASSED [ 21%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_skip_fails_gracefully_if_file_missing PASSED [ 21%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_skip_fails_gracefully_if_file_corrupt PASSED [ 22%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_file_nodes PASSED [ 22%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_all_node_types PASSED [ 22%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_test_file_tagged PASSED [ 22%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_entry_point_tagged PASSED [ 22%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_import_edges PASSED [ 22%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_tested_by_edges PASSED [ 22%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_layers_from_communities PASSED [ 23%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_layers_contain_node_ids PASSED [ 23%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_no_communities_gives_empty_layers PASSED [ 23%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_project_metadata PASSED [ 23%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_simple PASSED [ 23%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_moderate PASSED [ 23%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_complex_by_symbols PASSED [ 24%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_complex_by_lines PASSED [ 24%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_edge_simple PASSED [ 24%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_edge_complex PASSED [ 24%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_python_file PASSED [ 24%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_config_by_extension PASSED [ 24%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_config_by_flag PASSED [ 24%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_dockerfile PASSED [ 25%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_markdown PASSED [ 25%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_makefile PASSED [ 25%]+tests/unit/analysis/test_knowledge_graph.py::TestSlugify::test_normal PASSED [ 25%]+tests/unit/analysis/test_knowledge_graph.py::TestSlugify::test_special_chars PASSED [ 25%]+tests/unit/analysis/test_knowledge_graph.py::TestSlugify::test_empty PASSED [ 25%]+tests/unit/analysis/test_knowledge_graph.py::TestFingerprint::test_stability PASSED [ 25%]+tests/unit/analysis/test_knowledge_graph.py::TestFingerprint::test_changes_on_graph_change PASSED [ 26%]+tests/unit/analysis/test_knowledge_graph.py::TestFingerprint::test_length PASSED [ 26%]+tests/unit/analysis/test_knowledge_graph.py::TestToDict::test_schema PASSED [ 26%]+tests/unit/analysis/test_knowledge_graph.py::TestToDict::test_roundtrip_json PASSED [ 26%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_build_rs_never_flagged PASSED [ 26%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_examples_never_flagged PASSED [ 26%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_benches_never_flagged PASSED [ 27%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_tests_dir_never_flagged PASSED [ 27%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_bin_target_never_flagged PASSED [ 27%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_fuzz_target_never_flagged PASSED [ 27%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverPackageDirs::test_tests_dir_excluded PASSED [ 27%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverPackageDirs::test_benches_dir_excluded PASSED [ 27%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverPackageDirs::test_fuzz_dir_excluded PASSED [ 27%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustDynamicMarkers::test_proc_macro_detected PASSED [ 28%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustDynamicMarkers::test_doc_hidden_detected PASSED [ 28%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroCrateDetection::test_proc_macro_crate_detected PASSED [ 28%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroCrateDetection::test_non_proc_macro_crate_not_detected PASSED [ 28%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroCrateDetection::test_proc_macro_parsed_from_toml PASSED [ 28%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustUnusedInternalsSkipped::test_rust_private_function_not_flagged PASSED [ 28%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustUnusedInternalsSkipped::test_python_private_function_still_flagged PASSED [ 28%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_proc_macro_function_not_flagged PASSED [ 29%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_proc_macro_derive_not_flagged PASSED [ 29%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_proc_macro_attribute_not_flagged PASSED [ 29%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_regular_rust_public_function_still_flagged PASSED [ 29%]+tests/unit/analysis/test_ts_never_flag.py::TestTestSpecFiles::test_test_suffix_variants PASSED [ 29%]+tests/unit/analysis/test_ts_never_flag.py::TestTestSpecFiles::test_tests_and_mocks_dirs PASSED [ 29%]+tests/unit/analysis/test_ts_never_flag.py::TestTestSpecFiles::test_ordinary_source_not_flagged PASSED [ 30%]+tests/unit/analysis/test_ts_never_flag.py::TestStoriesAndBench::test_storybook_stories PASSED [ 30%]+tests/unit/analysis/test_ts_never_flag.py::TestStoriesAndBench::test_bench_files PASSED [ 30%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_next_env_and_gen PASSED [ 30%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_next_app_router_conventions PASSED [ 30%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_remix_entries PASSED [ 30%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_sveltekit_conventions PASSED [ 30%]+tests/unit/analysis/test_ts_never_flag.py::TestNeverFlagDoesNotLeak::test_python_not_affected PASSED [ 31%]+tests/unit/analysis/test_ts_never_flag.py::TestNeverFlagDoesNotLeak::test_go_not_affected PASSED [ 31%]+tests/unit/analysis/test_ts_never_flag.py::TestEntryPointSymbolNames::test_nextjs_route_exports_included PASSED [ 31%]+tests/unit/analysis/test_ts_never_flag.py::TestEntryPointSymbolNames::test_remix_route_exports_included PASSED [ 31%]+tests/unit/analysis/test_ts_never_flag.py::TestEntryPointSymbolNames::test_common_names_excluded PASSED [ 31%]+tests/unit/generation/test_agents_md.py::test_agents_md_renders_repowise_workflows PASSED [ 31%]+tests/unit/generation/test_agents_md.py::test_agents_md_writes_repo_root_file PASSED [ 31%]+tests/unit/generation/test_agents_md.py::test_agents_md_preserves_user_content PASSED [ 32%]+tests/unit/generation/test_agents_md.py::test_agents_md_replaces_only_managed_section PASSED [ 32%]+tests/unit/generation/test_api_contract_detector.py::test_detects_fastapi_router_via_import PASSED [ 32%]+tests/unit/generation/test_api_contract_detector.py::test_detects_fastapi_via_method_decorator PASSED [ 32%]+tests/unit/generation/test_api_contract_detector.py::test_skips_python_file_without_fastapi PASSED [ 32%]+tests/unit/generation/test_api_contract_detector.py::test_detects_aspnet_controller_via_inheritance PASSED [ 32%]+tests/unit/generation/test_api_contract_detector.py::test_detects_aspnet_controller_via_attribute PASSED [ 32%]+tests/unit/generation/test_api_contract_detector.py::test_already_flagged_file_is_untouched PASSED [ 33%]+tests/unit/generation/test_api_contract_detector.py::test_unknown_language_skipped PASSED [ 33%]+tests/unit/generation/test_categories.py::test_doc_files PASSED [ 33%]+tests/unit/generation/test_categories.py::test_pipeline_files PASSED [ 33%]+tests/unit/generation/test_categories.py::test_data_files PASSED [ 33%]+tests/unit/generation/test_categories.py::test_config_files PASSED [ 33%]+tests/unit/generation/test_categories.py::test_code_default PASSED [ 34%]+tests/unit/generation/test_categories.py::test_resolution_order_doc_beats_pipeline PASSED [ 34%]+tests/unit/generation/test_context_assembler.py::test_estimate_tokens_empty_string PASSED [ 34%]+tests/unit/generation/test_context_assembler.py::test_estimate_tokens_known_string PASSED [ 34%]+tests/unit/generation/test_context_assembler.py::test_estimate_tokens_short_string PASSED [ 34%]+tests/unit/generation/test_context_assembler.py::test_trim_to_budget_long_text_truncated PASSED [ 34%]+tests/unit/generation/test_context_assembler.py::test_trim_to_budget_short_text_unchanged PASSED [ 34%]+tests/unit/generation/test_context_assembler.py::test_trim_to_budget_zero_remaining PASSED [ 35%]+tests/unit/generation/test_context_assembler.py::test_assemble_file_page_returns_context PASSED [ 35%]+tests/unit/generation/test_context_assembler.py::test_assemble_file_page_dependents_from_graph PASSED [ 35%]+tests/unit/generation/test_context_assembler.py::test_assemble_file_page_dependencies_from_graph PASSED [ 35%]+tests/unit/generation/test_context_assembler.py::test_assemble_file_page_token_budget_respected PASSED [ 35%]+tests/unit/generation/test_context_assembler.py::test_assemble_file_page_private_undocumented_dropped_first PASSED [ 35%]+tests/unit/generation/test_context_assembler.py::test_assemble_symbol_spotlight_callers PASSED [ 35%]+tests/unit/generation/test_context_assembler.py::test_assemble_symbol_spotlight_no_callers PASSED [ 36%]+tests/unit/generation/test_context_assembler.py::test_assemble_module_page_total_symbols PASSED [ 36%]+tests/unit/generation/test_context_assembler.py::test_assemble_module_page_public_symbols PASSED [ 36%]+tests/unit/generation/test_context_assembler.py::test_assemble_scc_page_cycle_description_contains_files PASSED [ 36%]+tests/unit/generation/test_context_assembler.py::test_assemble_repo_overview_top_files_sorted PASSED [ 36%]+tests/unit/generation/test_context_assembler.py::test_assemble_repo_overview_circular_dep_count PASSED [ 36%]+tests/unit/generation/test_context_assembler.py::test_assemble_file_page_threads_decision_records PASSED [ 37%]+tests/unit/generation/test_context_assembler.py::test_assemble_module_page_threads_phase2_signals PASSED [ 37%]+tests/unit/generation/test_context_assembler.py::test_assemble_repo_overview_threads_external_systems_and_decisions PASSED [ 37%]+tests/unit/generation/test_context_assembler.py::test_assemble_api_contract_raw_content_budgeted PASSED [ 37%]+tests/unit/generation/test_context_assembler.py::test_assemble_api_contract_language_matches PASSED [ 37%]+tests/unit/generation/test_decision_harvest.py::test_parse_strips_fence_and_returns_payload PASSED [ 37%]+tests/unit/generation/test_decision_harvest.py::test_parse_no_fence_is_passthrough PASSED [ 37%]+tests/unit/generation/test_decision_harvest.py::test_parse_malformed_json_does_not_corrupt_page PASSED [ 38%]+tests/unit/generation/test_decision_harvest.py::test_parse_drops_titleless_items PASSED [ 38%]+tests/unit/generation/test_decision_harvest.py::test_grounded_decision_is_kept_as_llm_inferred PASSED [ 38%]+tests/unit/generation/test_decision_harvest.py::test_hallucinated_decision_is_rejected PASSED [ 38%]+tests/unit/generation/test_decision_harvest.py::test_partial_hallucination_drops_only_ungrounded_fields PASSED [ 38%]+tests/unit/generation/test_decision_harvest.py::test_no_fence_yields_no_decisions PASSED [ 38%]+tests/unit/generation/test_decision_harvest.py::test_directive_appended_when_harvest_enabled PASSED [ 38%]+tests/unit/generation/test_decision_harvest.py::test_directive_absent_when_harvest_disabled PASSED [ 39%]+tests/unit/generation/test_decision_harvest.py::test_directive_not_added_to_non_harvestable_page_type PASSED [ 39%]+tests/unit/generation/test_editor_file_base.py::test_render_returns_non_empty_string PASSED [ 39%]+tests/unit/generation/test_editor_file_base.py::test_render_contains_repo_name PASSED [ 39%]+tests/unit/generation/test_editor_file_base.py::test_write_creates_new_file PASSED [ 39%]+tests/unit/generation/test_editor_file_base.py::test_write_new_file_has_correct_structure PASSED [ 39%]+tests/unit/generation/test_editor_file_base.py::test_write_preserves_user_content_when_no_markers PASSED [ 40%]+tests/unit/generation/test_editor_file_base.py::test_write_appends_when_no_markers PASSED [ 40%]+tests/unit/generation/test_editor_file_base.py::test_write_replaces_between_markers PASSED [ 40%]+tests/unit/generation/test_editor_file_base.py::test_write_replaces_only_managed_section PASSED [ 40%]+tests/unit/generation/test_editor_file_base.py::test_write_is_idempotent PASSED [ 40%]+tests/unit/generation/test_editor_file_base.py::test_write_returns_path PASSED [ 40%]+tests/unit/generation/test_editor_file_base.py::test_render_full_matches_write_output PASSED [ 40%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_empty_db_returns_defaults PASSED [ 41%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_repo_name PASSED [ 41%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_architecture_summary PASSED [ 41%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_entry_points PASSED [ 41%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_entry_points_sorted_by_pagerank PASSED [ 41%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_hotspots PASSED [ 41%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_active_decisions_only PASSED [ 41%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_avg_confidence PASSED [ 42%]+tests/unit/generation/test_editor_file_fetcher.py::test_fetch_indexed_at_is_date_string PASSED [ 42%]+tests/unit/generation/test_interlinking.py::test_resolve_links_for_file_reference PASSED [ 42%]+tests/unit/generation/test_interlinking.py::test_dedup_same_target_referenced_multiple_times PASSED [ 42%]+tests/unit/generation/test_interlinking.py::test_self_reference_excluded PASSED [ 42%]+tests/unit/generation/test_interlinking.py::test_unresolved_refs_are_dropped_silently PASSED [ 42%]+tests/unit/generation/test_interlinking.py::test_index_resolves_basename_when_unique PASSED [ 42%]+tests/unit/generation/test_interlinking.py::test_link_index_build_returns_expected_keys PASSED [ 43%]+tests/unit/generation/test_job_system.py::test_create_job_returns_uuid PASSED [ 43%]+tests/unit/generation/test_job_system.py::test_create_job_writes_json_file PASSED [ 43%]+tests/unit/generation/test_job_system.py::test_create_job_status_is_pending PASSED [ 43%]+tests/unit/generation/test_job_system.py::test_start_job_sets_running PASSED [ 43%]+tests/unit/generation/test_job_system.py::test_start_job_stores_total_pages PASSED [ 43%]+tests/unit/generation/test_job_system.py::test_complete_page_increments_count PASSED [ 44%]+tests/unit/generation/test_job_system.py::test_complete_page_idempotent PASSED [ 44%]+tests/unit/generation/test_job_system.py::test_complete_page_json_persisted PASSED [ 44%]+tests/unit/generation/test_job_system.py::test_fail_page_increments_failed PASSED [ 44%]+tests/unit/generation/test_job_system.py::test_fail_page_job_stays_running PASSED [ 44%]+tests/unit/generation/test_job_system.py::test_complete_job_sets_completed PASSED [ 44%]+tests/unit/generation/test_job_system.py::test_fail_job_stores_error_message PASSED [ 44%]+tests/unit/generation/test_job_system.py::test_pause_job_sets_paused PASSED [ 45%]+tests/unit/generation/test_job_system.py::test_resume_job_sets_running PASSED [ 45%]+tests/unit/generation/test_job_system.py::test_resume_job_returns_checkpoint PASSED [ 45%]+tests/unit/generation/test_job_system.py::test_invalid_transition_raises_value_error PASSED [ 45%]+tests/unit/generation/test_job_system.py::test_json_round_trip_persistence PASSED [ 45%]+tests/unit/generation/test_job_system.py::test_list_jobs_sorted_by_created_at_desc PASSED [ 45%]+tests/unit/generation/test_job_system.py::test_list_jobs_returns_all PASSED [ 45%]+tests/unit/generation/test_job_system.py::test_get_completed_page_ids_correct_set PASSED [ 46%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageContextWithKG::test_kg_fields_populated PASSED [ 46%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageContextWithKG::test_kg_fields_empty_without_context PASSED [ 46%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageContextWithKG::test_kg_fields_with_none_context PASSED [ 46%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageContextWithKG::test_kg_entry_point_role PASSED [ 46%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageContextWithKG::test_kg_internal_role PASSED [ 46%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageContextWithKG::test_kg_no_tour_step PASSED [ 47%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageContextWithKG::test_kg_empty_neighbors PASSED [ 47%]+tests/unit/generation/test_kg_aware_file_pages.py::TestTokenBudgetWithKG::test_kg_reserves_budget PASSED [ 47%]+tests/unit/generation/test_kg_aware_file_pages.py::TestTokenBudgetWithKG::test_kg_budget_does_not_exceed_800 PASSED [ 47%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageTemplate::test_tier1_template_renders_kg_layer PASSED [ 47%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageTemplate::test_tier1_template_entry_point_role PASSED [ 47%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageTemplate::test_tier1_template_no_kg PASSED [ 47%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageTemplate::test_tier1_template_kg_signals PASSED [ 48%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageTemplate::test_tier2_template_renders_kg_layer PASSED [ 48%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageTemplate::test_tier2_template_no_kg PASSED [ 48%]+tests/unit/generation/test_kg_aware_file_pages.py::TestFilePageTemplate::test_tier1_cross_layer_neighbor PASSED [ 48%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestClaudeMdKGSection::test_renders_layers_when_present PASSED [ 48%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestClaudeMdKGSection::test_no_layers_section_without_data PASSED [ 48%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestClaudeMdKGSection::test_renders_tour_when_present PASSED [ 48%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestClaudeMdKGSection::test_no_tour_section_without_data PASSED [ 49%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestClaudeMdKGSection::test_tour_truncates_at_6 PASSED [ 49%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestOnboardingSignalsKG::test_signals_carry_kg_data PASSED [ 49%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestOnboardingSignalsKG::test_signals_default_empty PASSED [ 49%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestHowItWorksWithTour::test_tour_steps_in_context PASSED [ 49%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestHowItWorksWithTour::test_template_renders_tour PASSED [ 49%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestHowItWorksWithTour::test_template_no_tour_no_flows PASSED [ 50%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestHowItWorksWithTour::test_build_gate_passes_with_tour_only PASSED [ 50%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestHowItWorksWithTour::test_build_gate_fails_module_no_tour_no_flows PASSED [ 50%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestCodebaseMapWithLayers::test_layers_in_context PASSED [ 50%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestCodebaseMapWithLayers::test_template_renders_layers PASSED [ 50%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestCodebaseMapWithLayers::test_template_no_layers_section PASSED [ 50%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestKGContextGetTour::test_get_tour_returns_tour PASSED [ 50%]+tests/unit/generation/test_kg_claude_md_onboarding.py::TestKGContextGetTour::test_get_tour_unavailable PASSED [ 51%]+tests/unit/generation/test_kg_context.py::TestLoad::test_load_and_available PASSED [ 51%]+tests/unit/generation/test_kg_context.py::TestLoad::test_nonexistent_path PASSED [ 51%]+tests/unit/generation/test_kg_context.py::TestLoad::test_none_path PASSED [ 51%]+tests/unit/generation/test_kg_context.py::TestLoad::test_malformed_json PASSED [ 51%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_entry_point_role PASSED [ 51%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_edge_connector_role PASSED [ 51%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_internal_role PASSED [ 52%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_tour_step PASSED [ 52%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_no_tour_step PASSED [ 52%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_tags PASSED [ 52%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_node_summary PASSED [ 52%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_neighbors PASSED [ 52%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_cross_layer_neighbor PASSED [ 52%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_missing_file PASSED [ 53%]+tests/unit/generation/test_kg_context.py::TestGetFileContext::test_unavailable_returns_none PASSED [ 53%]+tests/unit/generation/test_kg_context.py::TestTourValidation::test_deleted_file_excluded_from_tour PASSED [ 53%]+tests/unit/generation/test_kg_context.py::TestLayers::test_get_layers PASSED [ 53%]+tests/unit/generation/test_kg_context.py::TestLayers::test_get_layers_unavailable PASSED [ 53%]+tests/unit/generation/test_kg_context.py::TestInterLayerEdges::test_deps_out PASSED [ 53%]+tests/unit/generation/test_kg_context.py::TestInterLayerEdges::test_deps_in PASSED [ 54%]+tests/unit/generation/test_kg_context.py::TestInterLayerEdges::test_no_cross_layer_edges PASSED [ 54%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_adds_wiki_page_ids PASSED [ 54%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_missing_pages_get_empty_list PASSED [ 54%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_preserves_existing_kg_data PASSED [ 54%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_multiple_files_in_step PASSED [ 54%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_non_file_node_ids_skipped PASSED [ 54%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_empty_tour_returns_zero PASSED [ 55%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_invalid_json_returns_zero PASSED [ 55%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_missing_file_returns_zero PASSED [ 55%]+tests/unit/generation/test_kg_enrichment.py::TestEnrichTourWithWikiLinks::test_idempotent PASSED [ 55%]+tests/unit/generation/test_kg_enrichment.py::TestOnboardingPrerequisites::test_all_slots_have_prerequisites PASSED [ 55%]+tests/unit/generation/test_kg_enrichment.py::TestOnboardingPrerequisites::test_root_slots_have_no_prerequisites PASSED [ 55%]+tests/unit/generation/test_kg_enrichment.py::TestOnboardingPrerequisites::test_downstream_slots_reference_valid_slots PASSED [ 55%]+tests/unit/generation/test_kg_enrichment.py::TestOnboardingPrerequisites::test_no_circular_prerequisites PASSED [ 56%]+tests/unit/generation/test_kg_enrichment.py::TestOnboardingPrerequisites::test_prerequisites_respect_ordering PASSED [ 56%]+tests/unit/generation/test_kg_enrichment.py::TestOnboardingPrerequisites::test_active_landscape_depends_on_codebase_map PASSED [ 56%]+tests/unit/generation/test_kg_enrichment.py::TestOnboardingPrerequisites::test_how_it_works_depends_on_key_concepts PASSED [ 56%]+tests/unit/generation/test_kg_prioritization.py::TestScoreFileKGBonus::test_tour_file_scores_higher PASSED [ 56%]+tests/unit/generation/test_kg_prioritization.py::TestScoreFileKGBonus::test_edge_connector_scores_higher PASSED [ 56%]+tests/unit/generation/test_kg_prioritization.py::TestScoreFileKGBonus::test_combined_tour_and_edge_connector PASSED [ 57%]+tests/unit/generation/test_kg_prioritization.py::TestScoreFileKGBonus::test_zero_kg_bonus_no_change PASSED [ 57%]+tests/unit/generation/test_kg_prioritization.py::TestScoreFileKGBonus::test_kg_bonus_before_test_penalty PASSED [ 57%]+tests/unit/generation/test_kg_prioritization.py::TestTieringWithKGScores::test_tour_file_promoted_to_tier1 PASSED [ 57%]+tests/unit/generation/test_kg_prioritization.py::TestTieringWithKGScores::test_no_kg_scores_uses_pagerank_only PASSED [ 57%]+tests/unit/generation/test_kg_prioritization.py::TestTieringWithKGScores::test_kg_scores_none PASSED [ 57%]+tests/unit/generation/test_kg_prioritization.py::TestTieringWithKGScores::test_all_tier1_ignores_kg_scores PASSED [ 57%]+tests/unit/generation/test_kg_prioritization.py::TestTieringWithKGScores::test_equal_pagerank_kg_breaks_tie PASSED [ 58%]+tests/unit/generation/test_kg_prioritization.py::TestComputeKGFileScores::test_tour_file_gets_bonus PASSED [ 58%]+tests/unit/generation/test_kg_prioritization.py::TestComputeKGFileScores::test_edge_connector_gets_bonus PASSED [ 58%]+tests/unit/generation/test_kg_prioritization.py::TestComputeKGFileScores::test_unavailable_kg_returns_empty PASSED [ 58%]+tests/unit/generation/test_kg_prioritization.py::TestComputeKGFileScores::test_tour_plus_edge_connector PASSED [ 58%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestEnrichLayers::test_enriches_layer_names PASSED [ 58%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestEnrichLayers::test_falls_back_on_llm_failure PASSED [ 58%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestEnrichLayers::test_falls_back_on_invalid_json PASSED [ 59%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestEnrichLayers::test_empty_layers_no_crash PASSED [ 59%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestTourGeneration::test_tour_generated_from_llm PASSED [ 59%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestTourGeneration::test_tour_fallback_on_failure PASSED [ 59%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestDeterministicTour::test_basic_tour PASSED [ 59%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestDeterministicTour::test_no_entry_points PASSED [ 59%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestDeterministicTour::test_empty_layers PASSED [ 60%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestSummaryBackfill::test_populates_summaries PASSED [ 60%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestSummaryBackfill::test_does_not_overwrite_existing PASSED [ 60%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestSummaryBackfill::test_handles_no_pages PASSED [ 60%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestParseJsonResponse::test_plain_json PASSED [ 60%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestParseJsonResponse::test_markdown_fenced PASSED [ 60%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestParseJsonResponse::test_json_with_preamble PASSED [ 60%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestParseJsonResponse::test_invalid_returns_none PASSED [ 61%]+tests/unit/generation/test_knowledge_graph_enrichment.py::TestParseJsonResponse::test_empty_string PASSED [ 61%]+tests/unit/generation/test_layer_pages.py::TestLayerPageModel::test_layer_page_in_page_type PASSED [ 61%]+tests/unit/generation/test_layer_pages.py::TestLayerPageModel::test_layer_page_generation_level PASSED [ 61%]+tests/unit/generation/test_layer_pages.py::TestLayerPageModel::test_layer_page_after_module_before_overview PASSED [ 61%]+tests/unit/generation/test_layer_pages.py::TestLayerPageContext::test_basic_construction PASSED [ 61%]+tests/unit/generation/test_layer_pages.py::TestLayerPageContext::test_full_construction PASSED [ 61%]+tests/unit/generation/test_layer_pages.py::TestLayerPageTemplate::test_renders_layer_name PASSED [ 62%]+tests/unit/generation/test_layer_pages.py::TestLayerPageTemplate::test_renders_key_files PASSED [ 62%]+tests/unit/generation/test_layer_pages.py::TestLayerPageTemplate::test_renders_inter_layer_deps PASSED [ 62%]+tests/unit/generation/test_layer_pages.py::TestLayerPageTemplate::test_renders_tour_steps PASSED [ 62%]+tests/unit/generation/test_layer_pages.py::TestLayerPageTemplate::test_renders_entry_points_and_connectors PASSED [ 62%]+tests/unit/generation/test_layer_pages.py::TestLayerPageTemplate::test_no_optional_sections_when_empty PASSED [ 62%]+tests/unit/generation/test_layer_pages.py::TestLayerPagePrompt::test_prompt_exists PASSED [ 62%]+tests/unit/generation/test_layer_pages.py::TestBuildLevel5Coros::test_generates_for_layer_with_enough_files PASSED [ 63%]+tests/unit/generation/test_layer_pages.py::TestBuildLevel5Coros::test_skips_small_layers PASSED [ 63%]+tests/unit/generation/test_layer_pages.py::TestBuildLevel5Coros::test_no_layers_no_coros PASSED [ 63%]+tests/unit/generation/test_layer_pages.py::TestBuildLevel5Coros::test_no_kg_returns_empty PASSED [ 63%]+tests/unit/generation/test_layer_pages.py::TestBuildLevel5Coros::test_skips_completed_layers PASSED [ 63%]+tests/unit/generation/test_layer_pages.py::TestBuildLevel5Coros::test_multiple_layers PASSED [ 63%]+tests/unit/generation/test_layers.py::test_infer_layer_matches_directory_hints PASSED [ 64%]+tests/unit/generation/test_layers.py::test_infer_layer_uses_deepest_matching_directory PASSED [ 64%]+tests/unit/generation/test_layers.py::test_infer_layer_falls_back_for_unmatched_paths PASSED [ 64%]+tests/unit/generation/test_layers.py::test_compute_layer_order_follows_dependency_direction PASSED [ 64%]+tests/unit/generation/test_layers.py::test_compute_layer_order_ignores_external_and_intra_layer_edges PASSED [ 64%]+tests/unit/generation/test_layers.py::test_compute_layer_order_stable_without_edges PASSED [ 64%]+tests/unit/generation/test_layers.py::test_compute_layer_order_single_layer PASSED [ 64%]+tests/unit/generation/test_lazy_generation_exports.py::test_all_exports_resolve PASSED [ 65%]+tests/unit/generation/test_lazy_generation_exports.py::test_dir_includes_lazy_exports PASSED [ 65%]+tests/unit/generation/test_lazy_generation_exports.py::test_unknown_attribute_raises PASSED [ 65%]+tests/unit/generation/test_lazy_generation_exports.py::test_light_leaf_import_does_not_load_heavy_stack PASSED [ 65%]+tests/unit/generation/test_lazy_generation_exports.py::test_lazy_attribute_access_imports_on_demand PASSED [ 65%]+tests/unit/generation/test_mermaid_safety.py::test_no_mermaid_is_noop PASSED [ 65%]+tests/unit/generation/test_mermaid_safety.py::test_path_node_ids_are_slugged_consistently PASSED [ 65%]+tests/unit/generation/test_mermaid_safety.py::test_dotted_ids_slugged PASSED [ 66%]+tests/unit/generation/test_mermaid_safety.py::test_unquoted_label_with_parens_is_quoted PASSED [ 66%]+tests/unit/generation/test_mermaid_safety.py::test_already_quoted_label_untouched PASSED [ 66%]+tests/unit/generation/test_mermaid_safety.py::test_inner_quotes_escaped PASSED [ 66%]+tests/unit/generation/test_mermaid_safety.py::test_non_graph_diagram_left_alone PASSED [ 66%]+tests/unit/generation/test_mermaid_safety.py::test_collision_produces_unique_slugs PASSED [ 66%]+tests/unit/generation/test_mermaid_safety.py::test_sanitize_pages_mutates_and_counts PASSED [ 67%]+tests/unit/generation/test_models.py::test_compute_page_id_normal PASSED [ 67%]+tests/unit/generation/test_models.py::test_compute_page_id_scc PASSED [ 67%]+tests/unit/generation/test_models.py::test_total_tokens_property PASSED [ 67%]+tests/unit/generation/test_models.py::test_freshness_same_hash_is_fresh PASSED [ 67%]+tests/unit/generation/test_models.py::test_freshness_different_hash_is_stale PASSED [ 67%]+tests/unit/generation/test_models.py::test_freshness_expired_by_age PASSED [ 67%]+tests/unit/generation/test_models.py::test_freshness_stale_by_age_same_hash PASSED [ 68%]+tests/unit/generation/test_models.py::test_decay_confidence_zero_days PASSED [ 68%]+tests/unit/generation/test_models.py::test_decay_confidence_halfway PASSED [ 68%]+tests/unit/generation/test_models.py::test_decay_confidence_beyond_expiry_is_zero PASSED [ 68%]+tests/unit/generation/test_models.py::test_generation_config_defaults PASSED [ 68%]+tests/unit/generation/test_models.py::test_generation_config_embed_concurrency_defaults_to_max_concurrency PASSED [ 68%]+tests/unit/generation/test_models.py::test_generation_config_normalizes_reasoning PASSED [ 68%]+tests/unit/generation/test_models.py::test_generation_config_accepts_native_reasoning_effort PASSED [ 69%]+tests/unit/generation/test_models.py::test_generation_config_rejects_invalid_reasoning PASSED [ 69%]+tests/unit/generation/test_onboarding.py::test_subkinds_registered_in_canonical_order PASSED [ 69%]+tests/unit/generation/test_onboarding.py::test_onboarding_level_is_eight PASSED [ 69%]+tests/unit/generation/test_onboarding.py::test_target_path_format PASSED [ 69%]+tests/unit/generation/test_onboarding.py::test_promoted_slots_map PASSED [ 69%]+tests/unit/generation/test_onboarding.py::test_codebase_map_always_builds PASSED [ 70%]+tests/unit/generation/test_onboarding.py::test_active_landscape_skipped_without_git_meta PASSED [ 70%]+tests/unit/generation/test_onboarding.py::test_active_landscape_skipped_below_threshold PASSED [ 70%]+tests/unit/generation/test_onboarding.py::test_active_landscape_fires_above_threshold PASSED [ 70%]+tests/unit/generation/test_onboarding.py::test_getting_started_skipped_without_signal PASSED [ 70%]+tests/unit/generation/test_onboarding.py::test_getting_started_fires_on_manifest PASSED [ 70%]+tests/unit/generation/test_onboarding.py::test_getting_started_fires_on_readme_install_section PASSED [ 70%]+tests/unit/generation/test_onboarding.py::test_key_concepts_skipped_when_too_few_concepts PASSED [ 71%]+tests/unit/generation/test_onboarding.py::test_key_concepts_fires_with_enough_concepts PASSED [ 71%]+tests/unit/generation/test_onboarding.py::test_how_it_works_skipped_for_flat_module_collection PASSED [ 71%]+tests/unit/generation/test_onboarding.py::test_how_it_works_fires_on_service_archetype PASSED [ 71%]+tests/unit/generation/test_onboarding.py::test_how_it_works_fires_on_cli_archetype_via_entry_point PASSED [ 71%]+tests/unit/generation/test_onboarding.py::test_development_guide_skipped_for_unconventional_repo PASSED [ 71%]+tests/unit/generation/test_onboarding.py::test_development_guide_fires_with_suffix_pattern_and_test_mirror PASSED [ 71%]+tests/unit/generation/test_onboarding.py::test_tag_promoted_pages_sets_onboarding_slot PASSED [ 72%]+tests/unit/generation/test_onboarding.py::test_guided_tour_skipped_without_enough_stops PASSED [ 72%]+tests/unit/generation/test_onboarding.py::test_guided_tour_builds_with_stops_and_summaries PASSED [ 72%]+tests/unit/generation/test_onboarding.py::test_subkind_template_renders[codebase_map-<lambda>] PASSED [ 72%]+tests/unit/generation/test_onboarding.py::test_subkind_template_renders[active_landscape-<lambda>] PASSED [ 72%]+tests/unit/generation/test_onboarding.py::test_subkind_template_renders[getting_started-<lambda>] PASSED [ 72%]+tests/unit/generation/test_onboarding.py::test_subkind_template_renders[key_concepts-<lambda>] PASSED [ 72%]+tests/unit/generation/test_onboarding.py::test_subkind_template_renders[how_it_works-<lambda>] PASSED [ 73%]+tests/unit/generation/test_onboarding.py::test_subkind_template_renders[guided_tour-<lambda>] PASSED [ 73%]+tests/unit/generation/test_onboarding.py::test_subkind_template_renders[development_guide-<lambda>] PASSED [ 73%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[file_page] PASSED [ 73%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[symbol_spotlight] PASSED [ 73%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[module_page] PASSED [ 73%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[scc_page] PASSED [ 74%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[repo_overview] PASSED [ 74%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[architecture_diagram] PASSED [ 74%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[api_contract] PASSED [ 74%]+tests/unit/generation/test_page_generator.py::test_system_prompt_exists[infra_page] PASSED [ 74%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[file_page] PASSED [ 74%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[symbol_spotlight] PASSED [ 74%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[module_page] PASSED [ 75%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[scc_page] PASSED [ 75%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[repo_overview] PASSED [ 75%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[architecture_diagram] PASSED [ 75%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[api_contract] PASSED [ 75%]+tests/unit/generation/test_page_generator.py::test_system_prompt_not_empty[infra_page] PASSED [ 75%]+tests/unit/generation/test_page_generator.py::test_generate_file_page_returns_generated_page PASSED [ 75%]+tests/unit/generation/test_page_generator.py::test_generate_file_page_provider_name PASSED [ 76%]+tests/unit/generation/test_page_generator.py::test_generate_file_page_increments_call_count PASSED [ 76%]+tests/unit/generation/test_page_generator.py::test_generate_file_page_forwards_reasoning_config PASSED [ 76%]+tests/unit/generation/test_page_generator.py::test_cache_hit_does_not_increment_call_count PASSED [ 76%]+tests/unit/generation/test_page_generator.py::test_cache_disabled_increments_every_call PASSED [ 76%]+tests/unit/generation/test_page_generator.py::test_different_page_type_different_cache_key PASSED [ 76%]+tests/unit/generation/test_page_generator.py::test_different_prompt_different_cache_key PASSED [ 77%]+tests/unit/generation/test_page_generator.py::test_generated_page_source_hash_is_64_hex PASSED [ 77%]+tests/unit/generation/test_page_generator.py::test_generated_page_created_at_is_iso PASSED [ 77%]+tests/unit/generation/test_page_generator.py::test_generate_all_api_contract_before_file_page PASSED [ 77%]+tests/unit/generation/test_page_generator.py::test_generate_all_infra_file_gets_infra_page PASSED [ 77%]+tests/unit/generation/test_page_generator.py::test_generate_all_returns_pages PASSED [ 77%]+tests/unit/generation/test_page_generator.py::test_generate_all_level_values_in_range PASSED [ 77%]+tests/unit/generation/test_page_generator.py::test_build_system_prompt_english_is_unchanged PASSED [ 78%]+tests/unit/generation/test_page_generator.py::test_build_system_prompt_non_english_prepends_instruction PASSED [ 78%]+tests/unit/generation/test_page_generator.py::test_build_system_prompt_unknown_language_falls_back_to_english PASSED [ 78%]+tests/unit/generation/test_page_generator.py::test_build_system_prompt_strips_control_chars_from_language PASSED [ 78%]+tests/unit/generation/test_page_generator.py::test_compute_cache_key_varies_by_language PASSED [ 78%]+tests/unit/generation/test_page_generator_tiering.py::test_partition_none_puts_everything_in_tier1 PASSED [ 78%]+tests/unit/generation/test_page_generator_tiering.py::test_partition_n_geq_len_is_all_tier1 PASSED [ 78%]+tests/unit/generation/test_page_generator_tiering.py::test_partition_top_n_by_pagerank PASSED [ 79%]+tests/unit/generation/test_page_generator_tiering.py::test_partition_zero_is_all_tier2 PASSED [ 79%]+tests/unit/generation/test_page_generator_tiering.py::test_partition_is_a_partition PASSED [ 79%]+tests/unit/generation/test_page_generator_tiering.py::test_partition_tie_break_is_deterministic PASSED [ 79%]+tests/unit/generation/test_page_generator_tiering.py::test_tier2_render_makes_no_provider_call PASSED [ 79%]+tests/unit/generation/test_page_generator_tiering.py::test_generation_config_tier1_top_n_defaults_none PASSED [ 79%]+tests/unit/generation/test_pipeline_reasoning.py::test_run_pipeline_loads_repo_reasoning_config PASSED [ 80%]+tests/unit/generation/test_provenance.py::test_layer_metadata_attached PASSED [ 80%]+tests/unit/generation/test_provenance.py::test_no_kg_layer_falls_back_to_inferred_layer PASSED [ 80%]+tests/unit/generation/test_provenance.py::test_sources_from_dependencies_and_decisions PASSED [ 80%]+tests/unit/generation/test_provenance.py::test_no_sources_means_no_key PASSED [ 80%]+tests/unit/generation/test_provenance.py::test_dependencies_capped_at_ten PASSED [ 80%]+tests/unit/generation/test_rag_prefetch.py::test_search_many_default_aligns_with_per_query_search PASSED [ 80%]+tests/unit/generation/test_rag_prefetch.py::test_in_memory_search_many_embeds_once PASSED [ 81%]+tests/unit/generation/test_rag_prefetch.py::test_search_many_empty_queries PASSED [ 81%]+tests/unit/generation/test_rag_prefetch.py::test_prefetch_populates_rag_context_with_self_exclusion PASSED [ 81%]+tests/unit/generation/test_rag_prefetch.py::test_prefetch_skips_when_store_below_min_size PASSED [ 81%]+tests/unit/generation/test_rag_prefetch.py::test_prefetch_returns_false_without_store_or_on_batch_failure PASSED [ 81%]+tests/unit/generation/test_rag_prefetch.py::test_prefetch_disabled_flag_returns_false PASSED [ 81%]+tests/unit/generation/test_rag_prefetch.py::test_per_page_search_skipped_iff_prefetched[True-0] PASSED [ 81%]+tests/unit/generation/test_rag_prefetch.py::test_per_page_search_skipped_iff_prefetched[False-1] PASSED [ 82%]+tests/unit/generation/test_run_level_cancellation.py::test_cancel_closes_queued_coroutines PASSED [ 82%]+tests/unit/generation/test_run_level_cancellation.py::test_cancel_emits_no_never_awaited_warning PASSED [ 82%]+tests/unit/generation/test_run_level_cancellation.py::test_run_level_completes_normally_after_fix PASSED [ 82%]+tests/unit/generation/test_selection_budget.py::test_compute_budget_scales_linearly_for_large_repo PASSED [ 82%]+tests/unit/generation/test_selection_budget.py::test_compute_budget_floors_for_small_repos PASSED [ 82%]+tests/unit/generation/test_selection_budget.py::test_compute_budget_zero_for_empty_repo PASSED [ 82%]+tests/unit/generation/test_selection_budget.py::test_allocate_budget_respects_candidate_supply PASSED [ 83%]+tests/unit/generation/test_selection_budget.py::test_select_pages_budget_tracks_coverage[0.1-96] PASSED [ 83%]+tests/unit/generation/test_selection_budget.py::test_select_pages_budget_tracks_coverage[0.2-192] PASSED [ 83%]+tests/unit/generation/test_selection_budget.py::test_select_pages_budget_tracks_coverage[0.5-479] PASSED [ 83%]+tests/unit/generation/test_selection_budget.py::test_select_pages_emits_no_pages_for_empty_repo PASSED [ 83%]+tests/unit/generation/test_selection_budget.py::test_higher_coverage_strictly_emits_more_pages PASSED [ 83%]+tests/unit/generation/test_selection_budget.py::test_landmarks_are_pulled_into_budget_without_inflating_count PASSED [ 84%]+tests/unit/generation/test_selection_budget.py::test_landmarks_respect_coverage_across_sizes PASSED [ 84%]+tests/unit/generation/test_symbol_index.py::test_indexed_extraction_matches_scan PASSED [ 84%]+tests/unit/generation/test_symbol_index.py::test_index_buckets_only_symbol_nodes PASSED [ 84%]+tests/unit/generation/test_symbol_index.py::test_assemble_file_page_identical_with_index PASSED [ 84%]+tests/unit/generation/test_tech_stack.py::test_empty_directory_returns_empty_list PASSED [ 84%]+tests/unit/generation/test_tech_stack.py::test_detects_python_from_pyproject PASSED [ 84%]+tests/unit/generation/test_tech_stack.py::test_detects_fastapi_from_pyproject PASSED [ 85%]+tests/unit/generation/test_tech_stack.py::test_detects_nodejs_from_package_json PASSED [ 85%]+tests/unit/generation/test_tech_stack.py::test_detects_react_from_package_json PASSED [ 85%]+tests/unit/generation/test_tech_stack.py::test_detects_typescript_from_tsconfig PASSED [ 85%]+tests/unit/generation/test_tech_stack.py::test_detects_rust_from_cargo_toml PASSED [ 85%]+tests/unit/generation/test_tech_stack.py::test_detects_go_from_go_mod PASSED [ 85%]+tests/unit/generation/test_tech_stack.py::test_detects_docker PASSED [ 85%]+tests/unit/generation/test_tech_stack.py::test_returns_sorted_by_category_then_name PASSED [ 86%]+tests/unit/generation/test_tech_stack.py::test_empty_directory_returns_empty_dict PASSED [ 86%]+tests/unit/generation/test_tech_stack.py::test_detects_pytest_from_pyproject PASSED [ 86%]+tests/unit/generation/test_tech_stack.py::test_detects_typo3_from_composer_type PASSED [ 86%]+tests/unit/generation/test_tech_stack.py::test_detects_typo3_from_cms_core_require PASSED [ 86%]+tests/unit/generation/test_tech_stack.py::test_detects_symfony_from_framework_bundle PASSED [ 86%]+tests/unit/generation/test_tech_stack.py::test_detects_laravel_from_framework_require PASSED [ 87%]+tests/unit/generation/test_tech_stack.py::test_typo3_takes_precedence_over_symfony_when_both_match PASSED [ 87%]+tests/unit/generation/test_tech_stack.py::test_plain_php_library_does_not_match_any_framework PASSED [ 87%]+tests/unit/generation/test_tech_stack.py::test_malformed_composer_does_not_crash PASSED [ 87%]+tests/unit/generation/test_tech_stack.py::test_detects_ruff_from_pyproject PASSED [ 87%]+tests/unit/generation/test_tech_stack.py::test_detects_npm_scripts PASSED [ 87%]+tests/unit/generation/test_tech_stack.py::test_detects_pnpm_when_lockfile_present PASSED [ 87%]+tests/unit/generation/test_tech_stack.py::test_detects_makefile_targets PASSED [ 88%]+tests/unit/generation/test_templates.py::test_file_page_renders_without_error PASSED [ 88%]+tests/unit/generation/test_templates.py::test_file_page_has_heading PASSED [ 88%]+tests/unit/generation/test_templates.py::test_file_page_contains_file_path PASSED [ 88%]+tests/unit/generation/test_templates.py::test_module_page_renders_without_error PASSED [ 88%]+tests/unit/generation/test_templates.py::test_module_page_has_heading PASSED [ 88%]+tests/unit/generation/test_templates.py::test_module_page_contains_module_path PASSED [ 88%]+tests/unit/generation/test_templates.py::test_repo_overview_renders_without_error PASSED [ 89%]+tests/unit/generation/test_templates.py::test_repo_overview_has_heading PASSED [ 89%]+tests/unit/generation/test_templates.py::test_repo_overview_contains_repo_name PASSED [ 89%]+tests/unit/generation/test_templates.py::test_symbol_spotlight_renders_without_error PASSED [ 89%]+tests/unit/generation/test_templates.py::test_symbol_spotlight_has_heading PASSED [ 89%]+tests/unit/generation/test_templates.py::test_symbol_spotlight_contains_symbol_name PASSED [ 89%]+tests/unit/generation/test_templates.py::test_architecture_diagram_renders_without_error PASSED [ 90%]+tests/unit/generation/test_templates.py::test_architecture_diagram_has_heading PASSED [ 90%]+tests/unit/generation/test_templates.py::test_architecture_diagram_mentions_mermaid PASSED [ 90%]+tests/unit/generation/test_templates.py::test_api_contract_renders_without_error PASSED [ 90%]+tests/unit/generation/test_templates.py::test_api_contract_has_heading PASSED [ 90%]+tests/unit/generation/test_templates.py::test_api_contract_contains_file_path PASSED [ 90%]+tests/unit/generation/test_templates.py::test_infra_page_renders_without_error PASSED [ 90%]+tests/unit/generation/test_templates.py::test_infra_page_has_heading PASSED [ 91%]+tests/unit/generation/test_templates.py::test_infra_page_contains_file_path PASSED [ 91%]+tests/unit/generation/test_templates.py::test_scc_page_renders_without_error PASSED [ 91%]+tests/unit/generation/test_templates.py::test_scc_page_has_heading PASSED [ 91%]+tests/unit/generation/test_templates.py::test_scc_page_contains_cycle_description PASSED [ 91%]+tests/unit/generation/test_tour.py::test_score_entry_points_rewards_entry_flag_and_filename PASSED [ 91%]+tests/unit/generation/test_tour.py::test_score_entry_points_excludes_zero_score PASSED [ 91%]+tests/unit/generation/test_tour.py::test_tour_landmark_paths_is_bounded PASSED [ 92%]+tests/unit/generation/test_tour.py::test_build_tour_only_references_documented_pages PASSED [ 92%]+tests/unit/generation/test_tour.py::test_build_tour_orders_by_bfs_depth PASSED [ 92%]+tests/unit/generation/test_tour.py::test_build_tour_weaves_infra_last PASSED [ 92%]+tests/unit/generation/test_tour.py::test_build_tour_respects_max_stops PASSED [ 92%]+tests/unit/generation/test_workspace_claude_md.py::test_render_returns_non_empty_string PASSED [ 92%]+tests/unit/generation/test_workspace_claude_md.py::test_render_contains_workspace_name PASSED [ 92%]+tests/unit/generation/test_workspace_claude_md.py::test_render_contains_repo_alias PASSED [ 93%]+tests/unit/generation/test_workspace_claude_md.py::test_render_contains_repo_table_headers PASSED [ 93%]+tests/unit/generation/test_workspace_claude_md.py::test_render_contains_file_and_symbol_counts PASSED [ 93%]+tests/unit/generation/test_workspace_claude_md.py::test_render_marks_default_repo PASSED [ 93%]+tests/unit/generation/test_workspace_claude_md.py::test_render_contains_mcp_tools_section PASSED [ 93%]+tests/unit/generation/test_workspace_claude_md.py::test_render_contains_workspace_query_note PASSED [ 93%]+tests/unit/generation/test_workspace_claude_md.py::test_render_skips_contract_section_when_empty PASSED [ 94%]+tests/unit/generation/test_workspace_claude_md.py::test_render_includes_contract_section_when_present PASSED [ 94%]+tests/unit/generation/test_workspace_claude_md.py::test_render_skips_co_changes_section_when_empty PASSED [ 94%]+tests/unit/generation/test_workspace_claude_md.py::test_render_includes_co_changes_section_when_present PASSED [ 94%]+tests/unit/generation/test_workspace_claude_md.py::test_render_limits_co_changes_to_ten PASSED [ 94%]+tests/unit/generation/test_workspace_claude_md.py::test_render_skips_package_deps_when_empty PASSED [ 94%]+tests/unit/generation/test_workspace_claude_md.py::test_render_includes_package_deps_when_present PASSED [ 94%]+tests/unit/generation/test_workspace_claude_md.py::test_render_includes_entry_points_per_repo PASSED [ 95%]+tests/unit/generation/test_workspace_claude_md.py::test_render_shows_placeholder_when_no_entry_points PASSED [ 95%]+tests/unit/generation/test_workspace_claude_md.py::test_write_creates_dot_claude_directory PASSED [ 95%]+tests/unit/generation/test_workspace_claude_md.py::test_write_creates_claude_md_at_workspace_root PASSED [ 95%]+tests/unit/generation/test_workspace_claude_md.py::test_write_returns_path PASSED [ 95%]+tests/unit/generation/test_workspace_claude_md.py::test_write_content_contains_markers PASSED [ 95%]+tests/unit/generation/test_workspace_claude_md.py::test_write_content_contains_user_placeholder_on_new_file PASSED [ 95%]+tests/unit/generation/test_workspace_claude_md.py::test_write_creates_parent_dirs_if_missing PASSED [ 96%]+tests/unit/generation/test_workspace_claude_md.py::test_write_preserves_user_content_above_markers PASSED [ 96%]+tests/unit/generation/test_workspace_claude_md.py::test_write_appends_when_no_markers_exist PASSED [ 96%]+tests/unit/generation/test_workspace_claude_md.py::test_write_replaces_only_managed_section PASSED [ 96%]+tests/unit/generation/test_workspace_claude_md.py::test_write_is_idempotent PASSED [ 96%]+tests/unit/generation/test_workspace_claude_md.py::test_render_with_all_empty_optional_fields_does_not_crash PASSED [ 96%]+tests/unit/generation/test_workspace_claude_md.py::test_render_with_single_repo_no_cross_repo_data PASSED [ 97%]+tests/unit/generation/test_workspace_claude_md.py::test_render_multiple_repos_all_appear_in_table PASSED [ 97%]+tests/unit/generation/test_workspace_claude_md.py::test_contracts_by_type_shown_when_present PASSED [ 97%]+::test_passing_parametrized[0] PASSED [ 97%]+::test_passing_parametrized[1] PASSED [ 97%]+::test_passing_parametrized[2] PASSED [ 97%]+::test_passing_parametrized[3] PASSED [ 97%]+::test_passing_parametrized[4] PASSED [ 98%]+::test_passing_parametrized[5] PASSED [ 98%]+::test_passing_parametrized[6] PASSED [ 98%]+::test_passing_parametrized[7] PASSED [ 98%]+::test_passing_parametrized[8] PASSED [ 98%]+::test_passing_parametrized[9] PASSED [ 98%]+::test_passing_parametrized[10] PASSED [ 98%]+::test_passing_parametrized[11] PASSED [ 99%]+::test_version_roundtrip PASSED [ 99%]+::test_assertion_failure FAILED [ 99%]+::test_unhandled_exception FAILED [ 99%]+::test_index_error_deep FAILED [ 99%]+::TestStoreBehavior::test_put_get PASSED [ 99%]+::TestStoreBehavior::test_missing_key_message FAILED [100%]++================================== FAILURES ===================================+___________________________ test_assertion_failure ____________________________+..\..\AppData\Local\Temp\distill_fixture_tests\test_sample.py:23: in test_assertion_failure+ assert result == expected+E AssertionError: assert {'layers': ['... 'pages': 412} == {'layers': ['... 'pages': 415}+E+E Omitting 1 identical items, use -vv to show+E Differing items:+E {'pages': 412} != {'pages': 415}+E {'layers': ['web', 'server']} != {'layers': ['web', 'server', 'core']}+E+E Full diff:...+E+E ...Full output truncated (12 lines hidden), use '-vv' to show+__________________________ test_unhandled_exception ___________________________+..\..\AppData\Local\Temp\distill_fixture_tests\test_sample.py:27: in test_unhandled_exception+ parse_version("not-a-version")+..\..\AppData\Local\Temp\distill_fixture_tests\test_sample.py:7: in parse_version+ major, minor, patch = s.split(".")+ ^^^^^^^^^^^^^^^^^^^+E ValueError: not enough values to unpack (expected 3, got 1)+____________________________ test_index_error_deep ____________________________+..\..\AppData\Local\Temp\distill_fixture_tests\test_sample.py:33: in test_index_error_deep+ _ = items[i]+ ^^^^^^^^+E IndexError: list index out of range+_________________ TestStoreBehavior.test_missing_key_message __________________+..\..\AppData\Local\Temp\distill_fixture_tests\test_sample.py:45: in test_missing_key_message+ _ = store["missing"]+ ^^^^^^^^^^^^^^^^+E KeyError: 'missing'++During handling of the above exception, another exception occurred:+..\..\AppData\Local\Temp\distill_fixture_tests\test_sample.py:44: in test_missing_key_message+ with pytest.raises(KeyError, match="other"):+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+E AssertionError: Regex pattern did not match.+E Expected regex: 'other'+E Actual message: "'missing'"+=========================== short test summary info ===========================+FAILED ::test_assertion_failure - AssertionError: assert {'layers': ['... 'pa...+FAILED ::test_unhandled_exception - ValueError: not enough values to unpack (...+FAILED ::test_index_error_deep - IndexError: list index out of range+FAILED ::TestStoreBehavior::test_missing_key_message - AssertionError: Regex ...+======================= 4 failed, 666 passed in 12.96s ========================diff --git a/tests/fixtures/distill/pytest_pass_verbose.txt b/tests/fixtures/distill/pytest_pass_verbose.txtnew file mode 100644index 000000000..58d0980de--- /dev/null+++ b/tests/fixtures/distill/pytest_pass_verbose.txt@@ -0,0 +1,222 @@+============================= test session starts =============================+platform win32 -- Python 3.13.5, pytest-9.0.3, pluggy-1.6.0 -- C:\Users\ragha\Desktop\repowise\.venv\Scripts\python.exe+rootdir: C:\Users\ragha\Desktop\repowise+configfile: pyproject.toml+plugins: anyio-4.13.0, asyncio-1.3.0, cov-7.1.0, respx-0.22.0, time-machine-2.19.0+asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function+collecting ... collected 212 items++tests/unit/analysis/test_change_risk.py::test_score_is_bounded_and_levelled PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_logit_is_exact_sum_of_driver_contributions PASSED [ 0%]+tests/unit/analysis/test_change_risk.py::test_larger_diff_scores_higher PASSED [ 1%]+tests/unit/analysis/test_change_risk.py::test_author_experience_is_protective PASSED [ 1%]+tests/unit/analysis/test_change_risk.py::test_unknown_experience_is_neutral PASSED [ 2%]+tests/unit/analysis/test_change_risk.py::test_top_drivers_sorted_by_magnitude PASSED [ 2%]+tests/unit/analysis/test_change_risk.py::test_features_from_file_changes_aggregates_diffusion PASSED [ 3%]+tests/unit/analysis/test_change_risk.py::test_extract_commit_features_counts_diffusion PASSED [ 3%]+tests/unit/analysis/test_change_risk.py::test_extract_filters_by_extension PASSED [ 4%]+tests/unit/analysis/test_change_risk.py::test_author_experience_accrues PASSED [ 4%]+tests/unit/analysis/test_change_risk.py::test_extract_range_features_aggregates PASSED [ 5%]+tests/unit/analysis/test_change_risk.py::test_score_change_on_real_commit PASSED [ 5%]+tests/unit/analysis/test_change_risk_normalize.py::test_empty_distribution_is_low_zero PASSED [ 6%]+tests/unit/analysis/test_change_risk_normalize.py::test_none_score_is_neutral PASSED [ 6%]+tests/unit/analysis/test_change_risk_normalize.py::test_none_values_dropped_from_distribution PASSED [ 7%]+tests/unit/analysis/test_change_risk_normalize.py::test_midrank_percentile_orders_monotonically PASSED [ 7%]+tests/unit/analysis/test_change_risk_normalize.py::test_ties_share_one_percentile PASSED [ 8%]+tests/unit/analysis/test_change_risk_normalize.py::test_priority_terciles PASSED [ 8%]+tests/unit/analysis/test_change_risk_normalize.py::test_priority_is_repo_relative_not_absolute PASSED [ 8%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_in_degree_positive_is_reachable PASSED [ 9%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_main_carrier_is_reachable PASSED [ 9%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_winmain_carrier_is_reachable PASSED [ 10%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_libfuzzer_entry_carrier_is_reachable PASSED [ 10%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_header_with_referenced_symbol_is_reachable PASSED [ 11%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_header_with_implements_edge_is_reachable PASSED [ 11%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_internal_header_rescued_by_sibling_with_importer PASSED [ 12%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_conditional_alt_pair_rescued PASSED [ 12%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_sibling_of_main_file_is_reachable PASSED [ 13%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_orphan_unrelated_header_is_unreachable PASSED [ 13%]+tests/unit/analysis/test_cpp_reachability.py::TestCppFileReachable::test_orphan_source_with_no_sibling_signal_is_unreachable PASSED [ 14%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_apps_tree_never_flagged PASSED [ 14%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_demos_tree_never_flagged PASSED [ 15%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_examples_tree_never_flagged PASSED [ 15%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_benchmarks_tree_never_flagged PASSED [ 16%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_tools_tree_never_flagged PASSED [ 16%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_tests_perf_fuzz_unit_manual_never_flagged PASSED [ 16%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_test_suffix_files_never_flagged PASSED [ 17%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_port_example_never_flagged PASSED [ 17%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_generated_qt_protobuf_grpc_globs PASSED [ 18%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_generated_yacc_flex_swig_globs PASSED [ 18%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_external_extern_contrib_submodules_globs PASSED [ 19%]+tests/unit/analysis/test_cpp_reachability.py::TestCppNeverFlag::test_ordinary_source_not_flagged PASSED [ 19%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_operator_overloads_protected PASSED [ 20%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_stl_customization_points_protected PASSED [ 20%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_coroutine_machinery_protected PASSED [ 21%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_constructor_destructor_protected PASSED [ 21%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_conversion_operator_protected PASSED [ 22%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_unrelated_language_not_protected PASSED [ 22%]+tests/unit/analysis/test_cpp_reachability.py::TestCppContractMethods::test_random_user_function_not_protected PASSED [ 23%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEntryPointSymbols::test_libfuzzer_entry_recognised PASSED [ 23%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEntryPointSymbols::test_windows_main_variants_recognised PASSED [ 24%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_main_carrier_not_flagged_unreachable PASSED [ 24%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_public_header_with_type_use_not_flagged_unreachable PASSED [ 25%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_operator_overload_not_flagged_unused_export PASSED [ 25%]+tests/unit/analysis/test_cpp_reachability.py::TestCppEndToEnd::test_apps_tree_never_flag_short_circuits PASSED [ 25%]+tests/unit/analysis/test_decision_provenance.py::test_source_rank_ladder_ordering PASSED [ 26%]+tests/unit/analysis/test_decision_provenance.py::test_git_archaeology_aliases_commit_rank PASSED [ 26%]+tests/unit/analysis/test_decision_provenance.py::test_unknown_source_lowest_rank PASSED [ 27%]+tests/unit/analysis/test_decision_provenance.py::test_cli_outranks_adr PASSED [ 27%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_rises_with_rank PASSED [ 28%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_rises_with_corroboration PASSED [ 28%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_decays_for_weak_verification PASSED [ 29%]+tests/unit/analysis/test_decision_provenance.py::test_confidence_bounded PASSED [ 29%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_exact_ignores_whitespace_and_case PASSED [ 30%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_fuzzy_on_paraphrase PASSED [ 30%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_unverified_on_hallucination PASSED [ 31%]+tests/unit/analysis/test_decision_provenance.py::test_verify_quote_unverified_without_source PASSED [ 31%]+tests/unit/analysis/test_decision_provenance.py::test_gate_keeps_grounded_decision PASSED [ 32%]+tests/unit/analysis/test_decision_provenance.py::test_gate_rejects_fully_hallucinated_decision PASSED [ 32%]+tests/unit/analysis/test_decision_provenance.py::test_gate_drops_only_the_hallucinated_field PASSED [ 33%]+tests/unit/analysis/test_decision_provenance.py::test_gate_keeps_unverifiable_when_no_source_text PASSED [ 33%]+tests/unit/analysis/test_decision_sources.py::test_discover_adrs_parses_nygard_template PASSED [ 33%]+tests/unit/analysis/test_decision_sources.py::test_discover_adrs_maps_superseded_status_from_frontmatter PASSED [ 34%]+tests/unit/analysis/test_decision_sources.py::test_mine_changelog_extracts_decision_sections PASSED [ 34%]+tests/unit/analysis/test_decision_sources.py::test_mine_changelog_finds_changelog_under_docs PASSED [ 35%]+tests/unit/analysis/test_decision_sources.py::test_extract_all_runs_deterministic_sources_and_gates PASSED [ 35%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_entry_package_sibling_is_reachable PASSED [ 36%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_imported_sibling_makes_package_reachable PASSED [ 36%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_orphaned_package_is_unreachable PASSED [ 37%]+tests/unit/analysis/test_go_reachability.py::TestGoReachabilityHelper::test_func_init_alone_does_not_rescue_package PASSED [ 37%]+tests/unit/analysis/test_go_reachability.py::TestGoUnreachableFiles::test_entry_package_helper_not_flagged PASSED [ 38%]+tests/unit/analysis/test_go_reachability.py::TestGoUnreachableFiles::test_orphan_package_still_flagged PASSED [ 38%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_test_file PASSED [ 39%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_cmd_main PASSED [ 39%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_root_main PASSED [ 40%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_doc_and_docs_stubs PASSED [ 40%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_magefile PASSED [ 41%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_generated_code PASSED [ 41%]+tests/unit/analysis/test_go_reachability.py::TestGoNeverFlagPatterns::test_ordinary_go_file_not_flagged PASSED [ 41%]+tests/unit/analysis/test_go_reachability.py::TestGoEntrySymbols::test_init_and_testmain_are_entry_symbols PASSED [ 42%]+tests/unit/analysis/test_go_reachability.py::TestGoDynamicMarkers::test_go_directives_present PASSED [ 42%]+tests/unit/analysis/test_go_reachability.py::TestGoUnusedInternals::test_uncalled_private_go_symbol_is_flagged PASSED [ 43%]+tests/unit/analysis/test_go_reachability.py::TestGoUnusedInternals::test_private_type_kinds_not_flagged_as_internal PASSED [ 43%]+tests/unit/analysis/test_go_reachability.py::TestGoUnusedInternals::test_called_private_go_symbol_not_flagged PASSED [ 44%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_bundle_outputs PASSED [ 44%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_minified PASSED [ 45%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_livereload_generated_and_shim PASSED [ 45%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_wasm_exec_glue PASSED [ 46%]+tests/unit/analysis/test_js_never_flag.py::TestJsNeverFlagPatterns::test_ordinary_js_not_flagged PASSED [ 46%]+tests/unit/analysis/test_js_never_flag.py::TestVendoredCNeverFlag::test_deps_vendor_third_party PASSED [ 47%]+tests/unit/analysis/test_js_never_flag.py::TestVendoredCNeverFlag::test_live_c_not_flagged PASSED [ 47%]+tests/unit/analysis/test_jsx_namespace_exempt.py::TestJsxNamespaceExemption::test_intrinsic_elements_in_jsx_namespace_not_flagged PASSED [ 48%]+tests/unit/analysis/test_jsx_namespace_exempt.py::TestJsxNamespaceExemption::test_whitelist_name_outside_jsx_namespace_still_flagged PASSED [ 48%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_in_degree_positive_is_reachable PASSED [ 49%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_sibling_with_importer_rescues PASSED [ 49%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_stereotype_annotated_class_is_reachable PASSED [ 50%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_spring_boot_application_is_reachable PASSED [ 50%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_main_method_is_reachable PASSED [ 50%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_fqn_qualified_annotation_recognised PASSED [ 51%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_orphan_non_annotated_class_is_unreachable PASSED [ 51%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFileReachable::test_kotlin_object_with_companion_main_is_reachable PASSED [ 52%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_module_info_never_flagged PASSED [ 52%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_package_info_never_flagged PASSED [ 53%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_caffeine_test_source_sets_never_flagged PASSED [ 53%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_integration_test_source_set PASSED [ 54%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_test_suffix_files PASSED [ 54%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_generated_roots_never_flagged PASSED [ 55%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmNeverFlag::test_ordinary_main_source_not_flagged PASSED [ 55%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_equals_hashcode_protected PASSED [ 56%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_serialization_protected PASSED [ 56%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_kotlin_data_class_synthesised_protected PASSED [ 57%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_enum_helpers_protected PASSED [ 57%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmContractMethods::test_unrelated_language_not_protected PASSED [ 58%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_spring_stereotypes_present PASSED [ 58%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_routing_annotations_present PASSED [ 58%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_test_markers_present PASSED [ 59%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmFrameworkDecorators::test_lifecycle_and_messaging_present PASSED [ 59%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmEndToEnd::test_service_annotated_class_not_flagged_unreachable PASSED [ 60%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmEndToEnd::test_module_info_not_flagged PASSED [ 60%]+tests/unit/analysis/test_jvm_reachability.py::TestJvmEndToEnd::test_private_post_construct_method_not_flagged_internal PASSED [ 61%]+tests/unit/analysis/test_jvm_reachability.py::TestWorkspaceNeverFlag::test_is_never_flag_node_attr_short_circuits_findings PASSED [ 61%]+tests/unit/analysis/test_jvm_reachability.py::TestHeritageEdgeRescue::test_extended_only_class_is_not_unused_export PASSED [ 62%]+tests/unit/analysis/test_jvm_reachability.py::TestHeritageEdgeRescue::test_implemented_only_interface_is_not_unused_export PASSED [ 62%]+tests/unit/analysis/test_jvm_reachability.py::TestHeritageEdgeRescue::test_type_use_only_class_is_not_unused_export PASSED [ 63%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_loads_valid_json PASSED [ 63%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_returns_none_for_missing_file PASSED [ 64%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_returns_none_for_invalid_json PASSED [ 64%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_handles_minimal_json PASSED [ 65%]+tests/unit/analysis/test_kg_skip_logic.py::TestKGResultFromFile::test_fingerprint_not_loaded PASSED [ 65%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_same_graph_same_fingerprint PASSED [ 66%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_different_nodes_different_fingerprint PASSED [ 66%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_different_edges_different_fingerprint PASSED [ 66%]+tests/unit/analysis/test_kg_skip_logic.py::TestFingerprintDeterminism::test_different_communities_different_fingerprint PASSED [ 67%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_skip_when_fingerprint_matches PASSED [ 67%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_regenerate_when_fingerprint_differs PASSED [ 68%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_force_bypasses_fingerprint PASSED [ 68%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_skip_fails_gracefully_if_file_missing PASSED [ 69%]+tests/unit/analysis/test_kg_skip_logic.py::TestSkipLogicUnit::test_skip_fails_gracefully_if_file_corrupt PASSED [ 69%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_file_nodes PASSED [ 70%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_all_node_types PASSED [ 70%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_test_file_tagged PASSED [ 71%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_entry_point_tagged PASSED [ 71%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_import_edges PASSED [ 72%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_tested_by_edges PASSED [ 72%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_builds_layers_from_communities PASSED [ 73%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_layers_contain_node_ids PASSED [ 73%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_no_communities_gives_empty_layers PASSED [ 74%]+tests/unit/analysis/test_knowledge_graph.py::TestSkeletonBuilder::test_project_metadata PASSED [ 74%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_simple PASSED [ 75%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_moderate PASSED [ 75%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_complex_by_symbols PASSED [ 75%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_complex_by_lines PASSED [ 76%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_edge_simple PASSED [ 76%]+tests/unit/analysis/test_knowledge_graph.py::TestComplexityClassification::test_edge_complex PASSED [ 77%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_python_file PASSED [ 77%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_config_by_extension PASSED [ 78%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_config_by_flag PASSED [ 78%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_dockerfile PASSED [ 79%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_markdown PASSED [ 79%]+tests/unit/analysis/test_knowledge_graph.py::TestFileTypeClassification::test_makefile PASSED [ 80%]+tests/unit/analysis/test_knowledge_graph.py::TestSlugify::test_normal PASSED [ 80%]+tests/unit/analysis/test_knowledge_graph.py::TestSlugify::test_special_chars PASSED [ 81%]+tests/unit/analysis/test_knowledge_graph.py::TestSlugify::test_empty PASSED [ 81%]+tests/unit/analysis/test_knowledge_graph.py::TestFingerprint::test_stability PASSED [ 82%]+tests/unit/analysis/test_knowledge_graph.py::TestFingerprint::test_changes_on_graph_change PASSED [ 82%]+tests/unit/analysis/test_knowledge_graph.py::TestFingerprint::test_length PASSED [ 83%]+tests/unit/analysis/test_knowledge_graph.py::TestToDict::test_schema PASSED [ 83%]+tests/unit/analysis/test_knowledge_graph.py::TestToDict::test_roundtrip_json PASSED [ 83%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_build_rs_never_flagged PASSED [ 84%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_examples_never_flagged PASSED [ 84%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_benches_never_flagged PASSED [ 85%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_tests_dir_never_flagged PASSED [ 85%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_bin_target_never_flagged PASSED [ 86%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverFlagPatterns::test_fuzz_target_never_flagged PASSED [ 86%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverPackageDirs::test_tests_dir_excluded PASSED [ 87%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverPackageDirs::test_benches_dir_excluded PASSED [ 87%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustNeverPackageDirs::test_fuzz_dir_excluded PASSED [ 88%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustDynamicMarkers::test_proc_macro_detected PASSED [ 88%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustDynamicMarkers::test_doc_hidden_detected PASSED [ 89%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroCrateDetection::test_proc_macro_crate_detected PASSED [ 89%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroCrateDetection::test_non_proc_macro_crate_not_detected PASSED [ 90%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroCrateDetection::test_proc_macro_parsed_from_toml PASSED [ 90%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustUnusedInternalsSkipped::test_rust_private_function_not_flagged PASSED [ 91%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestRustUnusedInternalsSkipped::test_python_private_function_still_flagged PASSED [ 91%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_proc_macro_function_not_flagged PASSED [ 91%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_proc_macro_derive_not_flagged PASSED [ 92%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_proc_macro_attribute_not_flagged PASSED [ 92%]+tests/unit/analysis/test_rust_dead_code_regression.py::TestProcMacroExemptFromUnusedExports::test_regular_rust_public_function_still_flagged PASSED [ 93%]+tests/unit/analysis/test_ts_never_flag.py::TestTestSpecFiles::test_test_suffix_variants PASSED [ 93%]+tests/unit/analysis/test_ts_never_flag.py::TestTestSpecFiles::test_tests_and_mocks_dirs PASSED [ 94%]+tests/unit/analysis/test_ts_never_flag.py::TestTestSpecFiles::test_ordinary_source_not_flagged PASSED [ 94%]+tests/unit/analysis/test_ts_never_flag.py::TestStoriesAndBench::test_storybook_stories PASSED [ 95%]+tests/unit/analysis/test_ts_never_flag.py::TestStoriesAndBench::test_bench_files PASSED [ 95%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_next_env_and_gen PASSED [ 96%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_next_app_router_conventions PASSED [ 96%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_remix_entries PASSED [ 97%]+tests/unit/analysis/test_ts_never_flag.py::TestCodegenAndConvention::test_sveltekit_conventions PASSED [ 97%]+tests/unit/analysis/test_ts_never_flag.py::TestNeverFlagDoesNotLeak::test_python_not_affected PASSED [ 98%]+tests/unit/analysis/test_ts_never_flag.py::TestNeverFlagDoesNotLeak::test_go_not_affected PASSED [ 98%]+tests/unit/analysis/test_ts_never_flag.py::TestEntryPointSymbolNames::test_nextjs_route_exports_included PASSED [ 99%]+tests/unit/analysis/test_ts_never_flag.py::TestEntryPointSymbolNames::test_remix_route_exports_included PASSED [ 99%]+tests/unit/analysis/test_ts_never_flag.py::TestEntryPointSymbolNames::test_common_names_excluded PASSED [100%]++============================= 212 passed in 3.69s =============================diff --git a/tests/fixtures/distill/rg_flood.txt b/tests/fixtures/distill/rg_flood.txtnew file mode 100644index 000000000..1fb64a647--- /dev/null+++ b/tests/fixtures/distill/rg_flood.txt@@ -0,0 +1,286 @@+packages\cli\src\repowise\cli\commands\costs_cmd.py:21:def _parse_date(value: str | None) -> datetime | None:+packages\cli\src\repowise\cli\commands\costs_cmd.py:78:def costs_command(+packages\cli\src\repowise\cli\commands\costs_cmd.py:217:async def _query_costs(+packages\cli\src\repowise\cli\commands\dead_code_cmd.py:71:def dead_code_command(+packages\cli\src\repowise\cli\commands\augment_cmd.py:74:def augment_command(client: str | None = None) -> None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:85:def _run_augment(*, client: str | None = None) -> None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:116:def _emit_response(event: str, context: str) -> None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:143:def _claim_emission(event: str, context: str) -> bool:+packages\cli\src\repowise\cli\commands\augment_cmd.py:190:def _handle_codex_context_event(event: str, cwd: str) -> str | None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:213:def _handle_search_post(+packages\cli\src\repowise\cli\commands\augment_cmd.py:249:def _looks_like_path_lookup(pattern: str) -> bool:+packages\cli\src\repowise\cli\commands\augment_cmd.py:299:def _extract_output_text(tool_output: object) -> str:+packages\cli\src\repowise\cli\commands\augment_cmd.py:330:def _count_search_results(output_text: str) -> int:+packages\cli\src\repowise\cli\commands\augment_cmd.py:354:async def _search_enrich(+packages\cli\src\repowise\cli\commands\augment_cmd.py:398:async def _rescue(+packages\cli\src\repowise\cli\commands\augment_cmd.py:442: def _rank(row):+packages\cli\src\repowise\cli\commands\augment_cmd.py:484:async def _triage(+packages\cli\src\repowise\cli\commands\augment_cmd.py:553:def _name_variants(token: str) -> list[str]:+packages\cli\src\repowise\cli\commands\augment_cmd.py:598:def _handle_post_tool_use(+packages\cli\src\repowise\cli\commands\augment_cmd.py:619:def _handle_post_edit_use(cwd: str) -> str | None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:636:def _handle_bash_post(tool_input: dict, tool_output: object, cwd: str) -> str | None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:733:def _read_in_flight_marker(repo_path: "object") -> dict | None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:783:def _already_warned(repo_path: object, head: str) -> bool:+packages\cli\src\repowise\cli\commands\augment_cmd.py:795:def _record_warning(repo_path: object, head: str) -> None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:803:def _extract_exit_code(tool_output: dict) -> int | None:+packages\cli\src\repowise\cli\commands\augment_cmd.py:821:def _find_repo_root(cwd: Path) -> Path | None:+packages\cli\src\repowise\cli\commands\delete_cmd.py:21:def delete_command(repo_id: str | None, force: bool, path: str | None) -> None:+packages\cli\src\repowise\cli\commands\delete_cmd.py:35: async def _run() -> None:+packages\cli\src\repowise\cli\commands\doctor_cmd.py:21:def _check(name: str, ok: bool, detail: str = "") -> tuple[str, str, str]:+packages\cli\src\repowise\cli\commands\doctor_cmd.py:26:def _print_cli_version_status() -> None:+packages\cli\src\repowise\cli\commands\doctor_cmd.py:79:def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:+packages\cli\src\repowise\cli\commands\doctor_cmd.py:108: async def _check_db():+packages\cli\src\repowise\cli\commands\doctor_cmd.py:175: async def _check_stale():+packages\cli\src\repowise\cli\commands\doctor_cmd.py:210: async def _check_stores():+packages\cli\src\repowise\cli\commands\doctor_cmd.py:294: async def _check_coordinator():+packages\cli\src\repowise\cli\commands\doctor_cmd.py:377: async def _repair():+packages\cli\src\repowise\cli\commands\doctor_cmd.py:480:def doctor_command(+packages\cli\src\repowise\cli\commands\doctor_cmd.py:557:def _run_workspace_checks(+packages\cli\src\repowise\cli\commands\doctor_cmd.py:655:def _check_mcp_registered(ws_root: _DoctorPath) -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:21:def _resolve_decision_repo(path: str | None):+packages\cli\src\repowise\cli\commands\decision_cmd.py:41:def decision_group() -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:52:def decision_add(path: str | None) -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:81: async def _persist() -> str:+packages\cli\src\repowise\cli\commands\decision_cmd.py:142:def decision_list(+packages\cli\src\repowise\cli\commands\decision_cmd.py:152: async def _query() -> list:+packages\cli\src\repowise\cli\commands\decision_cmd.py:233:def decision_show(decision_id: str, path: str | None) -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:237: async def _query():+packages\cli\src\repowise\cli\commands\decision_cmd.py:312:def decision_confirm(decision_id: str, path: str | None) -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:316: async def _update():+packages\cli\src\repowise\cli\commands\decision_cmd.py:351:def decision_dismiss(decision_id: str, path: str | None) -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:359: async def _delete():+packages\cli\src\repowise\cli\commands\decision_cmd.py:395:def decision_deprecate(decision_id: str, path: str | None, superseded_by: str | None) -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:399: async def _update():+packages\cli\src\repowise\cli\commands\decision_cmd.py:435:def decision_health(path: str | None) -> None:+packages\cli\src\repowise\cli\commands\decision_cmd.py:439: async def _query():+packages\cli\src\repowise\cli\commands\expand_cmd.py:24:def expand_command(ref: str, query: str | None) -> None:+packages\cli\src\repowise\cli\commands\expand_cmd.py:59:def _candidate_stores() -> list[Path]:+packages\cli\src\repowise\cli\commands\expand_cmd.py:71:def default_store_path_for(root: Path) -> Path:+packages\cli\src\repowise\cli\commands\expand_cmd.py:77:def _echo_safely(text: str) -> None:+packages\cli\src\repowise\cli\commands\distill_cmd.py:27:def distill_command(command: tuple[str, ...]) -> None:+packages\cli\src\repowise\cli\commands\distill_cmd.py:64:def _render_command(tokens: tuple[str, ...]) -> str:+packages\cli\src\repowise\cli\commands\distill_cmd.py:75:def _distill_or_raw(output: str, command_str: str, exit_code: int) -> str:+packages\cli\src\repowise\cli\commands\distill_cmd.py:97:def _load_distill_config(repo_root: Path | None) -> tuple[bool, tuple[str, ...]]:+packages\cli\src\repowise\cli\commands\distill_cmd.py:112:def _echo_safely(text: str) -> None:+packages\cli\src\repowise\cli\commands\claude_md_cmd.py:54:def claude_md_command(+packages\cli\src\repowise\cli\commands\claude_md_cmd.py:109:async def _generate(+packages\cli\src\repowise\cli\commands\claude_md_cmd.py:161:def _generate_workspace(+packages\core\src\repowise\core\distill\markers.py:23:def render_marker(ref: str, lines_omitted: int, tokens_omitted: int) -> str:+packages\core\src\repowise\core\distill\markers.py:32:def parse_marker_refs(text: str) -> list[str]:+packages\core\src\repowise\core\distill\markers.py:44:def is_valid_ref(ref: str) -> bool:+packages\core\src\repowise\core\distill\budget.py:14:def savings_pct(raw_tokens: int, distilled_tokens: int) -> float:+packages\core\src\repowise\core\distill\registry.py:21: def __init__(self) -> None:+packages\core\src\repowise\core\distill\registry.py:24: def register(self, filter_cls: F) -> F:+packages\core\src\repowise\core\distill\registry.py:29: def filters(self) -> tuple[OutputFilter, ...]:+packages\core\src\repowise\core\distill\registry.py:34: def get(self, name: str) -> OutputFilter | None:+packages\core\src\repowise\core\distill\registry.py:42: def _ensure_loaded() -> None:+packages\cli\src\repowise\cli\commands\export_cmd.py:43:def export_command(+packages\cli\src\repowise\cli\commands\export_cmd.py:59: async def _load_pages():+packages\core\src\repowise\core\distill\router.py:32:def normalize_command(command: str) -> str:+packages\core\src\repowise\core\distill\router.py:45:def select_filter(+packages\cli\src\repowise\cli\commands\health_cmd.py:92:def health_command(+packages\cli\src\repowise\cli\commands\health_cmd.py:363:def _effort_bucket(nloc: int) -> tuple[str, int]:+packages\cli\src\repowise\cli\commands\health_cmd.py:373:def _render_refactoring_targets(+packages\cli\src\repowise\cli\commands\health_cmd.py:439:def _render_trend(repo_path: object, *, fmt: str) -> None:+packages\cli\src\repowise\cli\commands\health_cmd.py:458: async def _fetch() -> tuple[list[dict], object]:+packages\cli\src\repowise\cli\commands\health_cmd.py:522:def _persist_health(+packages\cli\src\repowise\cli\commands\health_cmd.py:550: async def _do() -> None:+packages\cli\src\repowise\cli\commands\hook_cmd.py:16:def hook_group() -> None:+packages\cli\src\repowise\cli\commands\hook_cmd.py:20:def _hook_target(+packages\cli\src\repowise\cli\commands\hook_cmd.py:50:def hook_install(path: str | None, workspace: bool, no_workspace: bool) -> None:+packages\cli\src\repowise\cli\commands\hook_cmd.py:83:def hook_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:+packages\cli\src\repowise\cli\commands\hook_cmd.py:116:def hook_status(path: str | None, workspace: bool, no_workspace: bool) -> None:+packages\core\src\repowise\core\distill\__init__.py:61: def savings_pct(self) -> float:+packages\core\src\repowise\core\distill\__init__.py:65:def distill_output(+packages\cli\src\repowise\cli\commands\mcp_cmd.py:27:def mcp_command(path: str | None, transport: str, port: int) -> None:+packages\cli\src\repowise\cli\commands\reindex_cmd.py:27:def reindex_command(path: str | None, embedder: str, batch_size: int) -> None:+packages\cli\src\repowise\cli\commands\reindex_cmd.py:45:async def _reindex(repo_path, embedder_name: str, batch_size: int) -> None:+packages\core\src\repowise\core\distill\tracking.py:15:def record_saving(+packages\core\src\repowise\core\distill\tracking.py:36:def savings_summary(conn: sqlite3.Connection) -> dict[str, Any]:+packages\cli\src\repowise\cli\commands\search_cmd.py:46:def search_command(+packages\cli\src\repowise\cli\commands\search_cmd.py:133:def _search_fulltext(repo_path, query: str, limit: int) -> None:+packages\cli\src\repowise\cli\commands\search_cmd.py:134: async def _run():+packages\cli\src\repowise\cli\commands\search_cmd.py:148:def _search_semantic(repo_path, query: str, limit: int) -> None:+packages\cli\src\repowise\cli\commands\search_cmd.py:149: async def _run():+packages\cli\src\repowise\cli\commands\search_cmd.py:183:def _search_symbol(repo_path, query: str, limit: int) -> None:+packages\cli\src\repowise\cli\commands\search_cmd.py:184: async def _run():+packages\cli\src\repowise\cli\commands\search_cmd.py:224:def _display_results(results, title: str) -> None:+packages\cli\src\repowise\cli\commands\search_cmd.py:252:def _collect_fulltext(repo_path, query: str, limit: int):+packages\cli\src\repowise\cli\commands\search_cmd.py:253: async def _run():+packages\cli\src\repowise\cli\commands\search_cmd.py:266:def _collect_semantic(repo_path, query: str, limit: int):+packages\cli\src\repowise\cli\commands\search_cmd.py:267: async def _run():+packages\cli\src\repowise\cli\commands\search_cmd.py:298:def _collect_symbol(repo_path, query: str, limit: int):+packages\cli\src\repowise\cli\commands\search_cmd.py:299: async def _run():+packages\cli\src\repowise\cli\commands\search_cmd.py:322:def _display_results_multi(pairs, title: str) -> None:+packages\cli\src\repowise\cli\commands\search_cmd.py:344:def _render_symbol_rows(pairs, query: str, limit: int, *, multi: bool) -> None:+packages\core\src\repowise\core\distill\store.py:59:def default_store_path(start: Path | None = None) -> Path:+packages\core\src\repowise\core\distill\store.py:77:def content_ref(content: str) -> str:+packages\core\src\repowise\core\distill\store.py:89: def __init__(+packages\core\src\repowise\core\distill\store.py:108: def open_default(cls, start: Path | None = None) -> OmissionStore:+packages\core\src\repowise\core\distill\store.py:114: def put(+packages\core\src\repowise\core\distill\store.py:138: def get(self, ref: str, *, query: str | None = None) -> str | None:+packages\core\src\repowise\core\distill\store.py:158: def prune(self) -> None:+packages\core\src\repowise\core\distill\store.py:183: def record_saving(+packages\core\src\repowise\core\distill\store.py:202: def savings_summary(self) -> dict:+packages\core\src\repowise\core\distill\store.py:208: def close(self) -> None:+packages\core\src\repowise\core\distill\store.py:211: def __enter__(self) -> OmissionStore:+packages\core\src\repowise\core\distill\store.py:214: def __exit__(self, *exc: object) -> None:+packages\core\src\repowise\core\distill\store.py:218:def _filter_lines(content: str, query: str) -> str:+packages\cli\src\repowise\cli\commands\risk_cmd.py:47:def risk_command(revspec: str, repo_path: str, ext: str | None, fmt: str) -> None:+packages\core\src\repowise\core\distill\filters\build_output.py:51: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\build_output.py:54: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\build_output.py:59: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\build_output.py:73: def emit(line: str) -> None:+packages\core\src\repowise\core\distill\filters\build_output.py:83: def flush_repeats() -> None:+packages\core\src\repowise\core\distill\filters\base.py:32:def is_error_line(line: str) -> bool:+packages\core\src\repowise\core\distill\filters\base.py:37:def cap_block(lines: list[str], head: int, tail: int) -> list[str]:+packages\core\src\repowise\core\distill\filters\base.py:67: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\base.py:71: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\base.py:76: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\cli\src\repowise\cli\commands\init_cmd\command.py:81:def _run_generation_phase(+packages\cli\src\repowise\cli\commands\init_cmd\command.py:349:def init_command(+packages\cli\src\repowise\cli\commands\init_cmd\command.py:671: async def _index_with_resume() -> Any:+packages\core\src\repowise\core\distill\filters\git_diff.py:32: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\git_diff.py:35: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\git_diff.py:39: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\git_diff.py:70: def __init__(self, path: str) -> None:+packages\core\src\repowise\core\distill\filters\git_diff.py:77:def _split_file_blocks(output: str) -> list[_FileBlock]:+packages\cli\src\repowise\cli\commands\init_cmd\persistence.py:26:async def build_resume_controller(repo_path: Path, *, resume: bool) -> tuple[Any, Any]:+packages\cli\src\repowise\cli\commands\init_cmd\persistence.py:41:async def persist_result(result: Any, repo_path: Path) -> None:+packages\cli\src\repowise\cli\commands\init_cmd\persistence.py:139:def git_tier_for_run_mode(run_mode: str) -> str:+packages\cli\src\repowise\cli\commands\init_cmd\persistence.py:149:def effective_run_mode_for_resume(repo_path: Path, run_mode: str, resume: bool) -> str:+packages\cli\src\repowise\cli\commands\init_cmd\persistence.py:169:def save_full_state_and_config(+packages\cli\src\repowise\cli\commands\init_cmd\persistence.py:183: async def _count_db_pages() -> int:+packages\core\src\repowise\core\distill\filters\file_listing.py:35: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\file_listing.py:38: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\file_listing.py:45: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\file_listing.py:55:def _distill_paths(paths: list[str]) -> str:+packages\core\src\repowise\core\distill\filters\file_listing.py:75:def _distill_ls_long(lines: list[str]) -> str:+packages\cli\src\repowise\cli\commands\init_cmd\generation.py:48:def confirm_cost_gate(message: str) -> bool:+packages\cli\src\repowise\cli\commands\init_cmd\generation.py:63:def cost_gate_declined(est: Any, *, yes: bool, message: str) -> bool:+packages\cli\src\repowise\cli\commands\init_cmd\generation.py:72:def format_cost(est: Any) -> str:+packages\cli\src\repowise\cli\commands\init_cmd\generation.py:85:def select_coverage(+packages\cli\src\repowise\cli\commands\init_cmd\generation.py:152:def _enrich_knowledge_graph(+packages\cli\src\repowise\cli\commands\init_cmd\generation.py:172: def _run() -> Any:+packages\cli\src\repowise\cli\commands\init_cmd\generation.py:202:def run_repo_generation(+packages\core\src\repowise\core\distill\filters\git_status.py:62: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\git_status.py:65: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\git_status.py:71: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\git_status.py:90:def _render_branch_line(output: str) -> str | None:+packages\core\src\repowise\core\distill\filters\git_status.py:113:def _parse_entries(output: str) -> tuple[list[str], dict[str, int]]:+packages\cli\src\repowise\cli\commands\init_cmd\workspace.py:73:def _run_workspace_generation(+packages\cli\src\repowise\cli\commands\init_cmd\workspace.py:147:def _workspace_generation_provider_for_repo(provider: Any, repo_path: Path) -> Any:+packages\cli\src\repowise\cli\commands\init_cmd\workspace.py:199:def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtx) -> _RepoOutcome:+packages\cli\src\repowise\cli\commands\init_cmd\workspace.py:370:def _run_cross_repo_analysis(ws_config: Any, root: Any, selected: list[Any], errors: list) -> None:+packages\cli\src\repowise\cli\commands\init_cmd\workspace.py:384:def _workspace_init(+packages\cli\src\repowise\cli\commands\workspace_cmd.py:28:def _require_workspace(start: Path | None = None) -> tuple[Path, "WorkspaceConfig"]: # type: ignore[name-defined]+packages\cli\src\repowise\cli\commands\workspace_cmd.py:51:def workspace_group() -> None:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:62:def workspace_list(path: str | None) -> None:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:132:def _query_repo_counts(repo_path: Path) -> tuple[int, int]:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:140: async def _query() -> tuple[int, int]:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:188:def _format_relative_time(iso_timestamp: str | None) -> str:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:240:def workspace_add(+packages\cli\src\repowise\cli\commands\workspace_cmd.py:332:def _resolve_docs_flag(+packages\cli\src\repowise\cli\commands\workspace_cmd.py:387:def _run_index_for_repo(+packages\cli\src\repowise\cli\commands\workspace_cmd.py:457: async def _do_index() -> tuple[int, int, int]:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:568:def _generate_docs_for_added_repo(+packages\cli\src\repowise\cli\commands\workspace_cmd.py:632: async def _do() -> int:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:668:def workspace_remove(alias: str) -> None:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:722:def workspace_scan(path: str | None, yes: bool) -> None:+packages\cli\src\repowise\cli\commands\workspace_cmd.py:797:def workspace_set_default(alias: str) -> None:+packages\cli\src\repowise\cli\commands\init_cmd\_interactive.py:12:def offer_hook_install(+packages\core\src\repowise\core\distill\filters\test_output.py:56: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\test_output.py:59: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\test_output.py:62: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\test_output.py:76:def _detect_format(output: str) -> str | None:+packages\core\src\repowise\core\distill\filters\test_output.py:95:def _distill_pytest(lines: list[str]) -> str:+packages\core\src\repowise\core\distill\filters\test_output.py:102: def flush_failure_section() -> None:+packages\core\src\repowise\core\distill\filters\test_output.py:171:def _distill_go(lines: list[str]) -> str:+packages\core\src\repowise\core\distill\filters\test_output.py:201:def _distill_cargo(lines: list[str]) -> str:+packages\core\src\repowise\core\distill\filters\test_output.py:230:def _distill_jest(lines: list[str]) -> str:+packages\core\src\repowise\core\distill\filters\test_output.py:237: def flush() -> None:+packages\core\src\repowise\core\distill\filters\test_output.py:277:def _distill_generic(lines: list[str]) -> str:+packages\cli\src\repowise\cli\commands\init_cmd\reporting.py:22:def show_analysis_summary(result: Any) -> None:+packages\cli\src\repowise\cli\commands\init_cmd\reporting.py:76:def show_completion(+packages\cli\src\repowise\cli\commands\init_cmd\reporting.py:205:def show_workspace_completion(+packages\cli\src\repowise\cli\commands\watch_cmd.py:26:def _watch_single_repo(+packages\cli\src\repowise\cli\commands\watch_cmd.py:42: def _on_trigger() -> None:+packages\cli\src\repowise\cli\commands\watch_cmd.py:71: def on_any_event(self, event):+packages\cli\src\repowise\cli\commands\watch_cmd.py:107:def _watch_workspace(+packages\cli\src\repowise\cli\commands\watch_cmd.py:133: def _make_trigger(alias: str) -> callable:+packages\cli\src\repowise\cli\commands\watch_cmd.py:136: def _on_trigger() -> None:+packages\cli\src\repowise\cli\commands\watch_cmd.py:176: def __init__(self, alias: str, repo_path: Path):+packages\cli\src\repowise\cli\commands\watch_cmd.py:181: def on_any_event(self, event):+packages\cli\src\repowise\cli\commands\watch_cmd.py:256:def watch_command(+packages\core\src\repowise\core\distill\filters\git_log.py:33: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\git_log.py:36: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\git_log.py:43: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\git_log.py:56:def _parse_full_format(lines: list[str]) -> list[tuple[str, str, str]]:+packages\core\src\repowise\core\distill\filters\git_log.py:75:def _short_date(date: str) -> str:+packages\core\src\repowise\core\distill\filters\git_log.py:83:def _render(commits: list[tuple[str, str, str]]) -> str:+packages\core\src\repowise\core\distill\filters\search_results.py:46: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\search_results.py:49: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\search_results.py:56: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\search_results.py:63:def group_search_matches(output: str) -> "OrderedDict[str, list[tuple[int, str]]] | None":+packages\core\src\repowise\core\distill\filters\search_results.py:105:def render_search_digest(+packages\cli\src\repowise\cli\commands\init_cmd\_generation_persist.py:47:async def run_generation_with_persistence(+packages\cli\src\repowise\cli\commands\init_cmd\_generation_persist.py:98: async def _consumer() -> None:+packages\cli\src\repowise\cli\commands\init_cmd\_generation_persist.py:120: def _on_page_ready(page: Any) -> None:+packages\core\src\repowise\core\distill\filters\logs.py:42: def matches_command(self, command: str) -> bool:+packages\core\src\repowise\core\distill\filters\logs.py:45: def matches_content(self, output: str) -> bool:+packages\core\src\repowise\core\distill\filters\logs.py:52: def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+packages\core\src\repowise\core\distill\filters\logs.py:105:def _template(line: str) -> str:+packages\cli\src\repowise\cli\commands\status_cmd.py:26:def _query_repo_counts(repo_path: Path) -> tuple[int, int]:+packages\cli\src\repowise\cli\commands\status_cmd.py:29: async def _query() -> tuple[int, int]:+packages\cli\src\repowise\cli\commands\status_cmd.py:86:def _query_page_count(repo_path: Path) -> int:+packages\cli\src\repowise\cli\commands\status_cmd.py:89: async def _query() -> int:+packages\cli\src\repowise\cli\commands\status_cmd.py:129:def _query_health_line(repo_path: Path) -> str | None:+packages\cli\src\repowise\cli\commands\status_cmd.py:141: async def _q() -> dict | None:+packages\cli\src\repowise\cli\commands\status_cmd.py:197:def _format_relative_time(iso_timestamp: str | None) -> str:+packages\cli\src\repowise\cli\commands\status_cmd.py:221:def _workspace_status(target: CommandTarget) -> None:+packages\cli\src\repowise\cli\commands\status_cmd.py:345:def status_command(path: str | None, workspace: bool, no_workspace: bool) -> None:+packages\cli\src\repowise\cli\commands\status_cmd.py:388: async def _query_pages():+packages\cli\src\repowise\cli\commands\serve_cmd.py:21:def _setup_embedder() -> None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:105:def _get_or_prompt_api_key(embedder: str) -> str:+packages\cli\src\repowise\cli\commands\serve_cmd.py:125:def _set_api_key_env(embedder: str, key: str) -> None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:136:def _save_global_embedder(embedder: str, api_key: str) -> None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:159:def _load_local_provider_config() -> None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:193:def _is_port_free(host: str, port: int) -> bool:+packages\cli\src\repowise\cli\commands\serve_cmd.py:203:def _find_free_port(host: str, preferred: int, label: str, max_attempts: int = 20) -> int:+packages\cli\src\repowise\cli\commands\serve_cmd.py:240:def _node_available() -> str | None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:245:def _node_major_version(node: str) -> int | None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:270:def _npm_available() -> str | None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:275:def _web_is_cached(version: str) -> bool:+packages\cli\src\repowise\cli\commands\serve_cmd.py:283:def _find_local_web() -> Path | None:+packages\cli\src\repowise\cli\commands\serve_cmd.py:301:def _local_build_is_stale(web_dir: Path) -> bool:+packages\cli\src\repowise\cli\commands\serve_cmd.py:352:def _download_web(version: str) -> bool:+packages\cli\src\repowise\cli\commands\serve_cmd.py:396:def _build_local_web(web_dir: Path, npm: str) -> bool:+packages\cli\src\repowise\cli\commands\serve_cmd.py:421:def _start_frontend(+packages\cli\src\repowise\cli\commands\serve_cmd.py:484:def serve_command(+packages\cli\src\repowise\cli\commands\upgrade_flow.py:46:def _reparse(repo_path: Path, exclude_patterns: list[str]) -> tuple[list[Any], dict[str, bytes], Any]:+packages\cli\src\repowise\cli\commands\upgrade_flow.py:73:async def _backfill_git(+packages\cli\src\repowise\cli\commands\upgrade_flow.py:132:async def _run_upgrade(+packages\cli\src\repowise\cli\commands\upgrade_flow.py:304:def upgrade_to_full(+packages\cli\src\repowise\cli\commands\update_cmd.py:41:def _infer_legacy_docs_enabled(state: dict) -> bool:+packages\cli\src\repowise\cli\commands\update_cmd.py:57:def _build_update_vector_store(repo_path: Any, cfg: dict) -> Any | None:+packages\cli\src\repowise\cli\commands\update_cmd.py:77:def _resolve_index_only_mode(+packages\cli\src\repowise\cli\commands\update_cmd.py:103:async def _persist_partial_health(session: Any, repo_id: str, report: Any) -> None:+packages\cli\src\repowise\cli\commands\update_cmd.py:132:async def _persist_incremental_commits(session: Any, repo_id: str, repo_path: Any) -> None:+packages\cli\src\repowise\cli\commands\update_cmd.py:171:def _workspace_update(+packages\cli\src\repowise\cli\commands\update_cmd.py:230: def _on_start(alias: str) -> None:+packages\cli\src\repowise\cli\commands\update_cmd.py:233: def _on_done(result: RepoUpdateResult) -> None:+packages\cli\src\repowise\cli\commands\update_cmd.py:280:def _refresh_workspace_editor_project_files(+packages\cli\src\repowise\cli\commands\update_cmd.py:317:def _build_filtered_changed_paths(file_diffs: list, exclude_patterns: list[str]) -> list[str]:+packages\cli\src\repowise\cli\commands\update_cmd.py:328:def _build_repo_graph(+packages\cli\src\repowise\cli\commands\update_cmd.py:416:def _rebuild_graph_and_git(+packages\cli\src\repowise\cli\commands\update_cmd.py:478:def _run_partial_analysis(+packages\cli\src\repowise\cli\commands\update_cmd.py:544:def _persist_index_only_update(+packages\cli\src\repowise\cli\commands\update_cmd.py:558: async def _persist_index_only() -> None:+packages\cli\src\repowise\cli\commands\update_cmd.py:639:def _render_update_report(+packages\cli\src\repowise\cli\commands\update_cmd.py:663:def _git_metadata_to_dict(gm: Any) -> dict[str, Any]:+packages\cli\src\repowise\cli\commands\update_cmd.py:700:def _run_full_health_rescore(+packages\cli\src\repowise\cli\commands\update_cmd.py:739: async def _rescore() -> None:+packages\cli\src\repowise\cli\commands\update_cmd.py:931:def update_command(+packages\cli\src\repowise\cli\commands\update_cmd.py:1285: async def _run_evolution() -> dict:+packages\cli\src\repowise\cli\commands\update_cmd.py:1337: async def _load_prior() -> dict[str, object]:+packages\cli\src\repowise\cli\commands\update_cmd.py:1384: async def _persist() -> None:diff --git a/tests/fixtures/distill/skeleton_artifacts.src.txt b/tests/fixtures/distill/skeleton_artifacts.src.txtnew file mode 100644index 000000000..c0ca23234--- /dev/null+++ b/tests/fixtures/distill/skeleton_artifacts.src.txt@@ -0,0 +1,539 @@+"use client";++/**+ * Per-type chat artifact renderers. Dispatched by `ArtifactPanel` based on+ * `artifact.type`. Variant shapes are declared in+ * `@repowise-dev/types/chat`. Each renderer is intentionally small and+ * presentation-only — heavier visualisations (full graph canvases, tables,+ * etc.) belong in their own subpackages and are linked to from here.+ */++import {+ Activity,+ AlertTriangle,+ ArrowRight,+ Box,+ CheckCircle2,+ FileCode,+ GitBranch,+ Layers,+ Search,+ ShieldAlert,+ Sparkles,+} from "lucide-react";+import type {+ ContextArtifactData,+ DeadCodeArtifactData,+ DecisionsArtifactData,+ DiagramArtifactData,+ GraphPathArtifactData,+ OverviewArtifactData,+ RiskReportArtifactData,+ SearchResultsArtifactData,+} from "@repowise-dev/types/chat";+import { ChatMarkdown } from "./chat-markdown";+import { MermaidDiagram } from "../wiki/mermaid-diagram";+import { getPageTypeLabel } from "../lib/page-types";++// ---------------------------------------------------------------------------+// Shared atoms+// ---------------------------------------------------------------------------++function StatRow({ label, value }: { label: string; value: React.ReactNode }) {+ return (+ <div className="flex items-baseline justify-between gap-3 text-xs">+ <span className="text-[var(--color-text-tertiary)]">{label}</span>+ <span className="font-mono tabular-nums text-[var(--color-text-secondary)]">+ {value}+ </span>+ </div>+ );+}++function SectionTitle({+ icon: Icon,+ children,+}: {+ icon: React.ComponentType<{ className?: string }>;+ children: React.ReactNode;+}) {+ return (+ <div className="flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mb-2">+ <Icon className="h-3 w-3" />+ <span>{children}</span>+ </div>+ );+}++function FilePathChip({ path }: { path: string }) {+ return (+ <span className="inline-flex items-center gap-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[10px] font-mono text-[var(--color-text-secondary)]">+ <FileCode className="h-2.5 w-2.5 opacity-60" />+ <span className="truncate max-w-[200px]" title={path}>+ {path}+ </span>+ </span>+ );+}++// ---------------------------------------------------------------------------+// Overview+// ---------------------------------------------------------------------------++export function OverviewRenderer({ data }: { data: OverviewArtifactData }) {+ const langs = Object.entries(data.languages ?? {})+ .sort((a, b) => (b[1] as number) - (a[1] as number))+ .slice(0, 6);+ return (+ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-2">+ <StatRow label="Files" value={data.total_files.toLocaleString()} />+ <StatRow label="Symbols" value={data.total_symbols.toLocaleString()} />+ <StatRow label="Hotspots" value={data.hotspot_count.toLocaleString()} />+ <StatRow label="Monorepo" value={data.is_monorepo ? "yes" : "no"} />+ </div>++ {langs.length > 0 && (+ <div>+ <SectionTitle icon={Layers}>Languages</SectionTitle>+ <div className="space-y-1">+ {langs.map(([lang, count]) => (+ <StatRow+ key={lang}+ label={lang}+ value={(count as number).toLocaleString()}+ />+ ))}+ </div>+ </div>+ )}++ {data.modules.length > 0 && (+ <div>+ <SectionTitle icon={Box}>Modules</SectionTitle>+ <div className="flex flex-wrap gap-1">+ {data.modules.slice(0, 12).map((m) => (+ <span+ key={m}+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[10px] font-mono text-[var(--color-text-secondary)]"+ >+ {m}+ </span>+ ))}+ </div>+ </div>+ )}++ {data.entry_points.length > 0 && (+ <div>+ <SectionTitle icon={ArrowRight}>Entry points</SectionTitle>+ <div className="space-y-1">+ {data.entry_points.slice(0, 5).map((ep) => (+ <FilePathChip key={ep} path={ep} />+ ))}+ </div>+ </div>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Context+// ---------------------------------------------------------------------------++export function ContextRenderer({ data }: { data: ContextArtifactData }) {+ const targets = Object.entries(data.targets ?? {});+ if (targets.length === 0) {+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">No context loaded.</p>+ );+ }+ return (+ <div className="space-y-5">+ {targets.map(([target, info]) => {+ const md = info.docs?.content_md ?? "";+ return (+ <div key={target}>+ <h3 className="text-xs font-mono text-[var(--color-accent-primary)] mb-2 break-all">+ {target}+ </h3>+ {md ? (+ <ChatMarkdown content={md} />+ ) : (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ No documentation available.+ </p>+ )}+ </div>+ );+ })}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Risk report+// ---------------------------------------------------------------------------++export function RiskReportRenderer({ data }: { data: RiskReportArtifactData }) {+ return (+ <div className="space-y-4">+ <div>+ <SectionTitle icon={ShieldAlert}>Targets</SectionTitle>+ <div className="space-y-1.5">+ {data.targets.map((t, i) => (+ <div+ key={`${t.file_path}:${i}`}+ className="rounded-lg border border-[var(--color-border-default)] p-2.5"+ >+ <div className="flex items-center justify-between gap-2">+ <span className="font-mono text-xs text-[var(--color-text-primary)] truncate">+ {t.file_path}+ </span>+ {t.is_hotspot && (+ <span className="inline-flex items-center gap-1 rounded bg-amber-500/10 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wider text-amber-400">+ <AlertTriangle className="h-2.5 w-2.5" /> hotspot+ </span>+ )}+ </div>+ {typeof t.churn_percentile === "number" && (+ <div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5 tabular-nums">+ Churn {Math.round(t.churn_percentile)}th pct+ </div>+ )}+ </div>+ ))}+ </div>+ </div>++ {data.global_hotspots.length > 0 && (+ <div>+ <SectionTitle icon={Activity}>Top global hotspots</SectionTitle>+ <div className="space-y-1">+ {data.global_hotspots.slice(0, 5).map((h, i) => (+ <div+ key={`${h.path}:${i}`}+ className="flex items-center justify-between gap-2 text-xs"+ >+ <span className="font-mono text-[var(--color-text-secondary)] truncate">+ {h.path}+ </span>+ <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)]">+ {Math.round(h.churn_percentile)}th+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Search results+// ---------------------------------------------------------------------------++export function SearchResultsRenderer({+ data,+}: {+ data: SearchResultsArtifactData;+}) {+ if (!data.results || data.results.length === 0) {+ return (+ <div className="space-y-2">+ <SectionTitle icon={Search}>Query</SectionTitle>+ <p className="text-xs text-[var(--color-text-secondary)] font-mono">+ {data.query}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ No results found.+ </p>+ </div>+ );+ }+ return (+ <div className="space-y-2">+ <SectionTitle icon={Search}>{data.query}</SectionTitle>+ {data.results.map((r, i) => (+ <div+ key={`${r.page_id ?? r.title}:${i}`}+ className="rounded-lg border border-[var(--color-border-default)] p-3"+ >+ <div className="text-xs font-medium text-[var(--color-text-primary)]">+ {r.title}+ </div>+ <div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5">+ {getPageTypeLabel(r.page_type)}+ {typeof r.relevance_score === "number" && (+ <> · score {(r.relevance_score as number).toFixed(2)}</>+ )}+ </div>+ {r.snippet && (+ <p className="text-xs text-[var(--color-text-secondary)] mt-1 line-clamp-3">+ {r.snippet}+ </p>+ )}+ </div>+ ))}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Graph (dependency path)+// ---------------------------------------------------------------------------++export function GraphPathRenderer({ data }: { data: GraphPathArtifactData }) {+ return (+ <div className="space-y-3">+ <p className="text-xs text-[var(--color-text-secondary)]">+ {data.explanation}+ </p>+ {data.path.length > 0 ? (+ <div>+ <SectionTitle icon={GitBranch}>Path</SectionTitle>+ <ol className="space-y-1">+ {data.path.map((node, i) => (+ <li+ key={`${node}:${i}`}+ className="flex items-center gap-2 text-xs"+ >+ <span className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-[var(--color-bg-elevated)] border border-[var(--color-border-default)] text-[9px] font-mono tabular-nums text-[var(--color-text-tertiary)]">+ {i + 1}+ </span>+ <span className="font-mono text-[var(--color-text-secondary)] truncate">+ {node}+ </span>+ {i < data.path.length - 1 && (+ <ArrowRight className="h-3 w-3 text-[var(--color-text-tertiary)] ml-auto shrink-0" />+ )}+ </li>+ ))}+ </ol>+ </div>+ ) : (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ No path found.+ </p>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Decisions+// ---------------------------------------------------------------------------++export function DecisionsRenderer({ data }: { data: DecisionsArtifactData }) {+ if (data.mode === "health") {+ return (+ <div className="space-y-4">+ <StatRow+ label="Decisions"+ value={(data.total_decisions ?? 0).toLocaleString()}+ />+ {data.by_source && Object.keys(data.by_source).length > 0 && (+ <div>+ <SectionTitle icon={Layers}>By source</SectionTitle>+ <div className="space-y-1">+ {Object.entries(data.by_source).map(([source, count]) => (+ <StatRow+ key={source}+ label={source}+ value={(count as number).toLocaleString()}+ />+ ))}+ </div>+ </div>+ )}+ {data.decisions && data.decisions.length > 0 && (+ <div>+ <SectionTitle icon={Sparkles}>Recent</SectionTitle>+ <ul className="space-y-1">+ {data.decisions.map((d, i) => (+ <li key={i} className="text-xs text-[var(--color-text-secondary)]">+ <span className="truncate">{d.title}</span>+ {d.status && (+ <span className="ml-1.5 text-[10px] text-[var(--color-text-tertiary)]">+ ({d.status})+ </span>+ )}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ );+ }++ // search mode+ if (!data.results || data.results.length === 0) {+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ No matching decisions for {data.query ? `"${data.query}"` : "this query"}.+ </p>+ );+ }+ return (+ <div className="space-y-3">+ {data.query && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Matches for{" "}+ <span className="font-mono text-[var(--color-text-secondary)]">+ "{data.query}"+ </span>+ </p>+ )}+ {data.results.map((r, i) => (+ <div+ key={`${r.title}:${i}`}+ className="rounded-lg border border-[var(--color-border-default)] p-3 space-y-1.5"+ >+ <h3 className="text-xs font-medium text-[var(--color-text-primary)]">+ {r.title}+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)] leading-relaxed">+ {r.decision}+ </p>+ {r.rationale && (+ <p className="text-[11px] text-[var(--color-text-tertiary)] leading-relaxed">+ {r.rationale}+ </p>+ )}+ {r.affected_files && r.affected_files.length > 0 && (+ <div className="flex flex-wrap gap-1 pt-1">+ {r.affected_files.slice(0, 6).map((f) => (+ <FilePathChip key={f} path={f} />+ ))}+ </div>+ )}+ </div>+ ))}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Dead code+// ---------------------------------------------------------------------------++export function DeadCodeRenderer({ data }: { data: DeadCodeArtifactData }) {+ return (+ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-2">+ <StatRow+ label="Findings"+ value={data.total_findings.toLocaleString()}+ />+ <StatRow+ label="Deletable lines"+ value={data.deletable_lines.toLocaleString()}+ />+ </div>++ {data.high_confidence.length > 0 && (+ <div>+ <SectionTitle icon={CheckCircle2}>High confidence</SectionTitle>+ <div className="space-y-1.5">+ {data.high_confidence.map((f, i) => (+ <DeadCodeRow key={`${f.file_path}:${i}`} finding={f} showLines />+ ))}+ </div>+ </div>+ )}++ {data.medium_confidence.length > 0 && (+ <div>+ <SectionTitle icon={AlertTriangle}>Medium confidence</SectionTitle>+ <div className="space-y-1.5">+ {data.medium_confidence.map((f, i) => (+ <DeadCodeRow key={`${f.file_path}:${i}`} finding={f} />+ ))}+ </div>+ </div>+ )}+ </div>+ );+}++function DeadCodeRow({+ finding,+ showLines = false,+}: {+ finding: {+ file_path: string;+ symbol_name?: string | null;+ kind: string;+ confidence: number;+ reason: string;+ lines?: number;+ safe_to_delete?: boolean;+ };+ showLines?: boolean;+}) {+ return (+ <div className="rounded-md border border-[var(--color-border-default)] p-2 text-xs">+ <div className="flex items-center justify-between gap-2">+ <span className="font-mono text-[var(--color-text-primary)] truncate">+ {finding.symbol_name ? `${finding.file_path}::${finding.symbol_name}` : finding.file_path}+ </span>+ <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">+ {(finding.confidence * 100).toFixed(0)}%+ </span>+ </div>+ <div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5">+ {finding.kind}+ {showLines && typeof finding.lines === "number" && (+ <> · {finding.lines} lines</>+ )}+ {finding.safe_to_delete && <> · safe to delete</>}+ </div>+ <p className="text-[11px] text-[var(--color-text-secondary)] mt-1 line-clamp-2">+ {finding.reason}+ </p>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Diagram (Mermaid)+// ---------------------------------------------------------------------------++export function DiagramRenderer({ data }: { data: DiagramArtifactData }) {+ if (!data.mermaid_syntax) {+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ No diagram available.+ </p>+ );+ }+ return (+ <div className="space-y-3">+ {data.description && (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {data.description}+ </p>+ )}+ <MermaidDiagram chart={data.mermaid_syntax} />+ </div>+ );+}++// ---------------------------------------------------------------------------+// Generic JSON fallback+// ---------------------------------------------------------------------------++export function GenericJsonRenderer({+ data,+}: {+ data: Record<string, unknown>;+}) {+ return (+ <pre className="text-[10px] font-mono text-[var(--color-text-secondary)] overflow-auto max-h-[70vh] whitespace-pre-wrap break-words">+ {JSON.stringify(data, null, 2)}+ </pre>+ );+}diff --git a/tests/fixtures/distill/skeleton_artifacts.symbols.json b/tests/fixtures/distill/skeleton_artifacts.symbols.jsonnew file mode 100644index 000000000..05090f3b7--- /dev/null+++ b/tests/fixtures/distill/skeleton_artifacts.symbols.json@@ -0,0 +1,110 @@+{+ "file_path": "packages/ui/src/chat/artifacts.tsx",+ "pinned_commit": "4dc36271d1a91125df977de200d4a5b5e1cf1b8a",+ "symbols": [+ {+ "name": "StatRow",+ "kind": "function",+ "signature": "function StatRow({ label, value }: { label: string; value: React.ReactNode })",+ "start_line": 42,+ "end_line": 51,+ "pagerank": 0.00010408759789114238+ },+ {+ "name": "SectionTitle",+ "kind": "function",+ "signature": "function SectionTitle({\r\n icon: Icon,\r\n children,\r\n}: {\r\n icon: React.ComponentType<{ className?: string }>;\r\n children: React.ReactNode;\r\n})",+ "start_line": 53,+ "end_line": 66,+ "pagerank": 0.0002378230601578749+ },+ {+ "name": "FilePathChip",+ "kind": "function",+ "signature": "function FilePathChip({ path }: { path: string })",+ "start_line": 68,+ "end_line": 77,+ "pagerank": 8.625620292224473e-05+ },+ {+ "name": "OverviewRenderer",+ "kind": "function",+ "signature": "function OverviewRenderer({ data }: { data: OverviewArtifactData })",+ "start_line": 83,+ "end_line": 139,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "ContextRenderer",+ "kind": "function",+ "signature": "function ContextRenderer({ data }: { data: ContextArtifactData })",+ "start_line": 145,+ "end_line": 173,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "RiskReportRenderer",+ "kind": "function",+ "signature": "function RiskReportRenderer({ data }: { data: RiskReportArtifactData })",+ "start_line": 179,+ "end_line": 232,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "SearchResultsRenderer",+ "kind": "function",+ "signature": "function SearchResultsRenderer({\r\n data,\r\n}: {\r\n data: SearchResultsArtifactData;\r\n})",+ "start_line": 238,+ "end_line": 282,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "GraphPathRenderer",+ "kind": "function",+ "signature": "function GraphPathRenderer({ data }: { data: GraphPathArtifactData })",+ "start_line": 288,+ "end_line": 323,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "DecisionsRenderer",+ "kind": "function",+ "signature": "function DecisionsRenderer({ data }: { data: DecisionsArtifactData })",+ "start_line": 329,+ "end_line": 417,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "DeadCodeRenderer",+ "kind": "function",+ "signature": "function DeadCodeRenderer({ data }: { data: DeadCodeArtifactData })",+ "start_line": 423,+ "end_line": 460,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "DeadCodeRow",+ "kind": "function",+ "signature": "function DeadCodeRow({\r\n finding,\r\n showLines = false,\r\n}: {\r\n finding: {\r\n file_path: string;\r\n symbol_name?: string | null;\r\n kind: string;\r\n confidence: number;\r\n reason: string;\r\n lines?: number;\r\n safe_to_delete?: boolean;\r\n };\r\n showLines?: boolean;\r\n})",+ "start_line": 462,+ "end_line": 499,+ "pagerank": 6.842480795334707e-05+ },+ {+ "name": "DiagramRenderer",+ "kind": "function",+ "signature": "function DiagramRenderer({ data }: { data: DiagramArtifactData })",+ "start_line": 505,+ "end_line": 523,+ "pagerank": 6.259485891679677e-05+ },+ {+ "name": "GenericJsonRenderer",+ "kind": "function",+ "signature": "function GenericJsonRenderer({\r\n data,\r\n}: {\r\n data: Record<string, unknown>;\r\n})",+ "start_line": 529,+ "end_line": 539,+ "pagerank": 6.259485891679677e-05+ }+ ]+}\ No newline at end of filediff --git a/tests/fixtures/distill/skeleton_traverser.src.txt b/tests/fixtures/distill/skeleton_traverser.src.txtnew file mode 100644index 000000000..05219a05f--- /dev/null+++ b/tests/fixtures/distill/skeleton_traverser.src.txt@@ -0,0 +1,666 @@+"""File traversal for the repowise ingestion pipeline.++FileTraverser walks a repository tree and yields FileInfo objects for each+source file that should be documented. It respects:+ 1. .gitignore (via pathspec) — the repo-root file plus any nested+ .gitignore in subdirectories (git reads one per directory, so does this)+ 2. .repowiseIgnore (same syntax, user overrides) — root and per-directory+ 3. A hardcoded blocklist of dirs / file patterns+ 4. Binary file detection+ 5. File-size limit+ 6. Generated-file detection (header markers + filename suffixes)++It also detects monorepo structure and returns a RepoStructure.+"""++from __future__ import annotations++import configparser+import os+import threading+from collections.abc import Iterator+from dataclasses import dataclass, field+from datetime import datetime+from pathlib import Path++import pathspec+import structlog++from .languages.registry import REGISTRY as _LANG_REGISTRY+from .models import (+ EXTENSION_TO_LANGUAGE,+ SPECIAL_FILENAMES,+ FileInfo,+ LanguageTag,+ PackageInfo,+ RepoStructure,+)++# ---------------------------------------------------------------------------+# Traversal statistics+# ---------------------------------------------------------------------------+++@dataclass+class TraversalStats:+ """Counts collected during file traversal, broken down by skip reason."""++ total_paths_walked: int = 0+ included: int = 0+ skipped_gitignore: int = 0+ skipped_blocked_extension: int = 0+ skipped_oversized: int = 0+ skipped_binary: int = 0+ skipped_generated: int = 0+ skipped_extra_ignore: int = 0+ skipped_extra_exclude: int = 0+ skipped_blocked_pattern: int = 0+ skipped_unknown_language: int = 0+ skipped_dir_ignore: int = 0+ skipped_submodule: int = 0+ skipped_nested_repo: int = 0+ lang_counts: dict[str, int] = field(default_factory=dict)+++log = structlog.get_logger(__name__)++# ---------------------------------------------------------------------------+# Blocklists+# ---------------------------------------------------------------------------++_BLOCKED_DIRS: frozenset[str] = frozenset(+ {+ ".git",+ ".hg",+ ".svn",+ "node_modules",+ ".venv",+ "venv",+ "__pycache__",+ ".pytest_cache",+ ".mypy_cache",+ ".ruff_cache",+ ".tox",+ "dist",+ "build",+ ".next",+ "target", # Rust / Maven+ ".gradle",+ "vendor", # Go / PHP+ "coverage",+ "htmlcov",+ ".eggs",+ "site-packages",+ ".cache",+ ".idea",+ ".vscode",+ # NOTE: test/tests/spec/specs/__tests__ are intentionally NOT+ # blocked here. They used to be excluded as a workaround for a+ # PageRank-inflation bug in graph.py, where a test fixture named+ # like the package (e.g. tests/.../<pkg>.py) would dominate the+ # import stem map and collect spurious in-edges from the entire+ # library. That bug is now fixed in graph.py via deterministic+ # stem disambiguation (see _build_stem_map / _stem_priority), so+ # test files can be indexed safely. Their content is needed to+ # answer questions about test helpers and fixtures. Files under+ # these directories are still tagged is_test=True via+ # _is_test_file() so downstream consumers can filter them when+ # appropriate.+ #+ # The following ARE still blocked because they typically hold+ # binary fixtures, generated artifacts, or browser-driven test+ # rigs whose content rarely answers code questions:+ "e2e",+ "fixtures",+ "conftest",+ }+)++_BLOCKED_EXTENSIONS: frozenset[str] = frozenset(+ {".pyc", ".pyo", ".pyd", ".so", ".dll", ".dylib", ".exe", ".o", ".a", ".wasm"}+)++_BLOCKED_FILENAME_PATTERNS: list[str] = [+ "*.min.js",+ "*.min.css",+ "package-lock.json",+ "yarn.lock",+ "pnpm-lock.yaml",+ "go.sum",+ "Cargo.lock",+ "poetry.lock",+ "uv.lock",+ "*.lock",+]++# Generated file markers (checked in first 512 bytes)+_GENERATED_MARKERS: tuple[str, ...] = (+ "Code generated",+ "DO NOT EDIT",+ "This file was automatically generated",+ "GENERATED CODE",+ "AUTO-GENERATED",+ "@generated",+)++_GENERATED_SUFFIXES: tuple[str, ...] = tuple(_LANG_REGISTRY.generated_suffixes())++# Manifest files that indicate a package root (for monorepo detection)+_MANIFEST_FILES: frozenset[str] = frozenset(+ {"pyproject.toml", "package.json", "Cargo.toml", "go.mod"}+)++# Entry-point filename stems+_ENTRY_POINT_STEMS: frozenset[str] = frozenset(+ {"main", "index", "app", "run", "server", "start", "wsgi", "asgi"}+)++_ENTRY_POINT_NAMES: frozenset[str] = _LANG_REGISTRY.entry_point_names() | frozenset(+ {"run.py", "server.py"} # extra traverser-specific patterns not in language specs+)++# Default file-size limit+_DEFAULT_MAX_FILE_SIZE_BYTES: int = 500 * 1024 # 500 KB++# Languages for which generated-file detection is skipped. These files have+# no AST parsing anyway, so reading 512 bytes to check for generated markers+# adds no value.+# Languages for which generated-file detection is skipped — same as parser's+# passthrough set (no AST parsing, so reading 512 bytes for markers is pointless).+_SKIP_GENERATED_CHECK: frozenset[str] = frozenset(+ spec.tag+ for spec in _LANG_REGISTRY.all_specs()+ if spec.is_passthrough+ and (not spec.is_code or spec.is_infra)+ and spec.tag not in ("openapi", "unknown")+)+++class FileTraverser:+ """Traverse a repository and yield FileInfo for each documentable file.++ Args:+ repo_root: Absolute path to the repository root.+ max_file_size_kb: Skip files larger than this. Default: 500 KB.+ extra_ignore_filename: Name of an additional gitignore-syntax file.+ Defaults to ``.repowiseIgnore``.+ extra_exclude_patterns: Additional gitignore-style patterns to exclude+ (from CLI ``--exclude`` flags or ``repo.settings["exclude_patterns"]``).+ include_submodules: When False (default), directories listed in+ ``.gitmodules`` are skipped during traversal.+ include_nested_repos: When False (default), any subdirectory that is+ itself a git repository (contains a ``.git`` directory or file)+ is treated as a hard traversal boundary and skipped. This+ matches the workspace scanner's behaviour: nested git repos are+ independent units, not part of the parent repo's working tree.+ Without this, a parent repo that physically contains sibling+ repos (common when a workspace root is itself versioned) would+ be walked end-to-end, pulling in hundreds of thousands of files+ that belong to the nested repos.+ """++ def __init__(+ self,+ repo_root: Path,+ *,+ max_file_size_kb: int = 500,+ extra_ignore_filename: str = ".repowiseIgnore",+ extra_exclude_patterns: list[str] | None = None,+ include_submodules: bool = False,+ include_nested_repos: bool = False,+ ) -> None:+ self.repo_root = repo_root.resolve()+ self.max_file_size_bytes = max_file_size_kb * 1024+ self._extra_ignore_filename = extra_ignore_filename+ self._gitignore = _load_gitignore_spec(self.repo_root)+ self._extra_ignore = _load_extra_ignore_spec(self.repo_root, extra_ignore_filename)+ self._blocked_patterns = pathspec.PathSpec.from_lines(+ "gitwildmatch", _BLOCKED_FILENAME_PATTERNS+ )+ patterns = extra_exclude_patterns or []+ self._extra_exclude = pathspec.PathSpec.from_lines("gitwildmatch", patterns)+ # Per-directory ignore cache: absolute dir path -> PathSpec built from+ # that directory's nested .gitignore + .repowiseIgnore.+ # Pre-seed root: its .gitignore is matched full-path via self._gitignore+ # and its .repowiseIgnore via self._extra_ignore, so the root entry only+ # needs the latter (avoids reading either file a second time).+ self._dir_ignore_cache: dict[str, pathspec.PathSpec] = {+ str(self.repo_root): self._extra_ignore,+ }+ self._submodule_paths: frozenset[str] = frozenset()+ if not include_submodules:+ self._submodule_paths = _parse_gitmodules(self.repo_root)+ self._include_nested_repos = include_nested_repos+ self.stats = TraversalStats()+ self._count_lock = threading.Lock()+ log.info(+ "FileTraverser initialised",+ repo_root=str(self.repo_root),+ max_file_size_kb=max_file_size_kb,+ extra_exclude_patterns=len(patterns),+ submodules_skipped=len(self._submodule_paths),+ include_nested_repos=include_nested_repos,+ )++ # ------------------------------------------------------------------+ # Public API+ # ------------------------------------------------------------------++ def traverse(self) -> Iterator[FileInfo]:+ """Yield FileInfo for every includable source file in the repo."""+ for abs_path in self._walk():+ info = self._build_file_info(abs_path)+ if info is not None:+ with self._count_lock:+ self.stats.included += 1+ self.stats.lang_counts[info.language] = (+ self.stats.lang_counts.get(info.language, 0) + 1+ )+ yield info++ def get_repo_structure(self, files: list[FileInfo] | None = None) -> RepoStructure:+ """Analyse high-level repo structure including monorepo detection.++ Pass an already-traversed *files* list to avoid a redundant full+ traversal. If omitted the repo is traversed from scratch.+ """+ if files is None:+ files = list(self.traverse())++ lang_counts: dict[str, int] = {}+ entry_points: list[str] = []++ for f in files:+ lang_counts[f.language] = lang_counts.get(f.language, 0) + 1+ if f.is_entry_point:+ entry_points.append(f.path)++ # Estimate LOC from file sizes (~40 bytes/line for mixed codebases).+ # This avoids opening every file just for line counting — total_loc is+ # a display metric so a fast estimate is acceptable.+ total_loc = sum(f.size_bytes // 40 for f in files)++ total = max(sum(lang_counts.values()), 1)+ lang_dist = {k: round(v / total, 3) for k, v in sorted(lang_counts.items())}++ packages, is_monorepo = self._detect_monorepo()++ return RepoStructure(+ is_monorepo=is_monorepo,+ packages=packages,+ root_language_distribution=lang_dist,+ total_files=len(files),+ total_loc=total_loc,+ entry_points=sorted(entry_points),+ )++ # ------------------------------------------------------------------+ # Internal: walking+ # ------------------------------------------------------------------++ def _walk(self) -> Iterator[Path]:+ """Yield all absolute file paths, skipping blocked directories."""+ for dirpath, dirnames, filenames in os.walk(self.repo_root):+ dirpath_obj = Path(dirpath)+ rel_dir = dirpath_obj.relative_to(self.repo_root)++ # Load per-directory .repowiseIgnore for subdirectory pruning.+ dir_ignore = self._get_dir_ignore(dirpath_obj)++ # Prune ignored directories in-place (affects os.walk recursion)+ dirnames[:] = sorted(+ d+ for d in dirnames+ if not self._should_skip_dir(d, rel_dir / d, dirpath_obj / d, dir_ignore)+ )++ for filename in sorted(filenames):+ self.stats.total_paths_walked += 1+ yield dirpath_obj / filename++ def _get_dir_ignore(self, dirpath: Path) -> pathspec.PathSpec:+ """Return the per-directory ignore spec, loading and caching on first access.++ Merges the directory's nested ``.gitignore`` and ``.repowiseIgnore``+ (in that order) into one spec. Git applies a ``.gitignore`` to its own+ directory's entries — not just the repo root — so a monorepo/workspace+ package with its own ``.gitignore`` (e.g. ``frontend/.gitignore``+ excluding ``storybook-static/``) is honoured. Patterns are matched+ against the immediate child name (see ``_should_skip_dir`` /+ ``_build_file_info``), consistent with the existing per-directory+ ``.repowiseIgnore`` handling.+ """+ key = str(dirpath)+ if key not in self._dir_ignore_cache:+ lines: list[str] = []+ for name in (".gitignore", self._extra_ignore_filename):+ ignore_file = dirpath / name+ if ignore_file.exists():+ lines.extend(+ ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines()+ )+ self._dir_ignore_cache[key] = pathspec.PathSpec.from_lines("gitwildmatch", lines)+ return self._dir_ignore_cache[key]++ def _should_skip_dir(+ self,+ dirname: str,+ rel_path: Path,+ abs_path: Path,+ dir_ignore: pathspec.PathSpec | None = None,+ ) -> bool:+ if dirname in _BLOCKED_DIRS:+ return True+ rel_str = rel_path.as_posix()+ if rel_str in self._submodule_paths:+ self.stats.skipped_submodule += 1+ return True+ # Nested git repos are independent units — stop at the boundary+ # unless the caller explicitly opted in. Mirrors the workspace+ # scanner, which already refuses to descend into nested `.git`+ # markers. Without this, a parent repo that physically contains+ # sibling repos gets walked end-to-end.+ if not self._include_nested_repos and _is_nested_git_repo(abs_path):+ self.stats.skipped_nested_repo += 1+ log.debug("Skipping nested git repo", path=rel_str)+ return True+ if self._gitignore.match_file(rel_str + "/"):+ return True+ if self._extra_ignore.match_file(rel_str + "/"):+ return True+ if self._extra_exclude.match_file(rel_str + "/"):+ return True+ # Per-directory ignore: pattern is relative to the parent directory.+ return dir_ignore is not None and dir_ignore.match_file(dirname + "/")++ # ------------------------------------------------------------------+ # Internal: FileInfo construction+ # ------------------------------------------------------------------++ def _build_file_info(self, abs_path: Path) -> FileInfo | None:+ try:+ stat = abs_path.stat()+ except OSError:+ return None++ size_bytes = stat.st_size+ rel_path = abs_path.relative_to(self.repo_root)+ rel_str = rel_path.as_posix()++ # Size limit+ if size_bytes > self.max_file_size_bytes:+ with self._count_lock:+ self.stats.skipped_oversized += 1+ log.debug("Skipping oversized file", path=rel_str, size_kb=size_bytes // 1024)+ return None++ # Blocked extension+ if abs_path.suffix.lower() in _BLOCKED_EXTENSIONS:+ with self._count_lock:+ self.stats.skipped_blocked_extension += 1+ return None++ # gitignore / extra ignore / extra exclude patterns+ if self._gitignore.match_file(rel_str):+ with self._count_lock:+ self.stats.skipped_gitignore += 1+ return None+ if self._extra_ignore.match_file(rel_str):+ with self._count_lock:+ self.stats.skipped_extra_ignore += 1+ return None+ if self._extra_exclude.match_file(rel_str):+ with self._count_lock:+ self.stats.skipped_extra_exclude += 1+ return None+ # Per-directory .repowiseIgnore: check filename against the parent dir's spec.+ dir_ignore = self._get_dir_ignore(abs_path.parent)+ if dir_ignore.match_file(abs_path.name):+ with self._count_lock:+ self.stats.skipped_dir_ignore += 1+ return None++ # Blocklist filename patterns+ if self._blocked_patterns.match_file(rel_str):+ with self._count_lock:+ self.stats.skipped_blocked_pattern += 1+ return None++ # Language detection — name/extension lookup is free (no I/O). Only+ # fall through to binary detection + shebang when the extension is+ # unrecognised, avoiding an 8 KB read for every .py/.ts/.go/… file.+ language = _language_from_name_or_ext(abs_path)+ if language is None:+ if _is_binary(abs_path):+ with self._count_lock:+ self.stats.skipped_binary += 1+ return None+ language = _detect_by_shebang(abs_path)+ if language == "unknown":+ with self._count_lock:+ self.stats.skipped_unknown_language += 1+ return None++ # Generated file detection: only meaningful for code files. Skipping+ # for data/markup files avoids a 512-byte read per file with no benefit.+ if language not in _SKIP_GENERATED_CHECK and _is_generated(abs_path):+ with self._count_lock:+ self.stats.skipped_generated += 1+ log.debug("Skipping generated file", path=rel_str)+ return None++ filename = abs_path.name+ return FileInfo(+ path=rel_str,+ abs_path=str(abs_path),+ language=language,+ size_bytes=size_bytes,+ git_hash="",+ last_modified=datetime.fromtimestamp(stat.st_mtime),+ is_test=_is_test_file(rel_str, filename),+ is_config=_is_config_file(language),+ is_api_contract=_is_api_contract(abs_path, language),+ is_entry_point=filename in _ENTRY_POINT_NAMES or _stem_is_entry_point(abs_path),+ )++ # ------------------------------------------------------------------+ # Internal: monorepo detection+ # ------------------------------------------------------------------++ def _detect_monorepo(self) -> tuple[list[PackageInfo], bool]:+ """Detect package sub-directories by looking for manifest files."""+ packages: list[PackageInfo] = []+ seen_paths: set[str] = set()++ for depth in (1, 2):+ pattern = "/".join(["*"] * depth) + "/*"+ for candidate in self.repo_root.glob(pattern):+ if candidate.name not in _MANIFEST_FILES:+ continue+ pkg_dir = candidate.parent+ rel_pkg = pkg_dir.relative_to(self.repo_root).as_posix()+ if rel_pkg in seen_paths:+ continue+ seen_paths.add(rel_pkg)+ lang = _primary_language_in(pkg_dir)+ entry_pts = _find_entry_points_in(pkg_dir, self.repo_root)+ packages.append(+ PackageInfo(+ name=pkg_dir.name,+ path=rel_pkg,+ language=lang,+ entry_points=entry_pts,+ manifest_file=candidate.name,+ )+ )++ packages.sort(key=lambda p: p.path)+ return packages, len(packages) > 1+++# ---------------------------------------------------------------------------+# Module-level helpers+# ---------------------------------------------------------------------------+++def _language_from_name_or_ext(abs_path: Path) -> LanguageTag | None:+ """Return language from filename or extension alone — zero file I/O.++ Returns None when the extension is not recognised, signalling that the+ caller should fall back to binary detection and shebang sniffing.+ """+ filename = abs_path.name+ if filename in SPECIAL_FILENAMES:+ return SPECIAL_FILENAMES[filename]+ return EXTENSION_TO_LANGUAGE.get(abs_path.suffix.lower())+++def _detect_language(abs_path: Path) -> LanguageTag:+ """Detect the language of a file from name, extension, or shebang."""+ lang = _language_from_name_or_ext(abs_path)+ if lang is not None:+ return lang+ return _detect_by_shebang(abs_path)+++def _detect_by_shebang(abs_path: Path) -> LanguageTag:+ try:+ with open(abs_path, encoding="utf-8", errors="ignore") as f:+ first_line = f.readline(200)+ if not first_line.startswith("#!"):+ return "unknown"+ for spec in _LANG_REGISTRY.all_specs():+ for token in spec.shebang_tokens:+ if token in first_line:+ return spec.tag # type: ignore[return-value]+ except OSError:+ pass+ return "unknown"+++def _is_binary(abs_path: Path) -> bool:+ """Return True if the file contains null bytes in the first 8 KB."""+ try:+ with open(abs_path, "rb") as f:+ return b"\x00" in f.read(8192)+ except OSError:+ return True+++def _is_generated(abs_path: Path) -> bool:+ """Return True if the file appears to be auto-generated."""+ name = abs_path.name+ if any(name.endswith(sfx) for sfx in _GENERATED_SUFFIXES):+ return True+ try:+ with open(abs_path, encoding="utf-8", errors="ignore") as f:+ header = f.read(512)+ header_upper = header.upper()+ return any(marker.upper() in header_upper for marker in _GENERATED_MARKERS)+ except OSError:+ return False+++def _is_test_file(rel_path: str, filename: str) -> bool:+ stem = Path(filename).stem.lower()+ if stem.startswith("test_") or stem.endswith("_test"):+ return True+ if stem.startswith("spec_") or stem.endswith("_spec"):+ return True+ path_lower = rel_path.lower()+ return "/test/" in path_lower or "/tests/" in path_lower or "/spec/" in path_lower+++def _is_config_file(language: LanguageTag) -> bool:+ return language in ("yaml", "toml", "json", "dockerfile", "makefile")+++def _is_api_contract(abs_path: Path, language: LanguageTag) -> bool:+ if language in ("proto", "graphql"):+ return True+ name_lower = abs_path.name.lower()+ return any(+ marker in name_lower+ for marker in ("openapi", "swagger", "schema.graphql", "api.yaml", "api.json")+ )+++def _stem_is_entry_point(abs_path: Path) -> bool:+ stem = abs_path.stem.lower()+ return stem in _ENTRY_POINT_STEMS+++def _primary_language_in(directory: Path) -> LanguageTag:+ counts: dict[str, int] = {}+ try:+ for item in directory.rglob("*"):+ if item.is_file():+ lang = _detect_language(item)+ if lang not in ("unknown", "yaml", "json", "markdown", "toml"):+ counts[lang] = counts.get(lang, 0) + 1+ except OSError:+ pass+ if not counts:+ return "unknown"+ return max(counts, key=lambda k: counts[k]) # type: ignore[return-value]+++def _find_entry_points_in(directory: Path, repo_root: Path) -> list[str]:+ result: list[str] = []+ try:+ for item in directory.rglob("*"):+ if item.is_file() and item.name in _ENTRY_POINT_NAMES:+ result.append(item.relative_to(repo_root).as_posix())+ except OSError:+ pass+ return sorted(result)+++def _is_nested_git_repo(path: Path) -> bool:+ """Return True if *path* is itself a git repository.++ A directory is a git repository when it contains a ``.git`` entry,+ which may be a directory (regular repo) or a file (git submodule,+ worktree, or repo with an externally located gitdir). We test for+ existence rather than `.is_dir()` to catch all three forms.+ """+ try:+ return (path / ".git").exists()+ except OSError:+ return False+++def _parse_gitmodules(repo_root: Path) -> frozenset[str]:+ """Parse ``.gitmodules`` and return the set of submodule paths (POSIX-style, relative)."""+ gitmodules = repo_root / ".gitmodules"+ if not gitmodules.exists():+ return frozenset()+ try:+ parser = configparser.ConfigParser()+ parser.read(str(gitmodules), encoding="utf-8")+ paths: set[str] = set()+ for section in parser.sections():+ path = parser.get(section, "path", fallback=None)+ if path:+ # Normalize to POSIX-style relative path+ paths.add(path.strip().replace("\\", "/"))+ return frozenset(paths)+ except Exception:+ log.warning("Failed to parse .gitmodules", path=str(gitmodules))+ return frozenset()+++def _load_gitignore_spec(repo_root: Path) -> pathspec.PathSpec:+ gitignore = repo_root / ".gitignore"+ lines: list[str] = []+ if gitignore.exists():+ lines = gitignore.read_text(encoding="utf-8", errors="ignore").splitlines()+ return pathspec.PathSpec.from_lines("gitwildmatch", lines)+++def _load_extra_ignore_spec(repo_root: Path, filename: str) -> pathspec.PathSpec:+ ignore_file = repo_root / filename+ lines: list[str] = []+ if ignore_file.exists():+ lines = ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines()+ return pathspec.PathSpec.from_lines("gitwildmatch", lines)diff --git a/tests/fixtures/distill/skeleton_traverser.symbols.json b/tests/fixtures/distill/skeleton_traverser.symbols.jsonnew file mode 100644index 000000000..945782345--- /dev/null+++ b/tests/fixtures/distill/skeleton_traverser.symbols.json@@ -0,0 +1,206 @@+{+ "file_path": "packages/core/src/repowise/core/ingestion/traverser.py",+ "pinned_commit": "4dc36271d1a91125df977de200d4a5b5e1cf1b8a",+ "symbols": [+ {+ "name": "TraversalStats",+ "kind": "class",+ "signature": "class TraversalStats",+ "start_line": 45,+ "end_line": 62,+ "pagerank": 6.135283854723637e-05+ },+ {+ "name": "FileTraverser",+ "kind": "class",+ "signature": "class FileTraverser",+ "start_line": 179,+ "end_line": 498,+ "pagerank": 0.002082437856532275+ },+ {+ "name": "__init__",+ "kind": "method",+ "signature": "def __init__(\r\n self,\r\n repo_root: Path,\r\n *,\r\n max_file_size_kb: int = 500,\r\n extra_ignore_filename: str = \".repowiseIgnore\",\r\n extra_exclude_patterns: list[str] | None = None,\r\n include_submodules: bool = False,\r\n include_nested_repos: bool = False,\r\n ) -> None",+ "start_line": 202,+ "end_line": 243,+ "pagerank": 5.0593412984449395e-05+ },+ {+ "name": "traverse",+ "kind": "method",+ "signature": "def traverse(self) -> Iterator[FileInfo]",+ "start_line": 249,+ "end_line": 259,+ "pagerank": 6.493931373483203e-05+ },+ {+ "name": "get_repo_structure",+ "kind": "method",+ "signature": "def get_repo_structure(self, files: list[FileInfo] | None = None) -> RepoStructure",+ "start_line": 261,+ "end_line": 295,+ "pagerank": 5.0593412984449395e-05+ },+ {+ "name": "_walk",+ "kind": "method",+ "signature": "def _walk(self) -> Iterator[Path]",+ "start_line": 301,+ "end_line": 319,+ "pagerank": 7.823752263705802e-05+ },+ {+ "name": "_get_dir_ignore",+ "kind": "method",+ "signature": "def _get_dir_ignore(self, dirpath: Path) -> pathspec.PathSpec",+ "start_line": 321,+ "end_line": 343,+ "pagerank": 9.04658378918325e-05+ },+ {+ "name": "_should_skip_dir",+ "kind": "method",+ "signature": "def _should_skip_dir(\r\n self,\r\n dirname: str,\r\n rel_path: Path,\r\n abs_path: Path,\r\n dir_ignore: pathspec.PathSpec | None = None,\r\n ) -> bool",+ "start_line": 345,+ "end_line": 374,+ "pagerank": 8.3820433740602e-05+ },+ {+ "name": "_build_file_info",+ "kind": "method",+ "signature": "def _build_file_info(self, abs_path: Path) -> FileInfo | None",+ "start_line": 380,+ "end_line": 464,+ "pagerank": 7.823752263705802e-05+ },+ {+ "name": "_detect_monorepo",+ "kind": "method",+ "signature": "def _detect_monorepo(self) -> tuple[list[PackageInfo], bool]",+ "start_line": 470,+ "end_line": 498,+ "pagerank": 6.493931373483203e-05+ },+ {+ "name": "_language_from_name_or_ext",+ "kind": "function",+ "signature": "def _language_from_name_or_ext(abs_path: Path) -> LanguageTag | None",+ "start_line": 506,+ "end_line": 515,+ "pagerank": 0.00036005438496455113+ },+ {+ "name": "_detect_language",+ "kind": "function",+ "signature": "def _detect_language(abs_path: Path) -> LanguageTag",+ "start_line": 518,+ "end_line": 523,+ "pagerank": 0.0007109394479865149+ },+ {+ "name": "_detect_by_shebang",+ "kind": "function",+ "signature": "def _detect_by_shebang(abs_path: Path) -> LanguageTag",+ "start_line": 526,+ "end_line": 538,+ "pagerank": 0.00036005438496455113+ },+ {+ "name": "_is_binary",+ "kind": "function",+ "signature": "def _is_binary(abs_path: Path) -> bool",+ "start_line": 541,+ "end_line": 547,+ "pagerank": 5.723881713567992e-05+ },+ {+ "name": "_is_generated",+ "kind": "function",+ "signature": "def _is_generated(abs_path: Path) -> bool",+ "start_line": 550,+ "end_line": 561,+ "pagerank": 5.723881713567992e-05+ },+ {+ "name": "_is_test_file",+ "kind": "function",+ "signature": "def _is_test_file(rel_path: str, filename: str) -> bool",+ "start_line": 564,+ "end_line": 571,+ "pagerank": 5.723881713567992e-05+ },+ {+ "name": "_is_config_file",+ "kind": "function",+ "signature": "def _is_config_file(language: LanguageTag) -> bool",+ "start_line": 574,+ "end_line": 575,+ "pagerank": 5.723881713567992e-05+ },+ {+ "name": "_is_api_contract",+ "kind": "function",+ "signature": "def _is_api_contract(abs_path: Path, language: LanguageTag) -> bool",+ "start_line": 578,+ "end_line": 585,+ "pagerank": 5.723881713567992e-05+ },+ {+ "name": "_stem_is_entry_point",+ "kind": "function",+ "signature": "def _stem_is_entry_point(abs_path: Path) -> bool",+ "start_line": 588,+ "end_line": 590,+ "pagerank": 5.723881713567992e-05+ },+ {+ "name": "_primary_language_in",+ "kind": "function",+ "signature": "def _primary_language_in(directory: Path) -> LanguageTag",+ "start_line": 593,+ "end_line": 605,+ "pagerank": 6.902281941952181e-05+ },+ {+ "name": "_find_entry_points_in",+ "kind": "function",+ "signature": "def _find_entry_points_in(directory: Path, repo_root: Path) -> list[str]",+ "start_line": 608,+ "end_line": 616,+ "pagerank": 6.902281941952181e-05+ },+ {+ "name": "_is_nested_git_repo",+ "kind": "function",+ "signature": "def _is_nested_git_repo(path: Path) -> bool",+ "start_line": 619,+ "end_line": 630,+ "pagerank": 0.00012165941808726602+ },+ {+ "name": "_parse_gitmodules",+ "kind": "function",+ "signature": "def _parse_gitmodules(repo_root: Path) -> frozenset[str]",+ "start_line": 633,+ "end_line": 650,+ "pagerank": 6.135283854723637e-05+ },+ {+ "name": "_load_gitignore_spec",+ "kind": "function",+ "signature": "def _load_gitignore_spec(repo_root: Path) -> pathspec.PathSpec",+ "start_line": 653,+ "end_line": 658,+ "pagerank": 6.135283854723637e-05+ },+ {+ "name": "_load_extra_ignore_spec",+ "kind": "function",+ "signature": "def _load_extra_ignore_spec(repo_root: Path, filename: str) -> pathspec.PathSpec",+ "start_line": 661,+ "end_line": 666,+ "pagerank": 6.135283854723637e-05+ }+ ]+}\ No newline at end of filediff --git a/tests/fixtures/distill/tsc_errors.txt b/tests/fixtures/distill/tsc_errors.txtnew file mode 100644index 000000000..e431f5197--- /dev/null+++ b/tests/fixtures/distill/tsc_errors.txt@@ -0,0 +1,18 @@+> [email protected] type-check+> tsc --noEmit++src/components/chat/chat-interface.tsx(112,18): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.+ Type 'undefined' is not assignable to type 'string'.+src/components/chat/chat-interface.tsx(204,7): error TS2739: Type '{ role: string; }' is missing the following properties from type 'ChatMessage': id, content, createdAt+src/components/docs/docs-viewer.tsx(88,31): error TS2554: Expected 2 arguments, but got 1.+src/lib/api/client.ts(41,12): error TS18048: 'response.body' is possibly 'undefined'.+src/lib/api/client.ts(67,5): error TS2322: Type 'Promise<unknown>' is not assignable to type 'Promise<RepoSummary[]>'.+src/app/repos/[id]/c4/page.tsx(23,9): error TS2741: Property 'container' is missing in type '{ level: string; }' but required in type 'C4ViewState'.++Found 6 errors in 4 files.++Errors Files+ 2 src/components/chat/chat-interface.tsx:112+ 1 src/components/docs/docs-viewer.tsx:88+ 2 src/lib/api/client.ts:41+ 1 src/app/repos/[id]/c4/page.tsx:23diff --git a/tests/unit/cli/test_augment_search.py b/tests/unit/cli/test_augment_search.pyindex 8130879e2..ffc2fe536 100644--- a/tests/unit/cli/test_augment_search.py+++ b/tests/unit/cli/test_augment_search.py@@ -23,7 +23,6 @@ from repowise.cli.commands.augment_cmd import (_name_variants,)-# ---------------------------------------------------------------------------# Pure helpers# ---------------------------------------------------------------------------@@ -213,3 +212,60 @@ class TestDecisionTree:kwargs = call_args.kwargs or {}mode = kwargs.get("mode") if "mode" in kwargs else args[2]assert mode == "triage"+++# ---------------------------------------------------------------------------+# Grep-flood compact digest (>= _DIGEST_THRESHOLD lines)+# ---------------------------------------------------------------------------+++def _flood(files: int, per_file: int) -> str:+ return "\n".join(+ f"src/file{i}.py:{j}:hit number {j}" for i in range(files) for j in range(1, per_file + 1)+ )+++class TestFloodDigest:+ def test_digest_on_big_flood(self, repowise_cwd) -> None:+ """>= _DIGEST_THRESHOLD parseable lines across >= 3 files → digest."""+ out = _call("Grep", "auth", _flood(files=8, per_file=10), repowise_cwd)+ assert out is not None+ assert "compact digest" in out+ # No wiki.db in the fixture repo → ordering falls back to match count.+ assert "match count" in out+ assert "80 matches in 8 files" in out++ def test_digest_fires_even_for_path_patterns(self, repowise_cwd) -> None:+ """The digest summarizes results, so the concept-vs-path gate is moot."""+ out = _call("Grep", "src/file0.py", _flood(files=8, per_file=10), repowise_cwd)+ assert out is not None and "compact digest" in out++ def test_few_files_fall_through_to_triage(self, repowise_cwd) -> None:+ """A flood concentrated in 1-2 files is already navigable — no digest."""+ sentinel = "triaged"+ with patch.object(augment_cmd, "_search_enrich", return_value=sentinel) as enrich:+ with patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]):+ out = _call("Grep", "auth", _flood(files=2, per_file=40), repowise_cwd)+ assert out == sentinel+ assert enrich.called++ def test_unparseable_flood_falls_through(self, repowise_cwd) -> None:+ """Glob-style bare path lists can't be grouped — triage handles them."""+ big = "\n".join(f"line {i} of something unstructured" for i in range(60))+ sentinel = "triaged"+ with patch.object(augment_cmd, "_search_enrich", return_value=sentinel) as enrich:+ with patch("asyncio.run", side_effect=lambda coro: (coro.close(), sentinel)[1]):+ out = _call("Grep", "auth", big, repowise_cwd)+ assert out == sentinel+ assert enrich.called++ def test_top_files_listed_first(self, repowise_cwd) -> None:+ flood = "\n".join(+ [f"src/hot.py:{j}:hit" for j in range(1, 41)]+ + [f"src/warm.py:{j}:hit" for j in range(1, 11)]+ + [f"src/cold{i}.py:1:hit" for i in range(5)]+ )+ out = _call("Grep", "auth", flood, repowise_cwd)+ assert out is not None+ file_lines = [ln for ln in out.splitlines() if "matches)" in ln]+ assert file_lines[0].strip().startswith("src/hot.py")diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.pyindex c12d58d29..9bc2ac81e 100644--- a/tests/unit/cli/test_mcp_config.py+++ b/tests/unit/cli/test_mcp_config.py@@ -404,7 +404,7 @@ def test_install_claude_code_hooks_creates_missing_file(assert settings_path == tmp_path / ".claude" / "settings.json"saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]def test_install_claude_code_hooks_preserves_user_pretool_hooks(@@ -439,7 +439,7 @@ def test_install_claude_code_hooks_preserves_user_pretool_hooks(assert saved["hooks"]["PreToolUse"][0]["matcher"] == "Read"assert saved["hooks"]["PreToolUse"][0]["hooks"][0]["command"] == "echo read"# PostToolUse now has the repowise hook.- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]# ---------------------------------------------------------------------------@@ -453,7 +453,7 @@ def test_install_claude_code_hooks_migrates_pre_0_6_1_command("""Pre-0.6.1 entries used the legacy ``repowise augment`` Click command.Installer should drop the PreToolUse repowise entry entirely (the newdesign moves enrichment to PostToolUse) and rewrite + widen the- PostToolUse entry to ``Bash|Grep|Glob`` with ``repowise-augment``."""+ PostToolUse entry to ``Bash|Grep|Glob|Read|Edit|Write`` with ``repowise-augment``."""monkeypatch.setattr(Path, "home", lambda: tmp_path)settings_path = tmp_path / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True)@@ -483,14 +483,14 @@ def test_install_claude_code_hooks_migrates_pre_0_6_1_command(saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]def test_install_claude_code_hooks_migrates_pre_0_6_2_matcher(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""0.6.1 entries had ``repowise-augment`` already but kept matcher=Bash.- The matcher should widen to ``Bash|Grep|Glob`` so the same hook covers+ The matcher should widen to ``Bash|Grep|Glob|Read|Edit|Write`` so the same hook coversGrep/Glob enrichment too."""monkeypatch.setattr(Path, "home", lambda: tmp_path)settings_path = tmp_path / ".claude" / "settings.json"@@ -521,7 +521,7 @@ def test_install_claude_code_hooks_migrates_pre_0_6_2_matcher(saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]def test_install_claude_code_hooks_idempotent_on_current_shape(@@ -575,12 +575,72 @@ def test_migrate_claude_code_hooks_handles_full_legacy_payload(saved = json.loads(settings_path.read_text(encoding="utf-8"))assert "PreToolUse" not in saved["hooks"]- assert _post_repowise_entries(saved) == [("Bash|Grep|Glob", "repowise-augment")]+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]# Idempotent: a second run finds nothing to do.assert claude_config.migrate_claude_code_hooks() is False+def test_migrate_claude_code_hooks_widens_grep_glob_matcher(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Pre-read-intelligence installs used matcher ``Bash|Grep|Glob``;+ migration widens it to include Read/Edit/Write."""+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ settings_path = tmp_path / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True)+ settings_path.write_text(+ json.dumps(+ {+ "hooks": {+ "PostToolUse": [+ {+ "matcher": "Bash|Grep|Glob",+ "hooks": [{"type": "command", "command": "repowise-augment"}],+ }+ ]+ }+ }+ ),+ encoding="utf-8",+ )++ assert claude_config.migrate_claude_code_hooks() is True+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ assert _post_repowise_entries(saved) == [("Bash|Grep|Glob|Read|Edit|Write", "repowise-augment")]+++def test_migrate_claude_code_hooks_never_widens_user_matcher(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A legacy matcher whose hook list contains a user hook is left alone."""+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ settings_path = tmp_path / ".claude" / "settings.json"+ settings_path.parent.mkdir(parents=True)+ settings_path.write_text(+ json.dumps(+ {+ "hooks": {+ "PostToolUse": [+ {+ "matcher": "Bash|Grep|Glob",+ "hooks": [+ {"type": "command", "command": "repowise-augment"},+ {"type": "command", "command": "my-linter"},+ ],+ }+ ]+ }+ }+ ),+ encoding="utf-8",+ )++ assert claude_config.migrate_claude_code_hooks() is False+ saved = json.loads(settings_path.read_text(encoding="utf-8"))+ assert saved["hooks"]["PostToolUse"][0]["matcher"] == "Bash|Grep|Glob"++def test_migrate_claude_code_hooks_preserves_user_sibling_hook(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -626,7 +686,7 @@ def test_migrate_claude_code_hooks_noop_when_already_current("hooks": {"PostToolUse": [{- "matcher": "Bash|Grep|Glob",+ "matcher": "Bash|Grep|Glob|Read|Edit|Write","hooks": [{"type": "command", "command": "repowise-augment"}],}]diff --git a/tests/unit/distill/conftest.py b/tests/unit/distill/conftest.pynew file mode 100644index 000000000..6b468de37--- /dev/null+++ b/tests/unit/distill/conftest.py@@ -0,0 +1,34 @@+"""Shared fixtures for distill unit tests."""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.distill.store import OmissionStore++[email protected](scope="session")+def distill_fixtures_dir(fixtures_dir: Path) -> Path:+ """Path to tests/fixtures/distill/ (captured real command outputs)."""+ path = fixtures_dir / "distill"+ assert path.exists(), f"distill fixtures not found at {path}"+ return path++[email protected](scope="session")+def load_fixture(distill_fixtures_dir: Path):+ """Loader that tolerates the UTF-8 BOM PowerShell capture leaves behind."""++ def _load(name: str) -> str:+ return (distill_fixtures_dir / name).read_text(encoding="utf-8-sig")++ return _load+++def store(tmp_path: Path) -> OmissionStore:+ s = OmissionStore(tmp_path / "omissions" / "omissions.db")+ yield s+ s.close()diff --git a/tests/unit/distill/test_agent_adapters.py b/tests/unit/distill/test_agent_adapters.pynew file mode 100644index 000000000..6bb1d763c--- /dev/null+++ b/tests/unit/distill/test_agent_adapters.py@@ -0,0 +1,205 @@+"""Agent-adapter seam — Claude Code payload parsing, rendering, hook install.++The adapter owns everything Claude-Code-specific; these tests pin the+protocol shapes and prove the settings.json install/uninstall is idempotent,+migration-safe, and preserves user hooks and the augment PostToolUse entry.+"""++from __future__ import annotations++import json++import pytest++from repowise.cli.agent_adapters.base import RewriteResult+from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter+from repowise.cli.editor_integrations import claude_config+from repowise.cli.editor_integrations.claude_config import (+ claude_code_rewrite_hook_installed,+ install_claude_code_hooks,+ install_claude_code_rewrite_hook,+ migrate_claude_code_hooks,+ uninstall_claude_code_rewrite_hook,+)+++def adapter() -> ClaudeCodeAdapter:+ return ClaudeCodeAdapter()+++class TestParsePayload:+ def test_valid_bash_payload(self, adapter) -> None:+ raw = json.dumps(+ {+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": "pytest -x"},+ "cwd": "/repo",+ }+ )+ req = adapter.parse_hook_payload(raw)+ assert req is not None+ assert req.command == "pytest -x"+ assert req.cwd == "/repo"++ @pytest.mark.parametrize(+ "mutation",+ [+ {"hook_event_name": "PostToolUse"},+ {"tool_name": "Grep"},+ {"tool_input": {}},+ {"tool_input": {"command": " "}},+ {"tool_input": "pytest"},+ ],+ )+ def test_rejects_wrong_shapes(self, adapter, mutation) -> None:+ payload = {+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": "pytest"},+ "cwd": "/repo",+ }+ payload.update(mutation)+ assert adapter.parse_hook_payload(json.dumps(payload)) is None++ @pytest.mark.parametrize("raw", ["", "not json", "[1, 2]", "null"])+ def test_malformed_input_never_raises(self, adapter, raw) -> None:+ assert adapter.parse_hook_payload(raw) is None++ def test_missing_cwd_defaults_empty(self, adapter) -> None:+ raw = json.dumps(+ {"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": "ls"}}+ )+ req = adapter.parse_hook_payload(raw)+ assert req is not None and req.cwd == ""+++class TestRenderResponse:+ def test_shape(self, adapter) -> None:+ result = RewriteResult(command="repowise distill pytest -x", permission="ask", reason="why")+ rendered = json.loads(adapter.render_response(result))+ hso = rendered["hookSpecificOutput"]+ assert hso == {+ "hookEventName": "PreToolUse",+ "permissionDecision": "ask",+ "permissionDecisionReason": "why",+ "updatedInput": {"command": "repowise distill pytest -x"},+ }+++# ---------------------------------------------------------------------------+# settings.json install / uninstall+# ---------------------------------------------------------------------------+++def settings_path(tmp_path, monkeypatch):+ path = tmp_path / ".claude" / "settings.json"+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: path)+ return path+++def _read(settings_path) -> dict:+ return json.loads(settings_path.read_text(encoding="utf-8"))+++def _pre_hooks(settings_path) -> list:+ return _read(settings_path).get("hooks", {}).get("PreToolUse", [])+++class TestRewriteHookInstall:+ def test_fresh_install(self, settings_path) -> None:+ assert install_claude_code_rewrite_hook() == settings_path+ entries = _pre_hooks(settings_path)+ assert len(entries) == 1+ assert entries[0]["matcher"] == "Bash"+ hook = entries[0]["hooks"][0]+ assert hook["command"] == "repowise-rewrite"+ assert hook["type"] == "command"+ assert claude_code_rewrite_hook_installed() is True++ def test_idempotent(self, settings_path) -> None:+ install_claude_code_rewrite_hook()+ install_claude_code_rewrite_hook()+ assert len(_pre_hooks(settings_path)) == 1++ def test_preserves_user_pretool_hooks(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ user_entry = {+ "matcher": "Bash",+ "hooks": [{"type": "command", "command": "my-validator"}],+ }+ settings_path.write_text(+ json.dumps({"hooks": {"PreToolUse": [user_entry]}}), encoding="utf-8"+ )+ install_claude_code_rewrite_hook()+ entries = _pre_hooks(settings_path)+ assert len(entries) == 2+ assert entries[0]["hooks"][0]["command"] == "my-validator"++ def test_uninstall_removes_and_drops_empty_bucket(self, settings_path) -> None:+ install_claude_code_rewrite_hook()+ assert uninstall_claude_code_rewrite_hook() is True+ assert "PreToolUse" not in _read(settings_path).get("hooks", {})+ assert claude_code_rewrite_hook_installed() is False++ def test_uninstall_keeps_user_hooks(self, settings_path) -> None:+ settings_path.parent.mkdir(parents=True, exist_ok=True)+ user_entry = {+ "matcher": "Bash",+ "hooks": [{"type": "command", "command": "my-validator"}],+ }+ settings_path.write_text(+ json.dumps({"hooks": {"PreToolUse": [user_entry]}}), encoding="utf-8"+ )+ install_claude_code_rewrite_hook()+ assert uninstall_claude_code_rewrite_hook() is True+ entries = _pre_hooks(settings_path)+ assert len(entries) == 1+ assert entries[0]["hooks"][0]["command"] == "my-validator"++ def test_uninstall_when_absent(self, settings_path) -> None:+ assert uninstall_claude_code_rewrite_hook() is False+++class TestCoexistenceWithAugmentHooks:+ """The PostToolUse installer and the legacy migration historically strip+ repowise PreToolUse entries — the rewrite hook must survive both."""++ def test_post_install_preserves_rewrite_hook(self, settings_path) -> None:+ install_claude_code_rewrite_hook()+ install_claude_code_hooks()+ assert claude_code_rewrite_hook_installed() is True+ post = _read(settings_path)["hooks"]["PostToolUse"]+ assert any("repowise-augment" in h["command"] for e in post for h in e["hooks"])++ def test_migration_preserves_rewrite_hook(self, settings_path) -> None:+ install_claude_code_rewrite_hook()+ # Seed a legacy augment PreToolUse entry that migration must strip.+ existing = _read(settings_path)+ existing["hooks"]["PreToolUse"].append(+ {"matcher": "Bash", "hooks": [{"type": "command", "command": "repowise augment"}]}+ )+ settings_path.write_text(json.dumps(existing), encoding="utf-8")++ assert migrate_claude_code_hooks() is True+ entries = _pre_hooks(settings_path)+ commands = [h["command"] for e in entries for h in e["hooks"]]+ assert commands == ["repowise-rewrite"]++ def test_rewrite_install_preserves_augment_post_hook(self, settings_path) -> None:+ install_claude_code_hooks()+ install_claude_code_rewrite_hook()+ data = _read(settings_path)+ post = data["hooks"]["PostToolUse"]+ assert any("repowise-augment" in h["command"] for e in post for h in e["hooks"])+ assert claude_code_rewrite_hook_installed() is True+++class TestAdapterDelegation:+ def test_install_uninstall_via_adapter(self, settings_path, adapter) -> None:+ assert adapter.install_rewrite_hook() == settings_path+ assert adapter.rewrite_hook_installed() is True+ assert adapter.uninstall_rewrite_hook() is True+ assert adapter.rewrite_hook_installed() is Falsediff --git a/tests/unit/distill/test_claude_md_section.py b/tests/unit/distill/test_claude_md_section.pynew file mode 100644index 000000000..765409794--- /dev/null+++ b/tests/unit/distill/test_claude_md_section.py@@ -0,0 +1,49 @@+"""The generated CLAUDE.md must teach agents the distill marker semantics."""++from __future__ import annotations++from pathlib import Path++import pytest+from jinja2 import Environment, FileSystemLoader++from repowise.core.generation.editor_files.data import EditorFileData++_TEMPLATE_DIR = (+ Path(__file__).resolve().parents[3]+ / "packages"+ / "core"+ / "src"+ / "repowise"+ / "core"+ / "generation"+ / "templates"+)+++def rendered() -> str:+ env = Environment(loader=FileSystemLoader(str(_TEMPLATE_DIR)))+ data = EditorFileData(+ repo_name="test",+ indexed_at="2026-06-05",+ indexed_commit="abc123",+ architecture_summary="",+ )+ return env.get_template("claude_md.j2").render(data=data)+++class TestDistillSection:+ def test_section_present(self, rendered: str) -> None:+ assert "### Output Distillation" in rendered++ def test_teaches_distill_command(self, rendered: str) -> None:+ assert "repowise distill <cmd>" in rendered++ def test_teaches_marker_expansion(self, rendered: str) -> None:+ # Marker semantics: see a [repowise#<ref>: ...] marker → expand it.+ assert "[repowise#" in rendered+ assert "repowise expand <ref>" in rendered++ def test_discourages_rerunning(self, rendered: str) -> None:+ assert "Never re-run" in rendereddiff --git a/tests/unit/distill/test_cli.py b/tests/unit/distill/test_cli.pynew file mode 100644index 000000000..9e413e9ac--- /dev/null+++ b/tests/unit/distill/test_cli.py@@ -0,0 +1,117 @@+"""Unit tests for the ``repowise distill`` / ``repowise expand`` commands."""++from __future__ import annotations++import sys+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.cli.commands.distill_cmd import distill_command+from repowise.cli.commands.expand_cmd import expand_command+from repowise.core.distill.markers import parse_marker_refs+from repowise.core.distill.store import OmissionStore+++def repo_cwd(tmp_path: Path, monkeypatch) -> Path:+ """A scratch repo with .repowise/ so the store lands locally."""+ (tmp_path / ".repowise").mkdir()+ monkeypatch.chdir(tmp_path)+ return tmp_path+++def _py(code: str) -> list[str]:+ return [sys.executable, "-c", code]+++def test_distill_preserves_exit_code(repo_cwd: Path) -> None:+ runner = CliRunner()+ result = runner.invoke(distill_command, _py("import sys; sys.exit(7)"))+ assert result.exit_code == 7+++def test_distill_unmatched_command_passes_output_through(repo_cwd: Path) -> None:+ runner = CliRunner()+ result = runner.invoke(distill_command, _py("print('plain output')"))+ assert result.exit_code == 0+ assert "plain output" in result.output+ assert "[repowise#" not in result.output+++def test_distill_captures_stderr_too(repo_cwd: Path) -> None:+ runner = CliRunner()+ result = runner.invoke(+ distill_command,+ _py("import sys; print('out'); print('err line', file=sys.stderr)"),+ )+ assert "out" in result.output+ assert "err line" in result.output+++def test_distill_failing_git_command_keeps_exit_code(repo_cwd: Path) -> None:+ # tmp dir is not a git repository: git fails, the engine passes the raw+ # error output through, and the nonzero exit code survives.+ result = CliRunner().invoke(distill_command, ["git", "log", "-40"])+ assert result.exit_code != 0+++def test_distill_and_expand_roundtrip(repo_cwd: Path, fixtures_dir: Path) -> None:+ raw = (fixtures_dir / "distill" / "git_log_full.txt").read_text(encoding="utf-8-sig")+ from repowise.core.distill import distill_output++ store = OmissionStore(repo_cwd / ".repowise" / "omissions" / "omissions.db")+ distilled = distill_output(raw, command="git log -40", store=store)+ store.close()+ assert distilled.distilled+ (ref,) = parse_marker_refs(distilled.text)++ result = CliRunner().invoke(expand_command, [ref])+ assert result.exit_code == 0+ assert result.output.rstrip("\n") == raw.rstrip("\n")+++def test_expand_accepts_pasted_marker(repo_cwd: Path) -> None:+ store = OmissionStore(repo_cwd / ".repowise" / "omissions" / "omissions.db")+ ref = store.put("stashed content", source="cli:logs", original_tokens=10, kept_tokens=2)+ store.close()+ marker = f"[repowise#{ref}: 3 lines omitted (~30 tokens); restore: repowise expand {ref}]"+ result = CliRunner().invoke(expand_command, [marker])+ assert result.exit_code == 0+ assert "stashed content" in result.output+++def test_expand_with_query_filters_lines(repo_cwd: Path) -> None:+ store = OmissionStore(repo_cwd / ".repowise" / "omissions" / "omissions.db")+ ref = store.put(+ "keep FAILED a\ndrop ok b\nkeep FAILED c", source="cli:t", original_tokens=9, kept_tokens=1+ )+ store.close()+ result = CliRunner().invoke(expand_command, [ref, "--query", "FAILED"])+ assert result.exit_code == 0+ assert "drop ok b" not in result.output+ assert "keep FAILED a" in result.output+++def test_expand_unknown_ref_fails_cleanly(repo_cwd: Path) -> None:+ result = CliRunner().invoke(expand_command, ["0" * 12])+ assert result.exit_code == 1+++def test_expand_invalid_ref_fails_cleanly(repo_cwd: Path) -> None:+ result = CliRunner().invoke(expand_command, ["zzz"])+ assert result.exit_code == 2+++def test_distill_records_savings_ledger(repo_cwd: Path, fixtures_dir: Path) -> None:+ fixture = fixtures_dir / "distill" / "find_paths.txt"+ raw = fixture.read_text(encoding="utf-8-sig")+ from repowise.core.distill import distill_output++ store = OmissionStore(repo_cwd / ".repowise" / "omissions" / "omissions.db")+ result = distill_output(raw, command="find packages -name *.py", source="cli", store=store)+ assert result.distilled+ summary = store.savings_summary()+ store.close()+ assert summary["per_filter"]["file_listing"]["events"] == 1diff --git a/tests/unit/distill/test_config_and_doctor.py b/tests/unit/distill/test_config_and_doctor.pynew file mode 100644index 000000000..639ca729d--- /dev/null+++ b/tests/unit/distill/test_config_and_doctor.py@@ -0,0 +1,251 @@+"""Unit tests for distill config validation, doctor checks, and the+install/uninstall <-> init opt-out interplay."""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.cli.commands.doctor_cmd import _distill_checks+from repowise.cli.commands.hook_cmd import rewrite_install, rewrite_uninstall+from repowise.cli.editor_integrations import claude_config+from repowise.core.distill.config import (+ omission_store_settings,+ validate_distill_config,+)+from repowise.core.distill.store import DEFAULT_MAX_MB, DEFAULT_TTL_DAYS, OmissionStore++# ---------------------------------------------------------------------------+# validate_distill_config+# ---------------------------------------------------------------------------+++def test_validate_absent_block_is_ok() -> None:+ assert validate_distill_config(None) == []+++def test_validate_full_valid_block() -> None:+ cfg = {+ "enabled": True,+ "commands": {+ "enabled": True,+ "permission": "ask",+ "families": {"test_output": "allow", "git_diff": "deny"},+ "disabled_filters": ["logs"],+ },+ "omission_store": {"ttl_days": 14, "max_mb": 100},+ }+ assert validate_distill_config(cfg) == []+++def test_validate_non_mapping_block() -> None:+ assert validate_distill_config("yes") == ["distill: must be a mapping"]+++def test_validate_bad_permission() -> None:+ problems = validate_distill_config({"commands": {"permission": "always"}})+ assert any("permission" in p and "'always'" in p for p in problems)+++def test_validate_unknown_family_and_bad_value() -> None:+ problems = validate_distill_config(+ {"commands": {"families": {"nope": "ask", "git_status": "maybe"}}}+ )+ assert any("families.nope: unknown filter" in p for p in problems)+ assert any("families.git_status" in p and "'maybe'" in p for p in problems)+++def test_validate_unknown_disabled_filter() -> None:+ problems = validate_distill_config({"commands": {"disabled_filters": ["bogus"]}})+ assert any("disabled_filters: unknown filter 'bogus'" in p for p in problems)+++def test_validate_unknown_keys_flagged() -> None:+ problems = validate_distill_config({"read_nudges": True, "commands": {"permision": "ask"}})+ assert any("distill.read_nudges: unknown key" in p for p in problems)+ assert any("commands.permision: unknown key" in p for p in problems)+++def test_validate_store_values() -> None:+ problems = validate_distill_config(+ {"omission_store": {"ttl_days": -1, "max_mb": "big", "size": 1}}+ )+ assert any("ttl_days: must be a positive number" in p for p in problems)+ assert any("max_mb: must be a positive number" in p for p in problems)+ assert any("omission_store.size: unknown key" in p for p in problems)+++def test_validate_enabled_must_be_bool() -> None:+ problems = validate_distill_config({"enabled": "yes"})+ assert problems == ["distill.enabled: must be true or false"]+++# ---------------------------------------------------------------------------+# omission_store_settings+# ---------------------------------------------------------------------------+++def test_store_settings_defaults() -> None:+ assert omission_store_settings(None) == (DEFAULT_TTL_DAYS, DEFAULT_MAX_MB)+ assert omission_store_settings({}) == (DEFAULT_TTL_DAYS, DEFAULT_MAX_MB)+++def test_store_settings_reads_values() -> None:+ cfg = {"omission_store": {"ttl_days": 3, "max_mb": 10.5}}+ assert omission_store_settings(cfg) == (3.0, 10.5)+++def test_store_settings_invalid_values_fall_back() -> None:+ cfg = {"omission_store": {"ttl_days": True, "max_mb": -5}}+ assert omission_store_settings(cfg) == (DEFAULT_TTL_DAYS, DEFAULT_MAX_MB)+++def test_distill_cmd_loads_store_settings(tmp_path: Path) -> None:+ from repowise.cli.commands.distill_cmd import _load_distill_config++ repowise_dir = tmp_path / ".repowise"+ repowise_dir.mkdir()+ (repowise_dir / "config.yaml").write_text(+ "distill:\n omission_store:\n ttl_days: 2\n max_mb: 5\n",+ encoding="utf-8",+ )+ enabled, disabled, (ttl, cap) = _load_distill_config(tmp_path)+ assert enabled is True+ assert disabled == ()+ assert (ttl, cap) == (2.0, 5.0)+++# ---------------------------------------------------------------------------+# doctor distill checks+# ---------------------------------------------------------------------------+++def repo(tmp_path: Path) -> Path:+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++def no_real_hook(monkeypatch):+ """Keep doctor away from the developer's real ~/.claude/settings.json."""+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ monkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_installed", lambda self: False)+++def _rows(repo: Path) -> dict[str, tuple[str, str]]:+ return {name: (status, detail) for name, status, detail in _distill_checks(repo)}+++def test_doctor_defaults_all_ok(repo: Path, no_real_hook) -> None:+ rows = _rows(repo)+ assert "OK" in rows["Distill config"][0]+ assert rows["Distill config"][1] == "defaults (no block)"+ assert "OK" in rows["Omission store"][0]+ assert rows["Omission store"][1] == "not created yet"+ assert "OK" in rows["Distill rewrite hook"][0]+ assert "not installed" in rows["Distill rewrite hook"][1]+++def test_doctor_flags_invalid_config(repo: Path, no_real_hook) -> None:+ (repo / ".repowise" / "config.yaml").write_text(+ "distill:\n commands:\n permission: always\n", encoding="utf-8"+ )+ rows = _rows(repo)+ assert "FAIL" in rows["Distill config"][0]+ assert "permission" in rows["Distill config"][1]+++def test_doctor_store_within_cap(repo: Path, no_real_hook) -> None:+ store = OmissionStore(repo / ".repowise" / "omissions" / "omissions.db")+ store.put("some content", source="cli:logs", original_tokens=10, kept_tokens=2)+ store.close()+ rows = _rows(repo)+ assert "OK" in rows["Omission store"][0]+ assert "cap" in rows["Omission store"][1]+++def test_doctor_store_over_cap_fails(repo: Path, no_real_hook) -> None:+ (repo / ".repowise" / "config.yaml").write_text(+ "distill:\n omission_store:\n max_mb: 0.0001\n", encoding="utf-8"+ )+ store = OmissionStore(repo / ".repowise" / "omissions" / "omissions.db")+ # One row is never evicted by design, so a single oversized row can pin+ # the store over a tiny cap — exactly what the doctor check reports.+ store.put("x" * 200_000, source="cli:logs", original_tokens=10, kept_tokens=2)+ store.close()+ rows = _rows(repo)+ assert "FAIL" in rows["Omission store"][0]+ assert "over cap" in rows["Omission store"][1]+++def test_doctor_hook_installed_with_repo_opt_out(repo: Path, monkeypatch) -> None:+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter++ monkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_installed", lambda self: True)+ (repo / ".repowise" / "config.yaml").write_text(+ "distill:\n commands:\n enabled: false\n", encoding="utf-8"+ )+ rows = _rows(repo)+ assert rows["Distill rewrite hook"][1] == "installed (this repo opted out)"+++# ---------------------------------------------------------------------------+# hook rewrite install/uninstall <-> init opt-out interplay+# ---------------------------------------------------------------------------+++def settings_path(tmp_path, monkeypatch):+ path = tmp_path / ".claude" / "settings.json"+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: path)+ return path+++def test_install_after_init_opt_out_re_enables_repo(+ tmp_path: Path, settings_path: Path, monkeypatch+) -> None:+ from repowise.core.repo_config import load_repo_config++ repo = tmp_path / "repo"+ (repo / ".repowise").mkdir(parents=True)+ # Simulate a prior `repowise init --no-distill-hook` opt-out.+ (repo / ".repowise" / "config.yaml").write_text(+ "distill:\n commands:\n enabled: false\n", encoding="utf-8"+ )+ monkeypatch.chdir(repo)++ result = CliRunner().invoke(rewrite_install, [])+ assert result.exit_code == 0+ assert "installed" in result.output+ # Hook entry written...+ data = json.loads(settings_path.read_text(encoding="utf-8"))+ assert data["hooks"]["PreToolUse"]+ # ...and the repo's opt-out lifted (a manual install must not be inert).+ cfg = load_repo_config(repo)+ assert cfg["distill"]["commands"]["enabled"] is True+++def test_uninstall_removes_hook_but_leaves_repo_config(+ tmp_path: Path, settings_path: Path, monkeypatch+) -> None:+ from repowise.core.repo_config import load_repo_config++ repo = tmp_path / "repo"+ (repo / ".repowise").mkdir(parents=True)+ monkeypatch.chdir(repo)++ CliRunner().invoke(rewrite_install, [])+ result = CliRunner().invoke(rewrite_uninstall, [])+ assert result.exit_code == 0+ assert "removed" in result.output+ data = json.loads(settings_path.read_text(encoding="utf-8"))+ assert not data.get("hooks", {}).get("PreToolUse")+ # Uninstall is global (settings.json); per-repo config stays as-is so a+ # later reinstall does not need to re-discover repo preferences.+ cfg = load_repo_config(repo)+ assert cfg["distill"]["commands"]["enabled"] is Truediff --git a/tests/unit/distill/test_engine.py b/tests/unit/distill/test_engine.pynew file mode 100644index 000000000..22fa4bf91--- /dev/null+++ b/tests/unit/distill/test_engine.py@@ -0,0 +1,115 @@+"""Unit tests for the distill engine: safety guarantees around the filters."""++from __future__ import annotations++from typing import ClassVar++import pytest++from repowise.core.distill import distill_output+from repowise.core.distill.filters.base import OutputFilter+from repowise.core.distill.markers import parse_marker_refs+from repowise.core.distill.registry import filter_registry+from repowise.core.distill.store import OmissionStore+++def crashing_filter():+ """Temporarily register a filter that always raises."""++ class CrashingFilter(OutputFilter):+ name: ClassVar[str] = "crashing"+ priority: ClassVar[int] = 1+ min_lines: ClassVar[int] = 1++ def matches_command(self, command: str) -> bool:+ return command.startswith("crashme")++ def distill(self, output: str, *, command: str = "", exit_code: int = 0) -> str:+ raise RuntimeError("boom")++ instance = CrashingFilter()+ filter_registry._filters.append(instance)+ yield instance+ filter_registry._filters.remove(instance)+++def test_distills_and_emits_marker(load_fixture, store: OmissionStore) -> None:+ raw = load_fixture("git_log_full.txt")+ result = distill_output(raw, command="git log -40", store=store)+ assert result.distilled+ assert result.filter_name == "git_log"+ assert result.ref is not None+ assert parse_marker_refs(result.text) == [result.ref]+ assert result.distilled_tokens < result.raw_tokens+++def test_marker_ref_round_trips_through_store(load_fixture, store: OmissionStore) -> None:+ raw = load_fixture("git_log_full.txt")+ result = distill_output(raw, command="git log -40", store=store)+ assert store.get(result.ref) == raw+++def test_no_matching_filter_returns_raw(store: OmissionStore) -> None:+ raw = "hello\n" * 50+ result = distill_output(raw, command="echo hello", store=store)+ assert not result.distilled+ assert result.text == raw+ assert result.ref is None+++def test_filter_exception_falls_back_to_raw(crashing_filter, store: OmissionStore) -> None:+ raw = "some output\n" * 20+ result = distill_output(raw, command="crashme now", store=store)+ assert not result.distilled+ assert result.text == raw+++def test_short_output_passes_through(store: OmissionStore) -> None:+ raw = "On branch main\nnothing to commit, working tree clean"+ result = distill_output(raw, command="git status", store=store)+ assert not result.distilled+ assert result.text == raw+++def test_no_savings_passes_through(store: OmissionStore) -> None:+ # All-error tsc output: the filter keeps everything, so distillation+ # cannot win and the engine must return raw with no marker.+ raw = "\n".join(+ f"src/file{i}.ts({i},1): error TS2345: Argument of type 'A' is not assignable."+ for i in range(20)+ )+ result = distill_output(raw, command="tsc --noEmit", store=store)+ assert not result.distilled+ assert result.text == raw+++def test_store_failure_falls_back_to_raw(load_fixture, store: OmissionStore) -> None:+ # A closed store cannot persist the raw output; without reversibility+ # the engine must not drop a single byte.+ store.close()+ raw = load_fixture("git_log_full.txt")+ result = distill_output(raw, command="git log -40", store=store)+ assert not result.distilled+ assert result.text == raw+++def test_savings_recorded_in_ledger(load_fixture, store: OmissionStore) -> None:+ raw = load_fixture("git_log_full.txt")+ distill_output(raw, command="git log -40", source="cli", store=store)+ summary = store.savings_summary()+ assert summary["events"] == 1+ assert summary["per_filter"]["git_log"]["saved_tokens"] > 0+++def test_disabled_filters_respected(load_fixture, store: OmissionStore) -> None:+ raw = load_fixture("git_log_full.txt")+ result = distill_output(raw, command="git log -40", store=store, disabled_filters=("git_log",))+ assert not result.distilled+++def test_exit_code_does_not_block_distillation(load_fixture, store: OmissionStore) -> None:+ raw = load_fixture("pytest_fail.txt")+ result = distill_output(raw, command="pytest", exit_code=1, store=store)+ assert result.distilled+ assert result.filter_name == "test_output"diff --git a/tests/unit/distill/test_filters.py b/tests/unit/distill/test_filters.pynew file mode 100644index 000000000..8e9f95d23--- /dev/null+++ b/tests/unit/distill/test_filters.py@@ -0,0 +1,246 @@+"""Fixture-driven tests for the seven output filters.++Every fixture under tests/fixtures/distill/ is real output captured from this+repository (git/pytest/npm/find/ls) or a hand-written but format-faithful+sample for toolchains not present here (go, cargo, jest, tsc).++Two invariants run across the board:+- **zero error-line loss** on test/build output: every raw line classified by+ ``is_error_line`` appears verbatim in the distilled rendering;+- **savings assertions** per fixture, plus a >=60% median over the+ test/build bench set.+"""++from __future__ import annotations++import statistics++import pytest++from repowise.core.distill.budget import estimate_tokens, savings_pct+from repowise.core.distill.filters.base import is_error_line+from repowise.core.distill.registry import filter_registry+++def _distill(load_fixture, fixture: str, filter_name: str, command: str) -> tuple[str, str]:+ raw = load_fixture(fixture)+ f = filter_registry.get(filter_name)+ assert f is not None+ return raw, f.distill(raw, command=command)+++def _pct(raw: str, distilled: str) -> float:+ return savings_pct(estimate_tokens(raw), estimate_tokens(distilled))+++def _assert_no_error_line_lost(raw: str, distilled: str) -> None:+ for line in raw.splitlines():+ if is_error_line(line):+ assert line in distilled, f"error line dropped: {line!r}"+++# -- test_output ---------------------------------------------------------------++#: (fixture, command) pairs for the test/build savings bench.+BENCH_CASES = [+ ("pytest_fail.txt", "test_output", "pytest"),+ ("pytest_pass_verbose.txt", "test_output", "pytest tests/unit"),+ ("go_test_fail.txt", "test_output", "go test ./..."),+ ("cargo_test_fail.txt", "test_output", "cargo test"),+ ("jest_fail.txt", "test_output", "npm test"),+ ("npm_build.txt", "build_output", "npm run build"),+]++[email protected](("fixture", "filter_name", "command"), BENCH_CASES)+def test_no_error_line_lost(load_fixture, fixture, filter_name, command) -> None:+ raw, distilled = _distill(load_fixture, fixture, filter_name, command)+ _assert_no_error_line_lost(raw, distilled)++[email protected](("fixture", "filter_name", "command"), BENCH_CASES)+def test_individual_savings_floor(load_fixture, fixture, filter_name, command) -> None:+ raw, distilled = _distill(load_fixture, fixture, filter_name, command)+ assert _pct(raw, distilled) >= 40.0, f"{fixture} saved less than 40%"+++def test_bench_median_savings_at_least_60pct(load_fixture) -> None:+ """Plan exit criterion: >=60% median token reduction on test/build fixtures.++ tsc_errors.txt participates as 0%: it is all signal, the filter keeps+ everything, and the engine correctly passes it through — that behavior is+ asserted separately below.+ """+ pcts = []+ for fixture, filter_name, command in BENCH_CASES:+ raw, distilled = _distill(load_fixture, fixture, filter_name, command)+ pcts.append(_pct(raw, distilled))+ pcts.append(0.0) # tsc_errors.txt: all-error output, no savings possible+ assert statistics.median(pcts) >= 60.0, f"median savings {pcts}"+++def test_pytest_failures_and_summary_survive(load_fixture) -> None:+ raw, distilled = _distill(load_fixture, "pytest_fail.txt", "test_output", "pytest")+ assert "FAILURES" in distilled+ assert "short test summary info" in distilled+ assert "test_assertion_failure" in distilled+ # The final counts line is the single most useful line of a test run.+ assert "4 failed" in distilled+ # The pass parade is gone.+ assert "[ 55%]" not in distilled or distilled.count("%]") < raw.count("%]")+++def test_pytest_pass_run_collapses_to_header_and_summary(load_fixture) -> None:+ _raw, distilled = _distill(+ load_fixture, "pytest_pass_verbose.txt", "test_output", "pytest tests/unit"+ )+ assert "test session starts" in distilled+ assert "passed" in distilled+ assert len(distilled.splitlines()) < 20+++def test_go_panic_traceback_survives(load_fixture) -> None:+ _raw, distilled = _distill(load_fixture, "go_test_fail.txt", "test_output", "go test ./...")+ assert "--- FAIL: TestResolveImports" in distilled+ assert "panic: runtime error: index out of range" in distilled+ assert "blame_test.go:57" in distilled+ assert "exit status 2" in distilled+ # Passing subtests are summarized away.+ assert "TestParserPython3/basic" not in distilled+++def test_cargo_failures_section_survives(load_fixture) -> None:+ _raw, distilled = _distill(load_fixture, "cargo_test_fail.txt", "test_output", "cargo test")+ assert "store::tests::test_ttl_prune" in distilled+ assert "test result: FAILED. 22 passed; 2 failed" in distilled+ assert "test graph::tests::test_pagerank_sums_to_one ... ok" not in distilled+++def test_jest_failure_blocks_survive(load_fixture) -> None:+ _raw, distilled = _distill(load_fixture, "jest_fail.txt", "test_output", "npm test")+ assert "● ChatInterface › renders streaming tokens incrementally" in distilled # noqa: RUF001+ assert "chat-interface.test.tsx:47:20" in distilled+ assert "Tests: 2 failed, 117 passed, 119 total" in distilled+ assert "✓ renders without crashing" not in distilled+++# -- build_output ----------------------------------------------------------------+++def test_build_errors_survive_and_spam_collapses(load_fixture) -> None:+ raw, distilled = _distill(load_fixture, "npm_build.txt", "build_output", "npm run build")+ _assert_no_error_line_lost(raw, distilled)+ assert len(distilled.splitlines()) < len(raw.splitlines())+++def test_tsc_all_error_output_is_kept_whole(load_fixture) -> None:+ """All-signal build output: the filter must not beat the raw by dropping errors."""+ raw = load_fixture("tsc_errors.txt")+ f = filter_registry.get("build_output")+ distilled = f.distill(raw, command="npm run type-check")+ _assert_no_error_line_lost(raw, distilled)+ assert "Found 6 errors in 4 files." in distilled+++# -- git family -------------------------------------------------------------------+++def test_git_status_compact(load_fixture) -> None:+ raw, distilled = _distill(load_fixture, "git_status_dirty.txt", "git_status", "git status")+ assert distilled.splitlines()[0].startswith("## feat/distill")+ # Every path in the raw status survives, with porcelain-style codes.+ assert "A packages/core/src/repowise/core/distill/store.py" in distilled+ assert " M README.md" in distilled+ assert "?? tests/fixtures/distill/" in distilled+ # The hint boilerplate is gone.+ assert "git restore" not in distilled+ assert _pct(raw, distilled) >= 15.0+++def test_git_status_clean_tree() -> None:+ raw = (+ "On branch main\n"+ "Your branch is up to date with 'origin/main'.\n\n"+ "nothing to commit, working tree clean\n"+ "and some\nmore lines\nto pass min_lines\n"+ )+ f = filter_registry.get("git_status")+ distilled = f.distill(raw, command="git status")+ assert "## main...origin/main" in distilled+ assert "clean" in distilled+++def test_git_log_subjects_only(load_fixture) -> None:+ raw, distilled = _distill(load_fixture, "git_log_full.txt", "git_log", "git log -40")+ lines = distilled.splitlines()+ assert "40 commits" in lines[0]+ # Most recent commit subject is present with its short sha.+ assert any("2ef3f76c" in ln for ln in lines)+ assert _pct(raw, distilled) >= 80.0+++def test_git_diff_keeps_structure(load_fixture) -> None:+ raw, distilled = _distill(+ load_fixture, "git_diff_large.txt", "git_diff", "git diff HEAD~6..HEAD"+ )+ assert distilled.splitlines()[0].startswith("diff:")+ # Every changed file is accounted for: full hunks or a +/- summary line.+ import re++ for m in re.finditer(r"^diff --git a/(?P<a>.+?) b/(?P<b>.+)$", raw, re.MULTILINE):+ assert m.group("b") in distilled, f"file {m.group('b')} unaccounted for"+ assert _pct(raw, distilled) >= 50.0+++def test_git_diff_unrecognized_raises() -> None:+ f = filter_registry.get("git_diff")+ with pytest.raises(ValueError):+ f.distill("random text\n" * 50, command="git diff")+++# -- file_listing -------------------------------------------------------------------+++def test_find_paths_grouped_by_directory(load_fixture) -> None:+ raw, distilled = _distill(+ load_fixture, "find_paths.txt", "file_listing", "find packages/core/src -name *.py"+ )+ assert "directories:" in distilled.splitlines()[0]+ assert "packages/core/src/repowise/core/distill/" in distilled+ assert _pct(raw, distilled) >= 60.0+++def test_ls_long_compacts_columns(load_fixture) -> None:+ raw, distilled = _distill(load_fixture, "ls_la.txt", "file_listing", "ls -la")+ assert "entries:" in distilled.splitlines()[0]+ assert _pct(raw, distilled) >= 60.0+++# -- logs ------------------------------------------------------------------------+++def test_logs_collapse_templates_keep_errors(load_fixture) -> None:+ raw, distilled = _distill(load_fixture, "generic_logs.txt", "logs", "tail -200 server.log")+ # Every severe line survives verbatim.+ for line in raw.splitlines():+ if "ERROR" in line:+ assert line in distilled+ # Repeated event templates collapse with a count annotation.+ assert "similar)" in distilled+ assert _pct(raw, distilled) >= 50.0+++# -- registry/meta -----------------------------------------------------------------+++def test_all_seven_filters_registered() -> None:+ names = {f.name for f in filter_registry.filters()}+ assert names >= {+ "test_output",+ "build_output",+ "git_status",+ "git_log",+ "git_diff",+ "file_listing",+ "logs",+ }diff --git a/tests/unit/distill/test_init_optin.py b/tests/unit/distill/test_init_optin.pynew file mode 100644index 000000000..17a8e61e2--- /dev/null+++ b/tests/unit/distill/test_init_optin.py@@ -0,0 +1,69 @@+"""``repowise init`` opt-in flow for the distill command-rewrite hook."""++from __future__ import annotations++import json+from unittest.mock import MagicMock++import pytest+import yaml++from repowise.cli.commands.init_cmd._interactive import offer_distill_rewrite_hook+from repowise.cli.editor_integrations import claude_config+++def settings_path(tmp_path, monkeypatch):+ path = tmp_path / "home" / ".claude" / "settings.json"+ monkeypatch.setattr(claude_config, "_claude_code_settings_path", lambda: path)+ monkeypatch.delenv("REPOWISE_SKIP_EDITOR_SETUP", raising=False)+ return path+++def repo(tmp_path):+ (tmp_path / "repo" / ".repowise").mkdir(parents=True)+ return tmp_path / "repo"+++def _distill_config(repo) -> dict:+ cfg = yaml.safe_load((repo / ".repowise" / "config.yaml").read_text(encoding="utf-8"))+ return cfg.get("distill", {})+++class TestOfferDistillRewriteHook:+ def test_explicit_optin_installs_and_enables(self, settings_path, repo) -> None:+ offer_distill_rewrite_hook(MagicMock(), repo, flag=True)+ assert settings_path.exists()+ data = json.loads(settings_path.read_text(encoding="utf-8"))+ commands = [h["command"] for e in data["hooks"]["PreToolUse"] for h in e["hooks"]]+ assert commands == ["repowise-rewrite"]+ assert _distill_config(repo)["commands"]["enabled"] is True++ def test_explicit_optout_gates_repo_off(self, settings_path, repo) -> None:+ offer_distill_rewrite_hook(MagicMock(), repo, flag=False)+ assert not settings_path.exists()+ assert _distill_config(repo)["commands"]["enabled"] is False++ def test_no_flag_noninteractive_does_nothing(self, settings_path, repo, monkeypatch) -> None:+ import sys++ monkeypatch.setattr(sys.stdin, "isatty", lambda: False)+ offer_distill_rewrite_hook(MagicMock(), repo, flag=None)+ assert not settings_path.exists()+ assert not (repo / ".repowise" / "config.yaml").exists()++ def test_skip_editor_setup_env_blocks_install(self, settings_path, repo, monkeypatch) -> None:+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")+ offer_distill_rewrite_hook(MagicMock(), repo, flag=True)+ assert not settings_path.exists()++ def test_optout_preserves_existing_distill_config(self, settings_path, repo) -> None:+ (repo / ".repowise" / "config.yaml").write_text(+ yaml.dump({"distill": {"commands": {"disabled_filters": ["git_diff"]}}}),+ encoding="utf-8",+ )+ offer_distill_rewrite_hook(MagicMock(), repo, flag=False)+ distill = _distill_config(repo)+ assert distill["commands"]["enabled"] is False+ assert distill["commands"]["disabled_filters"] == ["git_diff"]diff --git a/tests/unit/distill/test_markers.py b/tests/unit/distill/test_markers.pynew file mode 100644index 000000000..205dff6f3--- /dev/null+++ b/tests/unit/distill/test_markers.py@@ -0,0 +1,67 @@+"""Unit tests for omission-marker rendering and parsing."""++from __future__ import annotations++import pytest++from repowise.core.distill.markers import (+ MARKER_RE,+ is_valid_ref,+ parse_marker_refs,+ render_marker,+)++REF = "3f9c2ab8d1e0"+++def test_render_parse_roundtrip() -> None:+ marker = render_marker(REF, 412, 3120)+ assert parse_marker_refs(f"some output\n\n{marker}\n") == [REF]+++def test_marker_is_ascii_only() -> None:+ """Distilled output is echoed to cp1252 consoles; the marker must survive."""+ marker = render_marker(REF, 10, 100)+ marker.encode("ascii") # raises if not+++def test_marker_mentions_expand_command() -> None:+ marker = render_marker(REF, 10, 100)+ assert f"repowise expand {REF}" in marker+ assert "10 lines omitted" in marker+ assert "~100 tokens" in marker+++def test_parse_multiple_refs_in_order_deduped() -> None:+ a = render_marker("a" * 12, 1, 1)+ b = render_marker("b" * 12, 2, 2)+ text = f"{a}\nmiddle\n{b}\nagain {a}"+ assert parse_marker_refs(text) == ["a" * 12, "b" * 12]+++def test_parse_ignores_non_marker_brackets() -> None:+ assert parse_marker_refs("[not a marker] [repowise#xyz: nope]") == []+++def test_render_rejects_invalid_ref() -> None:+ with pytest.raises(ValueError):+ render_marker("XYZ", 1, 1)+ with pytest.raises(ValueError):+ render_marker("abc", 1, 1) # too short+++def test_negative_counts_clamped() -> None:+ marker = render_marker(REF, -5, -10)+ assert "0 lines omitted" in marker+ assert "~0 tokens" in marker+++def test_is_valid_ref() -> None:+ assert is_valid_ref(REF)+ assert not is_valid_ref(REF.upper())+ assert not is_valid_ref(REF + "0")+ assert not is_valid_ref("")+++def test_marker_regex_matches_rendered_form() -> None:+ assert MARKER_RE.search(render_marker(REF, 3, 30))diff --git a/tests/unit/distill/test_read_intelligence.py b/tests/unit/distill/test_read_intelligence.pynew file mode 100644index 000000000..b05ddd120--- /dev/null+++ b/tests/unit/distill/test_read_intelligence.py@@ -0,0 +1,237 @@+"""Read-intelligence PostToolUse behaviors: skeleton nudges + stale reads.++Exercises the augment handlers directly (the `_handle_post_tool_use`+dispatch layer), below `_emit_response`'s cross-process dedup, so the+per-session state file is the only rate limiter under test.+"""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path++import pytest++from repowise.cli.commands.augment_cmd import (+ _handle_post_tool_use,+ _load_session_state,+ _session_state_path,+)++SESSION = "session-abc"+++def repo(tmp_path: Path) -> Path:+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++def _index_file(repo: Path, rel: str, bounds: list[tuple[int, int]]) -> None:+ """Minimal wiki.db carrying just the columns the hook path queries."""+ db = repo / ".repowise" / "wiki.db"+ con = sqlite3.connect(db)+ con.execute(+ "CREATE TABLE IF NOT EXISTS wiki_symbols "+ "(file_path TEXT, start_line INTEGER, end_line INTEGER)"+ )+ con.executemany(+ "INSERT INTO wiki_symbols VALUES (?, ?, ?)",+ [(rel, s, e) for s, e in bounds],+ )+ con.commit()+ con.close()+++def _write_big_file(repo: Path, rel: str, lines: int = 200) -> Path:+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("\n".join(f"x{n} = {n} # padding padding" for n in range(lines)) + "\n")+ return path+++def _read_event(repo: Path, rel: str, num_lines: int = 150, session: str = SESSION):+ return _handle_post_tool_use(+ "Read",+ {"file_path": str(repo / rel)},+ {"file": {"numLines": num_lines}},+ str(repo),+ session_id=session,+ )+++def _edit_event(repo: Path, rel: str, tool: str = "Edit", session: str = SESSION):+ return _handle_post_tool_use(+ tool,+ {"file_path": str(repo / rel)},+ {"success": True},+ str(repo),+ session_id=session,+ )+++class TestSkeletonNudge:+ def test_fires_for_big_read_of_indexed_file(self, repo: Path) -> None:+ _write_big_file(repo, "src/big.py")+ _index_file(repo, "src/big.py", [(10, 60), (70, 150), (160, 195)])++ result = _read_event(repo, "src/big.py")+ assert result is not None+ assert 'include=["skeleton"]' in result+ assert "src/big.py" in result+ assert "tokens" in result++ def test_fires_exactly_once_per_file_per_session(self, repo: Path) -> None:+ _write_big_file(repo, "src/big.py")+ _index_file(repo, "src/big.py", [(10, 60), (70, 150), (160, 195)])++ assert _read_event(repo, "src/big.py") is not None+ # Identical payload, same session: silent.+ assert _read_event(repo, "src/big.py") is None+ assert _read_event(repo, "src/big.py") is None+ # A new session resets the claim.+ assert _read_event(repo, "src/big.py", session="session-2") is not None++ def test_silent_below_line_threshold(self, repo: Path) -> None:+ _write_big_file(repo, "src/big.py")+ _index_file(repo, "src/big.py", [(10, 60), (70, 150)])+ assert _read_event(repo, "src/big.py", num_lines=40) is None++ def test_silent_without_wiki_db(self, repo: Path) -> None:+ _write_big_file(repo, "src/big.py")+ assert _read_event(repo, "src/big.py") is None++ def test_silent_when_file_not_indexed(self, repo: Path) -> None:+ _write_big_file(repo, "src/big.py")+ _index_file(repo, "src/other.py", [(1, 50)])+ assert _read_event(repo, "src/big.py") is None++ def test_silent_outside_any_repowise_repo(self, tmp_path: Path) -> None:+ plain = tmp_path / "plain"+ _write_big_file(plain, "src/big.py")+ result = _handle_post_tool_use(+ "Read",+ {"file_path": str(plain / "src/big.py")},+ {"file": {"numLines": 150}},+ str(plain),+ session_id=SESSION,+ )+ assert result is None++ def test_silent_for_tiny_file(self, repo: Path) -> None:+ # 150 reported lines but the on-disk file is too small to matter.+ path = repo / "src" / "small.py"+ path.parent.mkdir(parents=True)+ path.write_text("x = 1\n" * 30)+ _index_file(repo, "src/small.py", [(1, 30)])+ assert _read_event(repo, "src/small.py") is None+++class TestStaleReadNotice:+ def test_edit_then_reread_flags_staleness(self, repo: Path) -> None:+ _write_big_file(repo, "a.py", lines=10)+ assert _read_event(repo, "a.py", num_lines=10) is None # first read+ assert _edit_event(repo, "a.py") is None # records, says nothing+ notice = _read_event(repo, "a.py", num_lines=10)+ assert notice is not None+ assert "a.py" in notice and "stale" in notice++ def test_write_tool_also_counts_as_edit(self, repo: Path) -> None:+ _write_big_file(repo, "a.py", lines=10)+ _read_event(repo, "a.py", num_lines=10)+ _edit_event(repo, "a.py", tool="Write")+ assert "stale" in (_read_event(repo, "a.py", num_lines=10) or "")++ def test_notice_is_once_per_file_per_session(self, repo: Path) -> None:+ _write_big_file(repo, "a.py", lines=10)+ _read_event(repo, "a.py", num_lines=10)+ _edit_event(repo, "a.py")+ assert _read_event(repo, "a.py", num_lines=10) is not None+ _edit_event(repo, "a.py")+ assert _read_event(repo, "a.py", num_lines=10) is None++ def test_no_notice_without_intervening_edit(self, repo: Path) -> None:+ _write_big_file(repo, "a.py", lines=10)+ assert _read_event(repo, "a.py", num_lines=10) is None+ assert _read_event(repo, "a.py", num_lines=10) is None++ def test_no_notice_when_first_read_follows_edit(self, repo: Path) -> None:+ # The agent never saw pre-edit content — nothing is stale for it.+ _write_big_file(repo, "a.py", lines=10)+ _edit_event(repo, "a.py")+ assert _read_event(repo, "a.py", num_lines=10) is None++ def test_per_file_isolation(self, repo: Path) -> None:+ _write_big_file(repo, "a.py", lines=10)+ _write_big_file(repo, "b.py", lines=10)+ _read_event(repo, "a.py", num_lines=10)+ _edit_event(repo, "b.py") # different file+ assert _read_event(repo, "a.py", num_lines=10) is None++ def test_new_session_forgets_history(self, repo: Path) -> None:+ _write_big_file(repo, "a.py", lines=10)+ _read_event(repo, "a.py", num_lines=10)+ _edit_event(repo, "a.py")+ assert _read_event(repo, "a.py", num_lines=10, session="other") is None++ def test_edit_outside_repo_records_nothing(self, repo: Path, tmp_path: Path) -> None:+ outside = tmp_path.parent / "elsewhere.py"+ result = _handle_post_tool_use(+ "Edit",+ {"file_path": str(outside)},+ {"success": True},+ str(repo),+ session_id=SESSION,+ )+ assert result is None+ state = _load_session_state(repo, SESSION)+ assert state["edits"] == {}+++class TestSessionState:+ def test_state_file_lives_under_repowise(self, repo: Path) -> None:+ _write_big_file(repo, "a.py", lines=10)+ _read_event(repo, "a.py", num_lines=10)+ assert _session_state_path(repo).exists()+ state = json.loads(_session_state_path(repo).read_text(encoding="utf-8"))+ assert state["session_id"] == SESSION+ assert "a.py" in state["reads"]++ def test_corrupt_state_file_is_replaced_not_fatal(self, repo: Path) -> None:+ _session_state_path(repo).write_text("{not json", encoding="utf-8")+ _write_big_file(repo, "a.py", lines=10)+ assert _read_event(repo, "a.py", num_lines=10) is None+ state = _load_session_state(repo, SESSION)+ assert "a.py" in state["reads"]++ def test_state_trims_unbounded_growth(self, repo: Path) -> None:+ from repowise.cli.commands.augment_cmd import _save_session_state++ state = {+ "session_id": SESSION,+ "reads": {f"f{i}.py": float(i) for i in range(600)},+ "edits": {},+ "nudged": [],+ "stale_notified": [],+ }+ _save_session_state(repo, state)+ saved = json.loads(_session_state_path(repo).read_text(encoding="utf-8"))+ assert len(saved["reads"]) == 400+ # Most recent timestamps survive the trim.+ assert "f599.py" in saved["reads"]+ assert "f0.py" not in saved["reads"]++ def test_codex_edit_banner_still_fires_and_records(self, repo: Path) -> None:+ (repo / ".repowise" / "state.json").write_text("{}", encoding="utf-8")+ result = _handle_post_tool_use(+ "Edit",+ {"file_path": str(repo / "a.py")},+ {"success": True},+ str(repo),+ client="codex",+ session_id=SESSION,+ )+ assert result is not None and "Files were edited" in result+ state = _load_session_state(repo, SESSION)+ assert "a.py" in state["edits"]diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.pynew file mode 100644index 000000000..a69d3fadc--- /dev/null+++ b/tests/unit/distill/test_rewrite_hook.py@@ -0,0 +1,272 @@+"""repowise-rewrite PreToolUse hook — classification, bailouts, permissions.++The decision table here is the contract: payload in → rewrite/passthrough+out. The hook is allowlist-based (only table families are rewritten) and+every ambiguity resolves to passthrough.+"""++from __future__ import annotations++import io+import json+import sys++import pytest+import yaml++from repowise.cli import rewrite_hook+from repowise.cli.rewrite_hook import FAMILY_PATTERNS, _normalize, classify, decide++# ---------------------------------------------------------------------------+# Classification decision table+# ---------------------------------------------------------------------------+++class TestClassify:+ @pytest.mark.parametrize(+ ("command", "family"),+ [+ # test runners+ ("pytest -x", "test_output"),+ ("pytest tests/unit -q", "test_output"),+ ("uv run pytest tests/unit", "test_output"),+ ("python -m pytest tests", "test_output"),+ (r".venv\Scripts\pytest.exe -q", "test_output"),+ ("npm test", "test_output"),+ ("yarn test", "test_output"),+ ("cargo test", "test_output"),+ ("go test ./...", "test_output"),+ ("npx vitest run", "test_output"),+ # builds+ ("npm run build", "build_output"),+ ("npm run type-check", "build_output"),+ ("tsc --noEmit", "build_output"),+ ("cargo build --release", "build_output"),+ ("go vet ./...", "build_output"),+ ("make", "build_output"),+ # git+ ("git status", "git_status"),+ ("git log --oneline -20", "git_log"),+ ("git diff main", "git_diff"),+ ("git show HEAD~2", "git_diff"),+ # search / listings / logs+ ("rg TODO src/", "search_results"),+ ("grep -rn auth .", "search_results"),+ ("git grep parse_yaml", "search_results"),+ ("ls -la", "file_listing"),+ ("find . -name '*.py'", "file_listing"),+ ("tree src", "file_listing"),+ ("tail -n 100 app.log", "logs"),+ ("cat server.log", "logs"),+ ],+ )+ def test_rewrites(self, command: str, family: str) -> None:+ assert classify(command) == family++ @pytest.mark.parametrize(+ "command",+ [+ # ignore-list+ "cd packages/core",+ "echo hello",+ "mkdir -p foo",+ "rm -rf build",+ "mv a b",+ "cp a b",+ "touch x",+ "pwd",+ "which python",+ "sleep 5",+ # interactive+ "vim foo.py",+ "less README.md",+ "ssh host",+ "python script.py",+ "node server.js",+ # compound / pipes / redirections / substitution+ "pytest | head -50",+ "pytest && echo done",+ "pytest || true",+ "git status; ls",+ "pytest > out.txt 2>&1",+ "pytest < input.txt",+ "git log `git rev-parse HEAD`",+ "pytest $(cat args.txt)",+ "pytest -x &",+ "pytest -x\ngit status",+ "find . -name '*.tmp' -exec rm {} ;",+ # watch / follow modes+ "vitest --watch",+ "npm test -- --watchAll",+ "pytest --looponfail",+ "tail -f app.log",+ "kubectl logs --follow pod",+ # already repowise+ "repowise distill pytest -x",+ "repowise update",+ "repowise-augment",+ # opted-out variants+ "git status --porcelain",+ "git diff --stat",+ # non-table commands+ "docker compose up",+ "curl https://example.com",+ "",+ " ",+ ],+ )+ def test_passthrough(self, command: str) -> None:+ assert classify(command) is None++ def test_family_names_match_registered_filters(self) -> None:+ """Per-family config keys must be real filter names in the core registry."""+ from repowise.core.distill import filter_registry++ registered = {f.name for f in filter_registry.filters()}+ for family, _ in FAMILY_PATTERNS:+ assert family in registered++ @pytest.mark.parametrize(+ "command",+ [+ "pytest -x",+ "FOO=bar pytest",+ "uv run python -m pytest tests",+ r".venv\Scripts\pytest.exe -q",+ "npx jest --ci",+ "git status",+ "LS_COLORS=1 ls -la",+ ],+ )+ def test_normalize_mirrors_core_router(self, command: str) -> None:+ """The hot-path normalizer must stay behaviorally identical to core's."""+ from repowise.core.distill.router import normalize_command++ assert _normalize(command) == normalize_command(command)+++# ---------------------------------------------------------------------------+# decide() — repo gating + permission config+# ---------------------------------------------------------------------------+++def repo(tmp_path):+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++def _write_config(repo, distill_block) -> None:+ (repo / ".repowise" / "config.yaml").write_text(+ yaml.dump({"distill": distill_block}), encoding="utf-8"+ )+++class TestDecide:+ def test_default_is_ask(self, repo) -> None:+ result = decide("pytest -x", str(repo))+ assert result is not None+ assert result.command == "repowise distill pytest -x"+ assert result.permission == "ask"+ assert "repowise expand" in result.reason++ def test_no_repowise_dir_passes_through(self, tmp_path) -> None:+ assert decide("pytest -x", str(tmp_path)) is None++ def test_cwd_below_repo_root_is_found(self, repo) -> None:+ nested = repo / "packages" / "core"+ nested.mkdir(parents=True)+ assert decide("pytest -x", str(nested)) is not None++ def test_distill_disabled(self, repo) -> None:+ _write_config(repo, {"enabled": False})+ assert decide("pytest -x", str(repo)) is None++ def test_commands_disabled(self, repo) -> None:+ _write_config(repo, {"commands": {"enabled": False}})+ assert decide("pytest -x", str(repo)) is None++ def test_permission_off_disables(self, repo) -> None:+ _write_config(repo, {"commands": {"permission": "off"}})+ assert decide("pytest -x", str(repo)) is None++ def test_global_allow(self, repo) -> None:+ _write_config(repo, {"commands": {"permission": "allow"}})+ assert decide("git status", str(repo)).permission == "allow"++ def test_family_allow_overrides_ask(self, repo) -> None:+ _write_config(repo, {"commands": {"families": {"git_status": "allow"}}})+ assert decide("git status", str(repo)).permission == "allow"+ assert decide("pytest -x", str(repo)).permission == "ask"++ def test_family_off_disables_one_family(self, repo) -> None:+ _write_config(repo, {"commands": {"families": {"git_diff": "off"}}})+ assert decide("git diff main", str(repo)) is None+ assert decide("git status", str(repo)) is not None++ def test_family_deny_alias(self, repo) -> None:+ _write_config(repo, {"commands": {"families": {"git_diff": "deny"}}})+ assert decide("git diff main", str(repo)) is None++ def test_malformed_config_defaults_to_ask(self, repo) -> None:+ (repo / ".repowise" / "config.yaml").write_text(+ "distill: [not, a, mapping", encoding="utf-8"+ )+ result = decide("pytest -x", str(repo))+ assert result is not None and result.permission == "ask"+++# ---------------------------------------------------------------------------+# End-to-end: PreToolUse payload in, hookSpecificOutput JSON out+# ---------------------------------------------------------------------------+++def _run_main(monkeypatch, payload) -> str:+ stdin = io.StringIO(payload if isinstance(payload, str) else json.dumps(payload))+ stdout = io.StringIO()+ monkeypatch.setattr(sys, "stdin", stdin)+ monkeypatch.setattr(sys, "stdout", stdout)+ with pytest.raises(SystemExit) as exc:+ rewrite_hook.main()+ assert exc.value.code == 0+ return stdout.getvalue()+++def _payload(command: str, cwd: str, **overrides):+ base = {+ "session_id": "abc123",+ "transcript_path": "/tmp/transcript.jsonl",+ "cwd": cwd,+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": command},+ }+ base.update(overrides)+ return base+++class TestMain:+ def test_rewrite_response_shape(self, monkeypatch, repo) -> None:+ out = _run_main(monkeypatch, _payload("pytest -x", str(repo)))+ response = json.loads(out)+ hso = response["hookSpecificOutput"]+ assert hso["hookEventName"] == "PreToolUse"+ assert hso["permissionDecision"] == "ask"+ assert hso["updatedInput"] == {"command": "repowise distill pytest -x"}+ assert hso["permissionDecisionReason"]++ def test_passthrough_emits_nothing(self, monkeypatch, repo) -> None:+ assert _run_main(monkeypatch, _payload("cd src", str(repo))) == ""++ def test_non_bash_tool_ignored(self, monkeypatch, repo) -> None:+ assert _run_main(monkeypatch, _payload("pytest", str(repo), tool_name="Grep")) == ""++ def test_post_tool_use_ignored(self, monkeypatch, repo) -> None:+ payload = _payload("pytest", str(repo), hook_event_name="PostToolUse")+ assert _run_main(monkeypatch, payload) == ""++ def test_malformed_json_is_silent(self, monkeypatch) -> None:+ assert _run_main(monkeypatch, "{not json") == ""++ def test_empty_stdin_is_silent(self, monkeypatch) -> None:+ assert _run_main(monkeypatch, "") == ""diff --git a/tests/unit/distill/test_rewrite_perf.py b/tests/unit/distill/test_rewrite_perf.pynew file mode 100644index 000000000..c55bb963a--- /dev/null+++ b/tests/unit/distill/test_rewrite_perf.py@@ -0,0 +1,87 @@+"""Hot-path guarantees for the ``repowise-rewrite`` PreToolUse hook.++The hook fires on EVERY Bash tool call an agent makes, so it must answer in+well under 100 ms p95. Two layers of protection:++ 1. An import-graph guard: the hook module (and the adapters it uses) must+ never pull click, sqlalchemy, structlog, or any ``repowise.core``+ module — those are where the startup milliseconds hide.+ 2. An end-to-end wall-clock budget over repeated subprocess invocations,+ measured against the real console script when the venv provides one.+"""++from __future__ import annotations++import json+import subprocess+import sys+import time+from pathlib import Path++_HEAVY_PREFIXES = (+ "click",+ "sqlalchemy",+ "structlog",+ "networkx",+ "yaml",+ "rich",+ "repowise.core",+ "repowise.cli.main",+ "repowise.cli.helpers",+)+++def test_import_pulls_no_heavy_modules() -> None:+ """Importing the hook module must not load the heavy stack.++ (yaml IS imported lazily when a config.yaml exists — that's a deliberate+ pay-only-when-needed cost — but plain import must stay clean.)+ """+ code = (+ "import sys; "+ "import repowise.cli.rewrite_hook; "+ "import repowise.cli.agent_adapters.claude_code; "+ f"heavy = [m for m in sys.modules if m.startswith({_HEAVY_PREFIXES!r})]; "+ "print('\\n'.join(heavy)); "+ "sys.exit(1 if heavy else 0)"+ )+ result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)+ assert result.returncode == 0, f"heavy imports leaked:\n{result.stdout}{result.stderr}"+++def _hook_invocation() -> list[str]:+ """Prefer the real console script (what the agent actually runs)."""+ exe = Path(sys.executable).parent / (+ "repowise-rewrite.exe" if sys.platform == "win32" else "repowise-rewrite"+ )+ if exe.exists():+ return [str(exe)]+ return [sys.executable, "-c", "from repowise.cli.rewrite_hook import main; main()"]+++def test_p95_under_100ms(tmp_path: Path) -> None:+ (tmp_path / ".repowise").mkdir()+ payload = json.dumps(+ {+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": "pytest -x"},+ "cwd": str(tmp_path),+ }+ )+ cmd = _hook_invocation()++ # Warmup: first run pays one-off filesystem cache costs.+ subprocess.run(cmd, input=payload, capture_output=True, text=True)++ timings: list[float] = []+ for _ in range(12):+ start = time.perf_counter()+ result = subprocess.run(cmd, input=payload, capture_output=True, text=True)+ timings.append((time.perf_counter() - start) * 1000)+ assert result.returncode == 0+ assert "repowise distill pytest -x" in result.stdout++ timings.sort()+ p95 = timings[int(len(timings) * 0.95) - 1]+ assert p95 < 100, f"repowise-rewrite p95 {p95:.1f} ms >= 100 ms (all: {timings})"diff --git a/tests/unit/distill/test_router.py b/tests/unit/distill/test_router.pynew file mode 100644index 000000000..f406a7ceb--- /dev/null+++ b/tests/unit/distill/test_router.py@@ -0,0 +1,85 @@+"""Unit tests for command normalization and filter selection."""++from __future__ import annotations++import pytest++from repowise.core.distill.router import normalize_command, select_filter+++ ("raw", "expected"),+ [+ ("git status", "git status"),+ ("GIT STATUS", "git status"),+ ("uv run pytest -x", "pytest -x"),+ ("python -m pytest tests/unit", "pytest tests/unit"),+ ("uv run python -m pytest", "pytest"),+ (".venv\\Scripts\\pytest.exe -q", "pytest -q"),+ ("C:\\tools\\git.exe log", "git log"),+ ("/usr/bin/git diff", "git diff"),+ ("FOO=bar npm test", "npm test"),+ ("npx vitest run", "vitest run"),+ ],+)+def test_normalize_command(raw: str, expected: str) -> None:+ assert normalize_command(raw) == expected+++ ("command", "filter_name"),+ [+ ("git status", "git_status"),+ ("git log --oneline -20", "git_log"),+ ("git diff HEAD~3", "git_diff"),+ ("git show HEAD", "git_diff"),+ ("pytest tests/unit -x", "test_output"),+ ("uv run pytest", "test_output"),+ ("cargo test --workspace", "test_output"),+ ("go test ./...", "test_output"),+ ("npm test", "test_output"),+ ("npm run build", "build_output"),+ ("tsc --noEmit", "build_output"),+ ("cargo build --release", "build_output"),+ ("npm run type-check", "build_output"),+ ("find . -name *.py", "file_listing"),+ ("ls -la", "file_listing"),+ ("tree packages", "file_listing"),+ ("tail -200 app.log", "logs"),+ ("docker logs api", "logs"),+ ("kubectl logs pod-1", "logs"),+ ],+)+def test_select_filter_by_command(command: str, filter_name: str) -> None:+ chosen = select_filter(command)+ assert chosen is not None, f"no filter matched {command!r}"+ assert chosen.name == filter_name+++ "command",+ [+ "echo hello",+ "cd packages",+ "rm -rf build",+ "git push origin main",+ "git commit -m msg",+ "python script.py",+ "lsof -i :8000", # 'ls' must not greedily match+ "git statuses", # word boundary+ ],+)+def test_unrelated_commands_do_not_match(command: str) -> None:+ assert select_filter(command) is None+++def test_content_sniff_fallback_when_no_command(load_fixture) -> None:+ output = load_fixture("pytest_fail.txt")+ chosen = select_filter("", output)+ assert chosen is not None+ assert chosen.name == "test_output"+++def test_disabled_filters_are_skipped() -> None:+ assert select_filter("git status").name == "git_status"+ assert select_filter("git status", disabled=("git_status",)) is Nonediff --git a/tests/unit/distill/test_saved_cmd.py b/tests/unit/distill/test_saved_cmd.pynew file mode 100644index 000000000..645442c4f--- /dev/null+++ b/tests/unit/distill/test_saved_cmd.py@@ -0,0 +1,200 @@+"""Unit tests for ``repowise saved`` and the tracking rollup SQL."""++from __future__ import annotations++import time+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.cli.commands.saved_cmd import saved_command+from repowise.core.distill import tracking+from repowise.core.distill.store import OmissionStore+++def repo_cwd(tmp_path: Path, monkeypatch) -> Path:+ """A scratch repo with .repowise/ so the store lands locally."""+ (tmp_path / ".repowise").mkdir()+ monkeypatch.chdir(tmp_path)+ return tmp_path+++def _seed(store: OmissionStore) -> None:+ store.record_saving(+ filter_name="test_output",+ source="cli",+ command="pytest",+ raw_tokens=10_000,+ distilled_tokens=1_000,+ )+ store.record_saving(+ filter_name="test_output",+ source="hook",+ command="pytest -x",+ raw_tokens=5_000,+ distilled_tokens=500,+ )+ store.record_saving(+ filter_name="git_status",+ source="hook",+ command="git status",+ raw_tokens=400,+ distilled_tokens=100,+ )+++def _store(repo: Path) -> OmissionStore:+ return OmissionStore(repo / ".repowise" / "omissions" / "omissions.db")+++# -- tracking rollups -------------------------------------------------------+++def test_rollup_by_filter_orders_by_saved_desc(store: OmissionStore) -> None:+ _seed(store)+ rows = store.savings_rollup(by="filter")+ assert [r["group"] for r in rows] == ["test_output", "git_status"]+ assert rows[0]["events"] == 2+ assert rows[0]["saved_tokens"] == 13_500+ assert rows[1]["saved_tokens"] == 300+++def test_rollup_by_source(store: OmissionStore) -> None:+ _seed(store)+ rows = store.savings_rollup(by="source")+ by_group = {r["group"]: r for r in rows}+ assert by_group["cli"]["events"] == 1+ assert by_group["hook"]["events"] == 2+ assert by_group["hook"]["saved_tokens"] == 4_800+++def test_rollup_by_day_buckets_chronologically(store: OmissionStore) -> None:+ _seed(store)+ # Backdate one event by two days; the rollup must produce two buckets+ # in chronological order.+ store._conn.execute(+ "UPDATE savings SET created_at = created_at - 2 * 86400 WHERE filter = 'git_status'"+ )+ store._conn.commit()+ rows = store.savings_rollup(by="day")+ assert len(rows) == 2+ assert rows[0]["group"] < rows[1]["group"] # ISO dates sort lexically+ assert rows[0]["saved_tokens"] == 300+++def test_rollup_unknown_dimension_raises(store: OmissionStore) -> None:+ with pytest.raises(ValueError, match="Unknown rollup dimension"):+ store.savings_rollup(by="command")+++def test_summary_and_rollup_honor_since(store: OmissionStore) -> None:+ _seed(store)+ store._conn.execute(+ "UPDATE savings SET created_at = created_at - 10 * 86400 WHERE filter = 'git_status'"+ )+ store._conn.commit()+ cutoff = time.time() - 86400+ summary = store.savings_summary(since=cutoff)+ assert summary["events"] == 2+ assert "git_status" not in summary["per_filter"]+ rows = store.savings_rollup(by="filter", since=cutoff)+ assert [r["group"] for r in rows] == ["test_output"]+++def test_rollup_dimensions_constant_matches_columns() -> None:+ assert set(tracking.ROLLUP_DIMENSIONS) == set(tracking._ROLLUP_COLUMNS)+++# -- repowise saved ---------------------------------------------------------+++def test_saved_reports_totals_and_per_filter(repo_cwd: Path) -> None:+ s = _store(repo_cwd)+ _seed(s)+ s.close()+ result = CliRunner().invoke(saved_command, [])+ assert result.exit_code == 0+ assert "test_output" in result.output+ assert "git_status" in result.output+ assert "TOTAL" in result.output+ assert "13,800" in result.output # total saved tokens+ assert "Estimated saved" in result.output+ # The scope caveat must be visible in the report itself (normalize+ # whitespace — rich wraps the caption at terminal width).+ flat = " ".join(result.output.split())+ assert "MCP response truncation is not counted" in flat+++def test_saved_by_day(repo_cwd: Path) -> None:+ s = _store(repo_cwd)+ _seed(s)+ s.close()+ result = CliRunner().invoke(saved_command, ["--by", "day"])+ assert result.exit_code == 0+ assert "Events" in result.output+++def test_saved_dollar_estimate_uses_input_rate(repo_cwd: Path) -> None:+ s = _store(repo_cwd)+ s.record_saving(+ filter_name="test_output",+ source="cli",+ command="pytest",+ raw_tokens=1_000_000,+ distilled_tokens=0,+ )+ s.close()+ # claude-sonnet-4-6 input rate is $3.00/M -> exactly $3.00 for 1M saved.+ result = CliRunner().invoke(saved_command, [])+ assert result.exit_code == 0+ assert "$3.0000" in result.output+++def test_saved_no_store_prints_hint(repo_cwd: Path) -> None:+ result = CliRunner().invoke(saved_command, [])+ assert result.exit_code == 0+ assert "No savings recorded yet" in result.output+ assert "repowise distill" in result.output+++def test_saved_empty_ledger_prints_message(repo_cwd: Path) -> None:+ _store(repo_cwd).close() # creates the DB with zero ledger rows+ result = CliRunner().invoke(saved_command, [])+ assert result.exit_code == 0+ assert "No distillation events recorded" in result.output+++def test_saved_since_filters_events(repo_cwd: Path) -> None:+ s = _store(repo_cwd)+ _seed(s)+ s._conn.execute(+ "UPDATE savings SET created_at = created_at - 10 * 86400 WHERE filter = 'git_status'"+ )+ s._conn.commit()+ s.close()+ from datetime import date, timedelta++ cutoff = (date.today() - timedelta(days=1)).isoformat()+ result = CliRunner().invoke(saved_command, ["--since", cutoff])+ assert result.exit_code == 0+ assert "git_status" not in result.output+ assert "test_output" in result.output+++def test_saved_bad_since_fails_cleanly(repo_cwd: Path) -> None:+ result = CliRunner().invoke(saved_command, ["--since", "not-a-date"])+ assert result.exit_code != 0+ assert "Cannot parse date" in result.output+++def test_saved_explicit_path_argument(tmp_path: Path) -> None:+ repo = tmp_path / "elsewhere"+ (repo / ".repowise").mkdir(parents=True)+ s = _store(repo)+ _seed(s)+ s.close()+ result = CliRunner().invoke(saved_command, [str(repo)])+ assert result.exit_code == 0+ assert "test_output" in result.outputdiff --git a/tests/unit/distill/test_search_results.py b/tests/unit/distill/test_search_results.pynew file mode 100644index 000000000..55f49d1c5--- /dev/null+++ b/tests/unit/distill/test_search_results.py@@ -0,0 +1,116 @@+"""search_results filter — grouped-by-file compaction of grep/rg floods."""++from __future__ import annotations++import pytest++from repowise.core.distill import distill_output, estimate_tokens+from repowise.core.distill.filters.search_results import (+ SearchResultsFilter,+ group_search_matches,+ render_search_digest,+)+from repowise.core.distill.router import select_filter++[email protected](scope="module")+def filt() -> SearchResultsFilter:+ return SearchResultsFilter()+++class TestRouting:+ @pytest.mark.parametrize(+ "command",+ ["rg TODO", "grep -rn auth src/", "git grep parse_yaml", "egrep -i err *.txt"],+ )+ def test_command_match(self, command: str) -> None:+ chosen = select_filter(command)+ assert chosen is not None and chosen.name == "search_results"++ @pytest.mark.parametrize("command", ["git status", "ls -la", "pytest -x"])+ def test_other_commands_not_claimed(self, command: str) -> None:+ chosen = select_filter(command)+ assert chosen is None or chosen.name != "search_results"++ def test_content_sniff_on_flood(self, filt, load_fixture) -> None:+ assert filt.matches_content(load_fixture("rg_flood.txt")) is True++ def test_content_sniff_rejects_prose(self, filt) -> None:+ prose = "\n".join(f"line {i} of plain text" for i in range(60))+ assert filt.matches_content(prose) is False+++class TestGrouping:+ def test_flat_format(self) -> None:+ out = "src/a.py:10:def foo():\nsrc/a.py:42:def bar():\nsrc/b.py:7:def baz():"+ groups = group_search_matches(out)+ assert groups is not None+ assert list(groups) == ["src/a.py", "src/b.py"]+ assert groups["src/a.py"] == [(10, "def foo():"), (42, "def bar():")]++ def test_headed_rg_format(self) -> None:+ out = "src/a.py\n10:def foo():\n42:def bar():\n\nsrc/b.py\n7:def baz():"+ groups = group_search_matches(out)+ assert groups is not None+ assert groups["src/b.py"] == [(7, "def baz():")]++ def test_windows_drive_paths(self) -> None:+ out = "\n".join(f"C:\\repo\\src\\a.py:{i}:hit {i}" for i in range(1, 11))+ groups = group_search_matches(out)+ assert groups is not None+ assert len(groups["C:\\repo\\src\\a.py"]) == 10++ def test_unparseable_returns_none(self) -> None:+ assert group_search_matches("just some text\nwithout matches") is None+ assert group_search_matches("") is None++ def test_real_fixture_parses(self, load_fixture) -> None:+ groups = group_search_matches(load_fixture("rg_flood.txt"))+ assert groups is not None+ assert len(groups) > 5+ total = sum(len(v) for v in groups.values())+ assert total > 200+++class TestRendering:+ def test_digest_has_counts_and_anchors(self, load_fixture) -> None:+ raw = load_fixture("rg_flood.txt")+ groups = group_search_matches(raw)+ digest = render_search_digest(groups)+ head = digest.splitlines()[0]+ assert "matches in" in head and "files:" in head+ # Anchors carry line numbers.+ assert "L" in digest+ # Compaction is real.+ assert estimate_tokens(digest) < estimate_tokens(raw) * 0.5++ def test_file_order_override(self) -> None:+ out = "a.py:1:x\nb.py:1:x\nb.py:2:x\nc.py:1:x"+ groups = group_search_matches(out)+ digest = render_search_digest(groups, file_order=["c.py", "a.py", "b.py"])+ lines = [ln for ln in digest.splitlines() if ln.startswith(" ") and "(" in ln]+ assert lines[0].strip().startswith("c.py")++ def test_hidden_files_footer(self) -> None:+ out = "\n".join(f"f{i}.py:{j}:hit" for i in range(40) for j in range(1, 4))+ groups = group_search_matches(out)+ digest = render_search_digest(groups, max_files=10)+ assert "more files" in digest.splitlines()[-1]+++class TestEngine:+ def test_distill_round_trip(self, load_fixture, store) -> None:+ raw = load_fixture("rg_flood.txt")+ result = distill_output(raw, command='rg "def " -n packages', store=store)+ assert result.distilled is True+ assert result.filter_name == "search_results"+ assert result.savings_pct >= 40.0+ assert store.get(result.ref) == raw++ def test_files_only_output_falls_back_raw(self, store) -> None:+ # rg -l style: bare path lines sniff as file_listing territory, and+ # the search filter must raise → engine returns raw via this command.+ raw = "\n".join(f"src/dir{i}/file{i}.py" for i in range(40))+ result = distill_output(raw, command="rg -l TODO", store=store)+ assert result.distilled is False+ assert result.text == rawdiff --git a/tests/unit/distill/test_skeleton.py b/tests/unit/distill/test_skeleton.pynew file mode 100644index 000000000..b67b81473--- /dev/null+++ b/tests/unit/distill/test_skeleton.py@@ -0,0 +1,243 @@+"""Golden tests for index-backed skeletonization.++Fixtures are real files from this repo pinned at the commit the index was+built from (``*.src.txt`` content + ``*.symbols.json`` WikiSymbol rows with+symbol-node PageRank), so the tests never depend on the live working tree+or on a parser running at test time.+"""++from __future__ import annotations++import json++import pytest++from repowise.core.distill.skeleton import (+ SkeletonResult,+ SkeletonSymbol,+ build_skeleton,+ estimate_skeleton_tokens,+)+++def _load_case(load_fixture, stem: str) -> tuple[str, list[SkeletonSymbol]]:+ source = load_fixture(f"{stem}.src.txt")+ payload = json.loads(load_fixture(f"{stem}.symbols.json"))+ symbols = [+ SkeletonSymbol(+ name=s["name"],+ kind=s["kind"],+ start_line=s["start_line"],+ end_line=s["end_line"],+ signature=s["signature"],+ importance=s["pagerank"],+ )+ for s in payload["symbols"]+ ]+ return source, symbols++[email protected](scope="module")+def python_case(load_fixture):+ return _load_case(load_fixture, "skeleton_traverser")++[email protected](scope="module")+def tsx_case(load_fixture):+ return _load_case(load_fixture, "skeleton_artifacts")+++class TestSignaturesMode:+ def test_size_and_completeness_python(self, python_case) -> None:+ source, symbols = python_case+ result = build_skeleton(source, symbols, mode="signatures")+ assert result.mode == "signatures"+ # Exit criterion: a ~600-line file compresses to <=~15% of full tokens.+ assert result.skeleton_tokens <= result.full_tokens * 0.15, (+ f"{result.skeleton_tokens}/{result.full_tokens} = {result.pct_of_full:.1f}%"+ )+ # Every signature line is present verbatim.+ lines = source.splitlines()+ for sym in symbols:+ if sym.name == "__module__":+ continue+ assert lines[sym.start_line - 1] in result.text, sym.name++ def test_size_and_completeness_tsx(self, tsx_case) -> None:+ source, symbols = tsx_case+ result = build_skeleton(source, symbols, mode="signatures")+ assert result.skeleton_tokens <= result.full_tokens * 0.35+ lines = source.splitlines()+ for sym in symbols:+ assert lines[sym.start_line - 1] in result.text, sym.name++ def test_imports_and_module_docstring_kept(self, python_case) -> None:+ source, symbols = python_case+ result = build_skeleton(source, symbols, mode="signatures")+ for line in source.splitlines():+ if line.startswith(("import ", "from ")):+ assert line in result.text, line+ # Module docstring opener is the first line of the file.+ assert source.splitlines()[0] in result.text++ def test_elision_markers_carry_line_ranges(self, python_case) -> None:+ source, symbols = python_case+ result = build_skeleton(source, symbols, mode="signatures")+ import re++ markers = re.findall(r"\.\.\. (\d+) lines \((\d+)-(\d+)\)", result.text)+ assert markers, "expected at least one elision marker"+ for n, a, b in markers:+ assert int(b) - int(a) + 1 == int(n)+ assert 1 <= int(a) <= int(b) <= len(source.splitlines())++ def test_no_bodies_in_signatures_mode(self, python_case) -> None:+ source, symbols = python_case+ result = build_skeleton(source, symbols, mode="signatures")+ assert result.bodies_kept == ()+++class TestSmartMode:+ def test_keeps_high_pagerank_bodies(self, python_case) -> None:+ source, symbols = python_case+ result = build_skeleton(source, symbols, mode="smart", token_budget=2500)+ assert result.bodies_kept, "smart mode kept no bodies"+ # The kept bodies are the top-importance leaf symbols, in rank order.+ ranked = sorted(symbols, key=lambda s: -s.importance)+ top_names = [s.name for s in ranked[:10]]+ assert result.bodies_kept[0] in top_names+ # And the skeleton is strictly larger than signatures-only.+ sig_only = build_skeleton(source, symbols, mode="signatures")+ assert result.skeleton_tokens > sig_only.skeleton_tokens++ def test_respects_token_budget(self, python_case) -> None:+ source, symbols = python_case+ small = build_skeleton(source, symbols, mode="smart", token_budget=900)+ large = build_skeleton(source, symbols, mode="smart", token_budget=3000)+ assert small.skeleton_tokens <= large.skeleton_tokens+ # Budget bounds the output with slack for the signature floor.+ assert small.skeleton_tokens <= 900 * 1.3++ def test_query_match_boosts_symbol(self, python_case) -> None:+ source, symbols = python_case+ # Pick a low-importance leaf symbol and query for it by name.+ leaf = min(+ (s for s in symbols if s.end_line - s.start_line > 8),+ key=lambda s: s.importance,+ )+ result = build_skeleton(source, symbols, mode="smart", token_budget=2500, query=leaf.name)+ assert leaf.name in result.bodies_kept++ def test_hotspot_widens_budget(self, python_case) -> None:+ source, symbols = python_case+ cold = build_skeleton(source, symbols, mode="smart", token_budget=1500)+ hot = build_skeleton(source, symbols, mode="smart", token_budget=1500, hotspot=True)+ assert hot.skeleton_tokens >= cold.skeleton_tokens+++class TestDegradation:+ def test_no_symbols_returns_raw(self) -> None:+ source = "line one\nline two\nline three\n"+ result = build_skeleton(source, [])+ assert result.mode == "raw"+ assert result.text == source+ assert result.skeleton_tokens == result.full_tokens++ def test_out_of_range_symbols_returns_raw(self) -> None:+ source = "x = 1\n"+ bad = [SkeletonSymbol(name="ghost", kind="function", start_line=50, end_line=80)]+ result = build_skeleton(source, bad)+ assert result.mode == "raw"+ assert result.text == source++ def test_synthetic_module_symbol_ignored(self) -> None:+ source = "x = 1\ny = 2\n"+ syn = [SkeletonSymbol(name="__module__", kind="module", start_line=0, end_line=0)]+ result = build_skeleton(source, syn)+ assert result.mode == "raw"++ def test_end_line_clamped_to_file(self) -> None:+ source = "def f():\n return 1\n"+ sym = [SkeletonSymbol(name="f", kind="function", start_line=1, end_line=999)]+ result = build_skeleton(source, sym, mode="signatures")+ assert "def f():" in result.text++ def test_unknown_mode_falls_back_to_signatures(self, python_case) -> None:+ source, symbols = python_case+ result = build_skeleton(source, symbols, mode="banana")+ assert result.mode == "signatures"+ assert result.bodies_kept == ()+++class TestSignatureEndHeuristics:+ def test_multiline_python_signature(self) -> None:+ source = (+ "def f(\n"+ " a: int,\n"+ " b: str,\n"+ ") -> bool:\n"+ " x = 1\n"+ " y = 2\n"+ " z = 3\n"+ " w = 4\n"+ " return True\n"+ )+ sym = [SkeletonSymbol(name="f", kind="function", start_line=1, end_line=9)]+ result = build_skeleton(source, sym, mode="signatures")+ assert ") -> bool:" in result.text+ assert "return True" not in result.text++ def test_brace_language_signature(self) -> None:+ source = (+ "func Process(items []string) error {\n" + "\tstep := 0\n" * 8 + "\treturn nil\n}\n"+ )+ sym = [SkeletonSymbol(name="Process", kind="function", start_line=1, end_line=11)]+ result = build_skeleton(source, sym, mode="signatures")+ assert "func Process(items []string) error {" in result.text+ assert "step := 0" not in result.text++ def test_docstring_summary_kept_in_smart_mode_only(self) -> None:+ body = (+ ' """Summary line.\n\n Detail one.\n Detail two.\n Detail three.\n Detail four.\n """\n'+ + " x = 1\n" * 6+ )+ source = "def f():\n" + body + " return x\n"+ total = source.count("\n")+ sym = [SkeletonSymbol(name="f", kind="function", start_line=1, end_line=total)]+ smart = build_skeleton(source, sym, mode="smart", token_budget=1)+ assert '"""Summary line.' in smart.text+ sigs = build_skeleton(source, sym, mode="signatures")+ assert "Summary line." not in sigs.text+ assert "x = 1" not in sigs.text+++class TestEstimate:+ def test_estimate_tracks_real_skeleton(self, python_case) -> None:+ source, symbols = python_case+ real = build_skeleton(source, symbols, mode="signatures")+ est = estimate_skeleton_tokens(+ [(s.start_line, s.end_line) for s in symbols],+ file_size_bytes=len(source.encode("utf-8")),+ total_lines=len(source.splitlines()),+ )+ # Within 2x either way — good enough for a "~M tokens vs K" nudge.+ assert real.skeleton_tokens / 2 <= est <= real.skeleton_tokens * 2++ def test_estimate_empty_bounds(self) -> None:+ assert estimate_skeleton_tokens([], file_size_bytes=4000) == 1000++ def test_estimate_is_below_full(self, python_case) -> None:+ source, symbols = python_case+ size = len(source.encode("utf-8"))+ est = estimate_skeleton_tokens(+ [(s.start_line, s.end_line) for s in symbols], file_size_bytes=size+ )+ assert est < size // 4+++class TestResultShape:+ def test_pct_of_full(self) -> None:+ r = SkeletonResult(+ text="x", mode="signatures", full_tokens=200, skeleton_tokens=30, symbol_count=3+ )+ assert r.pct_of_full == 15.0diff --git a/tests/unit/distill/test_store.py b/tests/unit/distill/test_store.pynew file mode 100644index 000000000..f594d2ca2--- /dev/null+++ b/tests/unit/distill/test_store.py@@ -0,0 +1,134 @@+"""Unit tests for the OmissionStore sidecar."""++from __future__ import annotations++import time+from pathlib import Path++from repowise.core.distill.store import OmissionStore, content_ref, default_store_path+++def test_put_get_roundtrip(store: OmissionStore) -> None:+ content = "line one\nline two with unicode ✓\nline three"+ ref = store.put(content, source="cli:test_output", original_tokens=100, kept_tokens=20)+ assert len(ref) == 12+ assert store.get(ref) == content+++def test_put_is_idempotent_per_content(store: OmissionStore) -> None:+ a = store.put("same", source="cli:logs", original_tokens=10, kept_tokens=2)+ b = store.put("same", source="cli:logs", original_tokens=10, kept_tokens=2)+ assert a == b == content_ref("same")+++def test_get_unknown_ref_returns_none(store: OmissionStore) -> None:+ assert store.get("0" * 12) is None+ assert store.get("not-a-ref") is None+++def test_get_record_returns_provenance(store: OmissionStore) -> None:+ before = time.time()+ ref = store.put(+ "payload\nERROR boom", source="mcp:get_context", original_tokens=50, kept_tokens=5+ )+ record = store.get_record(ref)+ assert record["content"] == "payload\nERROR boom"+ assert record["source"] == "mcp:get_context"+ assert record["original_tokens"] == 50+ assert record["kept_tokens"] == 5+ assert record["created_at"] >= before+ # Query filtering applies to the record's content too.+ assert store.get_record(ref, query="^ERROR")["content"] == "ERROR boom"+ assert store.get_record("0" * 12) is None+++def test_get_with_query_filters_lines(store: OmissionStore) -> None:+ content = "FAILED test_a\npassed test_b\nFAILED test_c"+ ref = store.put(content, source="cli:test_output", original_tokens=10, kept_tokens=2)+ assert store.get(ref, query="FAILED") == "FAILED test_a\nFAILED test_c"+++def test_get_with_invalid_regex_falls_back_to_substring(store: OmissionStore) -> None:+ content = "a [bracket( line\nother"+ ref = store.put(content, source="cli:logs", original_tokens=10, kept_tokens=2)+ assert store.get(ref, query="[bracket(") == "a [bracket( line"+++def test_access_count_increments(store: OmissionStore) -> None:+ ref = store.put("content", source="cli:logs", original_tokens=10, kept_tokens=2)+ store.get(ref)+ store.get(ref)+ count = store._conn.execute(+ "SELECT access_count FROM omissions WHERE ref = ?", (ref,)+ ).fetchone()[0]+ assert count == 2+++def test_ttl_prune_drops_old_rows(tmp_path: Path) -> None:+ s = OmissionStore(tmp_path / "omissions.db", ttl_days=1)+ ref = s.put("old content", source="cli:logs", original_tokens=10, kept_tokens=2)+ # Backdate the row past the TTL, then trigger an opportunistic prune.+ s._conn.execute(+ "UPDATE omissions SET created_at = ? WHERE ref = ?",+ (time.time() - 2 * 86400, ref),+ )+ s._conn.commit()+ s.prune()+ assert s.get(ref) is None+ s.close()+++def test_size_cap_prunes_oldest_first(tmp_path: Path) -> None:+ # Cap small enough that two large random-ish payloads cannot coexist.+ s = OmissionStore(tmp_path / "omissions.db", max_mb=0.001) # 1 KB+ import random++ rng = random.Random(42)+ blob_a = "".join(chr(rng.randint(33, 126)) for _ in range(4000))+ blob_b = "".join(chr(rng.randint(33, 126)) for _ in range(4000))+ ref_a = s.put(blob_a, source="cli:logs", original_tokens=10, kept_tokens=2)+ s._conn.execute("UPDATE omissions SET created_at = created_at - 60 WHERE ref = ?", (ref_a,))+ s._conn.commit()+ ref_b = s.put(blob_b, source="cli:logs", original_tokens=10, kept_tokens=2)+ assert s.get(ref_a) is None # oldest evicted+ s.close()+ assert ref_b != ref_a+++def test_savings_ledger_roundtrip(store: OmissionStore) -> None:+ store.record_saving(+ filter_name="test_output",+ source="cli",+ command="pytest",+ raw_tokens=1000,+ distilled_tokens=100,+ )+ store.record_saving(+ filter_name="git_log",+ source="cli",+ command="git log",+ raw_tokens=500,+ distilled_tokens=50,+ )+ summary = store.savings_summary()+ assert summary["events"] == 2+ assert summary["raw_tokens"] == 1500+ assert summary["saved_tokens"] == 1350+ assert summary["per_filter"]["test_output"]["saved_tokens"] == 900+++def test_default_store_path_finds_repowise_dir(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ nested = repo / "src" / "deep"+ nested.mkdir(parents=True)+ (repo / ".repowise").mkdir()+ path = default_store_path(nested)+ assert path == repo / ".repowise" / "omissions" / "omissions.db"+++def test_default_store_path_falls_back_to_home(tmp_path: Path) -> None:+ # No .repowise anywhere up the tree (tmp_path is outside home's subtree+ # on CI runners; if not, the walk stops at home and still falls back).+ path = default_store_path(tmp_path)+ assert path.name == "omissions.db"+ assert ".repowise" in str(path)diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex 0d23bfb71..8790334ef 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -23,12 +23,13 @@ def _create_test_app():"""Create a FastAPI app without the lifespan (we manage state manually)."""from contextlib import asynccontextmanager+ from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse- from fastapi import FastAPIfrom repowise.server.routers import (c4,+ costs,dead_code,decisions,git,@@ -66,6 +67,7 @@ def _create_test_app():app.include_router(health.router)app.include_router(repos.router)+ app.include_router(costs.router)app.include_router(pages.router)app.include_router(search.router)app.include_router(jobs.router)diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pynew file mode 100644index 000000000..a6240e96a--- /dev/null+++ b/tests/unit/server/mcp/test_budget.py@@ -0,0 +1,398 @@+"""Tests for the shared MCP budgeter and reversible truncation.++Covers:+* OmissionCollector — round-trip through the omission store, inline markers,+ and the degrade-to-silent-drop posture on store failure.+* truncate_to_budget — dropped symbols / targets / skeleton texts are+ recoverable, and keep/drop decisions are unchanged by the collector.+* get_symbol — omission-ref overload (``repowise#<12-hex>``), query+ filtering, and byte-identical normal symbol resolution.+* Migrated tools (get_dead_code, get_risk trim helper, get_overview) — no+ silent truncation: every drop yields ``_meta.omitted`` refs that expand.+* CLI round-trip — ``repowise expand`` resolves MCP-origin rows.+"""++from __future__ import annotations++import copy+import json+from pathlib import Path++import pytest++from repowise.core.distill.markers import MARKER_RE+from repowise.core.distill.store import OmissionStore, default_store_path+from repowise.server.mcp_server._budget import OmissionCollector, truncate_to_budget+++def repo_root(tmp_path: Path) -> Path:+ """A fake repo that has opted into repowise (so the store is repo-local)."""+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++def _store_get(repo: Path, ref: str, query: str | None = None) -> str | None:+ store = OmissionStore(default_store_path(repo))+ try:+ return store.get(ref, query=query)+ finally:+ store.close()+++def _store_record(repo: Path, ref: str) -> dict | None:+ store = OmissionStore(default_store_path(repo))+ try:+ return store.get_record(ref)+ finally:+ store.close()+++# ---------------------------------------------------------------------------+# OmissionCollector+# ---------------------------------------------------------------------------+++def test_collector_combined_doc_round_trip(repo_root: Path):+ collector = OmissionCollector("test_tool", repo_root=repo_root)+ collector.add("first chunk", "alpha line one\nalpha line two")+ collector.add("second chunk", [{"file_path": "x.py", "count": 3}])++ response: dict = {"_meta": {"timing_ms": 1.0}}+ collector.attach(response)++ marker = response["omission_marker"]+ assert MARKER_RE.fullmatch(marker)+ omitted = response["_meta"]["omitted"]+ assert omitted["refs"] and omitted["tokens"] > 0+ assert "get_symbol" in omitted["restore"] and "repowise expand" in omitted["restore"]++ ref = omitted["refs"][0]+ content = _store_get(repo_root, ref)+ assert content is not None+ assert "alpha line one" in content+ assert "first chunk" in content and "second chunk" in content+ assert '"file_path": "x.py"' in content+ assert _store_record(repo_root, ref)["source"] == "mcp:test_tool"+++def test_collector_inline_marker_is_byte_identical(repo_root: Path):+ collector = OmissionCollector("test_tool", repo_root=repo_root)+ original = "def f():\n return 1\n\n# tail"+ marker = collector.add_inline("skeleton of x.py", original)+ assert marker is not None and MARKER_RE.fullmatch(marker)++ response: dict = {}+ collector.attach(response)+ refs = response["_meta"]["omitted"]["refs"]+ assert len(refs) == 1+ # Inline rows store the content alone — expand returns it verbatim.+ assert _store_get(repo_root, refs[0]) == original+ # No combined doc was queued, so no top-level marker.+ assert "omission_marker" not in response+++def test_collector_store_failure_degrades_silently(tmp_path: Path):+ # A *file* where the store's parent directory should be makes every+ # write fail; the collector must degrade to silent-drop, never raise.+ blocker = tmp_path / "blocker"+ blocker.write_text("not a directory")+ collector = OmissionCollector("test_tool", store_path=blocker / "omissions.db")++ assert collector.add_inline("label", "content") is None+ collector.add("label", "queued content")+ response: dict = {"_meta": {}}+ collector.attach(response)+ assert "omission_marker" not in response+ assert "omitted" not in response["_meta"]+++# ---------------------------------------------------------------------------+# truncate_to_budget with a collector+# ---------------------------------------------------------------------------+++def _big_response(n_targets: int = 4, n_symbols: int = 40) -> dict:+ targets = {}+ for i in range(n_targets):+ name = f"pkg/mod_{i}/file_{i}.py"+ targets[name] = {+ "target": name,+ "type": "file",+ "docs": {+ "title": f"File {i}",+ "content_md": f"BODY_{i} " + "x" * 2000,+ "symbols": [+ {+ "name": f"Sym{i}_{j}",+ "kind": "function",+ "signature": f"def sym_{j}(...)",+ "docstring": "d" * 200,+ }+ for j in range(n_symbols)+ ],+ },+ }+ return {"targets": targets, "_meta": {"timing_ms": 1.0}}+++def test_budgeter_dropped_content_recoverable(repo_root: Path):+ response = _big_response()+ collector = OmissionCollector("get_context", repo_root=repo_root)+ out = truncate_to_budget(response, char_budget=4000, collector=collector)++ assert out["truncated"] is True+ omitted = out["_meta"]["omitted"]+ assert omitted["refs"]+ assert MARKER_RE.fullmatch(out["omission_marker"])++ # Everything reported as dropped must be findable in the stored doc(s).+ stored = "\n".join(_store_get(repo_root, r) or "" for r in omitted["refs"])+ for tgt_name in out["dropped_targets"]:+ assert f"dropped target {tgt_name}" in stored+ for names in out["dropped_symbols"].values():+ for name in names:+ assert name in stored+ # Stage-1 heavy fields are captured too.+ assert "BODY_" in stored+++def test_budgeter_decisions_unchanged_by_collector(repo_root: Path):+ fixture = _big_response()+ plain = truncate_to_budget(copy.deepcopy(fixture), char_budget=4000)+ collector = OmissionCollector("get_context", repo_root=repo_root)+ collected = truncate_to_budget(copy.deepcopy(fixture), char_budget=4000, collector=collector)++ # Strip the additive reversibility fields; the rest must be identical.+ collected.pop("omission_marker", None)+ collected["_meta"].pop("omitted", None)+ assert json.dumps(collected, sort_keys=True, default=str) == json.dumps(+ plain, sort_keys=True, default=str+ )+++def _skeleton_response(text_chars: int = 12000) -> dict:+ return {+ "targets": {+ "pkg/big.py": {+ "target": "pkg/big.py",+ "type": "file",+ "docs": {"title": "Big", "symbols": [{"name": "f", "kind": "function"}]},+ "skeleton": {+ "mode": "smart",+ "tokens": text_chars // 4,+ "full_tokens": text_chars,+ "text": "line\n" * (text_chars // 5),+ },+ }+ },+ "_meta": {},+ }+++def test_skeleton_stage_replaces_text_with_marker(repo_root: Path):+ response = _skeleton_response()+ original = response["targets"]["pkg/big.py"]["skeleton"]["text"]+ collector = OmissionCollector("get_context", repo_root=repo_root)+ out = truncate_to_budget(response, char_budget=2000, collector=collector)++ skel = out["targets"]["pkg/big.py"]["skeleton"]+ assert skel["omitted"] is True+ assert MARKER_RE.fullmatch(skel["text"])+ assert out["truncated"] is True+ ref = MARKER_RE.fullmatch(skel["text"]).group("ref")+ assert _store_get(repo_root, ref) == original+++def test_skeleton_stage_without_collector_drops_with_note():+ out = truncate_to_budget(_skeleton_response(), char_budget=2000)+ skel = out["targets"]["pkg/big.py"]["skeleton"]+ assert "text" not in skel+ assert skel["omitted"] is True+ assert "budget" in skel["note"]+++# ---------------------------------------------------------------------------+# get_symbol — omission-ref overload + normal-path stability+# ---------------------------------------------------------------------------+++def _put_row(repo: Path, content: str, source: str = "mcp:test") -> str:+ store = OmissionStore(default_store_path(repo))+ try:+ return store.put(content, source=source, original_tokens=100, kept_tokens=0)+ finally:+ store.close()+++async def test_get_symbol_resolves_omission_ref(setup_mcp, repo_root: Path):+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import get_symbol++ mcp_mod._repo_path = str(repo_root)+ content = "ERROR first\nok line\nERROR second"+ ref = _put_row(repo_root, content)++ result = await get_symbol(f"repowise#{ref}")+ assert result["kind"] == "omission"+ assert result["content"] == content+ assert result["source"] == "mcp:test"+ assert result["ref"] == ref+ assert "created_at" in result++ filtered = await get_symbol(f"repowise#{ref}", query="^ERROR")+ assert filtered["content"] == "ERROR first\nERROR second"+ assert filtered["query"] == "^ERROR"+++async def test_get_symbol_accepts_pasted_marker(setup_mcp, repo_root: Path):+ import repowise.server.mcp_server as mcp_mod+ from repowise.core.distill.markers import render_marker+ from repowise.server.mcp_server import get_symbol++ mcp_mod._repo_path = str(repo_root)+ ref = _put_row(repo_root, "stashed content")+ marker = render_marker(ref, 1, 3)++ result = await get_symbol(marker)+ assert result["content"] == "stashed content"+++async def test_get_symbol_unknown_ref_errors(setup_mcp, repo_root: Path):+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import get_symbol++ mcp_mod._repo_path = str(repo_root)+ result = await get_symbol("repowise#" + "0" * 12)+ assert "error" in result+ assert "expired" in result["error"]+++async def test_get_symbol_normal_path_byte_identical(setup_mcp, repo_root: Path):+ """A real symbol_id must still slice the exact on-disk byte range."""+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import get_symbol++ src = repo_root / "src" / "auth"+ src.mkdir(parents=True)+ lines = [f"line {i}" for i in range(1, 121)]+ (src / "service.py").write_text("\n".join(lines), encoding="utf-8")+ mcp_mod._repo_path = str(repo_root)++ # WikiSymbol fixture rows: login spans lines 20..40 (see conftest).+ result = await get_symbol("src/auth/service.py::login")+ assert result["source"] == "\n".join(lines[19:40])+ assert result["start_line"] == 20 and result["end_line"] == 40+ assert result["truncated"] is False+++# ---------------------------------------------------------------------------+# Migrated tools — no silent truncation+# ---------------------------------------------------------------------------+++async def test_get_dead_code_truncation_is_expandable(setup_mcp, repo_root: Path):+ import repowise.server.mcp_server as mcp_mod+ from repowise.server.mcp_server import get_dead_code++ mcp_mod._repo_path = str(repo_root)+ # Fixture has two medium-tier findings; limit=1 drops one of them.+ result = await get_dead_code(limit=1)+ assert result["tiers"]["medium"]["truncated"] is True+ omitted = result["_meta"]["omitted"]+ assert omitted["refs"]++ stored = "\n".join(_store_get(repo_root, r) or "" for r in omitted["refs"])+ assert "OldModel" in stored # the dropped medium finding+ assert "medium-tier findings beyond limit=1" in stored+ rec = _store_record(repo_root, omitted["refs"][0])+ assert rec["source"] == "mcp:get_dead_code"+++def test_risk_trim_blast_lists_collects_drops(repo_root: Path):+ from repowise.server.mcp_server.tool_risk import _trim_blast_lists++ blast = {+ "transitive_affected": [f"pkg/f{i}.py" for i in range(20)],+ "overall_risk_score": 4.2,+ }+ collector = OmissionCollector("get_risk", repo_root=repo_root)+ trimmed = _trim_blast_lists(blast, None, collector)+ assert len(trimmed["transitive_affected"]) == 15+ assert trimmed["transitive_affected_truncated_total"] == 20++ response: dict = {"_meta": {}}+ collector.attach(response)+ refs = response["_meta"]["omitted"]["refs"]+ stored = _store_get(repo_root, refs[0])+ assert "pkg/f19.py" in stored and "pkg/f15.py" in stored+ assert "pkg/f14.py" not in stored # kept entries are not stored+++async def test_get_overview_module_cap_is_expandable(setup_mcp, session, repo_root: Path):+ from datetime import UTC, datetime++ import repowise.server.mcp_server as mcp_mod+ from repowise.core.persistence.models import Page+ from repowise.server.mcp_server import get_overview++ now = datetime(2026, 3, 19, tzinfo=UTC)+ for i in range(25):+ session.add(+ Page(+ id=f"module_page:src/extra{i:02d}",+ repository_id=setup_mcp,+ page_type="module_page",+ title=f"Extra Module {i:02d}",+ content=f"# Extra Module {i:02d}\n\nFiller.",+ target_path=f"src/extra{i:02d}",+ source_hash=f"extra{i}",+ model_name="mock",+ provider_name="mock",+ generation_level=4,+ confidence=0.9,+ freshness_status="fresh",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ )+ )+ await session.flush()++ mcp_mod._repo_path = str(repo_root)+ result = await get_overview()+ assert len(result["key_modules"]) == 20+ omitted = result["_meta"]["omitted"]+ stored = "\n".join(_store_get(repo_root, r) or "" for r in omitted["refs"])+ # 27 module pages total, ordered by title — the tail is in the store.+ assert "module pages beyond cap=20" in stored+ assert stored.count("Extra Module") + stored.count("Module") >= 7+++# ---------------------------------------------------------------------------+# Cross-surface round-trip — CLI expand resolves MCP-origin rows+# ---------------------------------------------------------------------------+++def test_cli_expand_resolves_mcp_row(repo_root: Path, monkeypatch):+ from click.testing import CliRunner++ from repowise.cli.commands.expand_cmd import expand_command++ collector = OmissionCollector("get_context", repo_root=repo_root)+ collector.add("dropped target pkg/a.py", {"target": "pkg/a.py", "docs": {"title": "A"}})+ response: dict = {"_meta": {}}+ collector.attach(response)+ ref = response["_meta"]["omitted"]["refs"][0]++ monkeypatch.chdir(repo_root)+ result = CliRunner().invoke(expand_command, [ref])+ assert result.exit_code == 0, result.output+ assert "dropped target pkg/a.py" in result.output+ assert '"title": "A"' in result.outputdiff --git a/tests/unit/server/mcp/test_context_skeleton.py b/tests/unit/server/mcp/test_context_skeleton.pynew file mode 100644index 000000000..ae4b431d7--- /dev/null+++ b/tests/unit/server/mcp/test_context_skeleton.py@@ -0,0 +1,73 @@+"""get_context include=["skeleton"] — the distill skeleton block."""++from __future__ import annotations++import pytest+++def _write_source(tmp_path, rel="src/auth/service.py", total_lines=100):+ """A real on-disk file matching the populated WikiSymbol bounds.++ AuthService spans 10-100, login 20-40 (see conftest). Everything else is+ filler so the body elision has something to elide.+ """+ lines = ["import os", "import sys"] + ["# preamble"] * 7 # lines 1-9+ lines.append("class AuthService:") # line 10+ for n in range(11, 20):+ lines.append(f" setup_{n} = {n}")+ lines.append(" async def login(self, username: str, password: str) -> Token:") # 20+ for n in range(21, 41):+ lines.append(f" step_{n} = {n}")+ for n in range(41, total_lines + 1):+ lines.append(f" tail_{n} = {n}")+ path = tmp_path / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")+ return path+++async def test_skeleton_block_for_file_target(setup_mcp, tmp_path, monkeypatch):+ from repowise.server.mcp_server import _state, get_context++ _write_source(tmp_path)+ monkeypatch.setattr(_state, "_repo_path", str(tmp_path))++ result = await get_context(["src/auth/service.py"], include=["skeleton"])+ sk = result["targets"]["src/auth/service.py"]["skeleton"]+ assert "error" not in sk+ assert sk["mode"] == "smart"+ assert "class AuthService:" in sk["text"]+ assert "async def login" in sk["text"]+ assert sk["tokens"] < sk["full_tokens"]+ assert "... " in sk["text"] # at least one elision marker+++async def test_skeleton_requires_file_target(setup_mcp, tmp_path, monkeypatch):+ from repowise.server.mcp_server import _state, get_context++ monkeypatch.setattr(_state, "_repo_path", str(tmp_path))+ result = await get_context(["AuthService"], include=["skeleton"])+ sk = result["targets"]["AuthService"]["skeleton"]+ assert "file target" in sk["error"]+++async def test_skeleton_missing_source_file(setup_mcp, tmp_path, monkeypatch):+ from repowise.server.mcp_server import _state, get_context++ monkeypatch.setattr(_state, "_repo_path", str(tmp_path)) # nothing on disk+ result = await get_context(["src/auth/service.py"], include=["skeleton"])+ sk = result["targets"]["src/auth/service.py"]["skeleton"]+ assert "could not be read" in sk["error"]+++async def test_skeleton_not_included_by_default(setup_mcp, tmp_path, monkeypatch):+ from repowise.server.mcp_server import _state, get_context++ _write_source(tmp_path)+ monkeypatch.setattr(_state, "_repo_path", str(tmp_path))+ result = await get_context(["src/auth/service.py"])+ assert "skeleton" not in result["targets"]["src/auth/service.py"]diff --git a/tests/unit/server/test_distill_savings.py b/tests/unit/server/test_distill_savings.pynew file mode 100644index 000000000..69bc7f777--- /dev/null+++ b/tests/unit/server/test_distill_savings.py@@ -0,0 +1,88 @@+"""Unit tests for GET /api/repos/{repo_id}/distill-savings."""++from __future__ import annotations++from pathlib import Path++from httpx import AsyncClient++from repowise.core.distill.store import OmissionStore++from .conftest import create_test_repo+++def _seed_store(repo_dir: Path) -> None:+ store = OmissionStore(repo_dir / ".repowise" / "omissions" / "omissions.db")+ store.record_saving(+ filter_name="test_output",+ source="hook",+ command="pytest",+ raw_tokens=10_000,+ distilled_tokens=1_000,+ )+ store.record_saving(+ filter_name="git_log",+ source="cli",+ command="git log",+ raw_tokens=2_000,+ distilled_tokens=200,+ )+ store.close()+++async def test_savings_endpoint_returns_rollups(client: AsyncClient, tmp_path: Path) -> None:+ repo = await create_test_repo(client, tmp_path)+ _seed_store(Path(repo["local_path"]))++ resp = await client.get(f"/api/repos/{repo['id']}/distill-savings")+ assert resp.status_code == 200+ data = resp.json()+ assert data["available"] is True+ assert data["events"] == 2+ assert data["saved_tokens"] == 10_800+ assert data["pricing_model"]+ assert data["estimated_usd_saved"] > 0+ filters = {row["group"]: row for row in data["per_filter"]}+ assert filters["test_output"]["saved_tokens"] == 9_000+ assert filters["git_log"]["events"] == 1+ assert len(data["per_day"]) == 1 # both events landed today+++async def test_savings_endpoint_no_store_is_unavailable(+ client: AsyncClient, tmp_path: Path+) -> None:+ repo = await create_test_repo(client, tmp_path)+ resp = await client.get(f"/api/repos/{repo['id']}/distill-savings")+ assert resp.status_code == 200+ data = resp.json()+ assert data["available"] is False+ assert data["events"] == 0+ assert data["saved_tokens"] == 0+++async def test_savings_endpoint_since_filter(client: AsyncClient, tmp_path: Path) -> None:+ repo = await create_test_repo(client, tmp_path)+ repo_dir = Path(repo["local_path"])+ _seed_store(repo_dir)+ # Backdate one event past the filter window.+ import sqlite3++ db = repo_dir / ".repowise" / "omissions" / "omissions.db"+ conn = sqlite3.connect(db)+ conn.execute("UPDATE savings SET created_at = created_at - 10 * 86400 WHERE filter = 'git_log'")+ conn.commit()+ conn.close()++ from datetime import date, timedelta++ cutoff = (date.today() - timedelta(days=1)).isoformat()+ resp = await client.get(f"/api/repos/{repo['id']}/distill-savings", params={"since": cutoff})+ assert resp.status_code == 200+ data = resp.json()+ assert data["events"] == 1+ assert [row["group"] for row in data["per_filter"]] == ["test_output"]+++async def test_savings_endpoint_unknown_repo_404(client: AsyncClient) -> None:+ resp = await client.get("/api/repos/nope/distill-savings")+ assert resp.status_code == 404