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(suspects): rank recent changes against a symptom, with the evidence for each (#3813)
Raghav Chamadiya6aded82449db
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 4b35af377..e74116ff2 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -162,7 +162,7 @@ A triage card for files, modules or symbols: summary, symbols with signatures an| Parameter | Type | Default | Meaning ||-----------|------|---------|---------|| `targets` | list[string] | required | File paths, module paths, `"path::Symbol"` ids, `"component:<name>"`, `"change:<id>"`, or `"package:<name>"` |-| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols`, `changes`, `provenance` |+| `include` | list[string] | none | Any of `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `references`, `metrics`, `community`, `decisions`, `skeleton`, `health`, `doc_drift`, `symbols`, `changes`, `provenance`, `suspects` || `compact` | bool | `true` | `false` adds the structure block, imports and docstrings || `repo` | string | default repo | Workspace repo alias. `"all"` is not supported (returns an error) |@@ -170,7 +170,7 @@ A triage card for files, modules or symbols: summary, symbols with signatures anA `component:<name>` target returns the component's declared context (owner, system, criticality, tags) and `facts` rolled up over its files: health, hotspots, bus factor, test reach and dead code, each with a `basis` (`measured`, `inferred` or `unavailable`). Components come from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or are derived from the index. With `include=["ownership"]` a component card adds `ownership`: declared teams with their activity over the last 90 days, a count of individual owners, and findings (`critical_no_active_owner`, `declared_owner_inactive`, `critical_bus_factor_one`, `catalog_entry_no_code`). An owner with no identity in the indexed history is `unknown` and raises no finding, so `critical_no_active_owner` does not fire when every owner is unknown; individuals match only by exact git email or forge noreply login. No other `include` applies to component targets. Health and dead code leave out files in gated languages and say how many.-A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none.+A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none. `suspects` adds one top-level block: the changes merged in the last 14 days ranked against the targets as a symptom, at most 5 rows, each with the signals that fired and their evidence, plus the candidate count and window; an order to read changes in, never a cause.A `package:<name>` target (`package:requests`, or `package:npm:lodash`) returns where that third-party package is imported: its manifest declarations, a summary, the components and declared owner teams, and up to 25 import sites with line, `mapping` (`declared` or `inferred`) and `reachability` (`reachable`, `unreachable`, `test` or `unknown`, with a basis). See [PACKAGE_USAGE.md](../reference/PACKAGE_USAGE.md).diff --git a/docs/architecture/README.md b/docs/architecture/README.mdindex 12bcadc65..fb575cc10 100644--- a/docs/architecture/README.md+++ b/docs/architecture/README.md@@ -10,7 +10,7 @@ curious; you don't need them to *use* repowise (start with| [deep-dives.md](deep-dives.md) | Algorithm-level treatment of the hard parts: dead-code detection, the decision/ADR system, search & vector-store internals, incremental updates & webhooks, the change-cascade algorithm || [code-health.md](code-health.md) | The code-health layer as a full vertical slice: pipeline, the 53 registered detectors, scoring, trends, persistence schema, and extension points || [change-risk.md](change-risk.md) | The change-risk model: features, offline calibration and why the score is reported as a size statistic, PR structural impact, and the public risk-scale inventory |-| [bug-history.md](bug-history.md) | Bug-fix history internals: fix-shape classification, the `fix_events` table, the bug-magnet rollup, and the inducing-commit (SZZ) work that was measured and not shipped |+| [bug-history.md](bug-history.md) | Bug-fix history internals: fix-shape classification, the `fix_events` table, the bug-magnet rollup, the inducing-commit (SZZ) work that was measured and not shipped, and the suspects ranking measurement || [decisions.md](decisions.md) | Decision capture internals: the source registry, evidence verification, confidence, currency, session mining and hook delivery || [security.md](security.md) | Security signals internals: per-kind matching rules, placeholder skipping, baseline keys, and the JS/TS precision checks || [test-intelligence.md](test-intelligence.md) | The inferred test tier: call and import walks, their measured precision and recall, the resolution-origin filter, and why nothing is stored |diff --git a/docs/architecture/bug-history.md b/docs/architecture/bug-history.mdindex 6809ca548..44596f3f2 100644--- a/docs/architecture/bug-history.md+++ b/docs/architecture/bug-history.md@@ -113,3 +113,44 @@ django, pandas, litellm and langfuse: 67 of 67 named the change as the cause(95% Wilson interval 94.6% to 100%; regression 47, caused by 12, broken by 8). `Fixes #N` (about 2 of7), "introduced in #N" (about 5 of 14) and a fix commit quoting a sha (0 of15) fell below 90% and are not read.++## Suspects ranking: measured++`repowise suspects` (`core/suspects/`) ranks the Change Records merged before a+symptom and names no cause, so it stays clear of the inducing-commit claim above.+It was preregistered (gate: the explicitly named change in the top 5 for at least+60% of issues pooled, at least 15 points over the better of recency and shared+files, no repo losing on MRR) with ground truth from reverts and fixes that name+the change (`This reverts commit`, `Regression in <sha>`, `Fixes: <sha>`), never+from blame. Each link class was hand-checked blind with 20% decoys (no decoy+passed); every class used scored at least 95%, and django's `Fixes #N` class+(25%) was dropped because `#N` names a Trac ticket there.++Symptom: the closed issue's text as filed; candidates: the 14 days before it;+index facts from a monthly snapshot before the issue. Trailers that name people+(`Signed-off-by`, `Co-authored-by`, `Reviewed-By`, any trailer with an email)+are excluded from the text index; the figures below are from the rerun with+them excluded, on the same items and snapshots (before: node MRR 0.354, pooled+MRR 0.450, interval +0.256 to +0.535; every hit@5 unchanged).++| Arm (hit@5 / MRR) | django (18) | node (25) | pooled (43) |+|---|---|---|---|+| Fused ranking | 0.833 / 0.582 | 0.560 / 0.358 | 0.674 / 0.452 |+| Shared files | 0.389 / 0.333 | 0.200 / 0.197 | 0.279 / 0.254 |+| Newest first | 0.111 / 0.103 | 0.160 / 0.127 | 0.140 / 0.117 |++The lift over shared files is +0.395 hit@5 (95% bootstrap interval +0.233 to++0.558). Two limits come with it: most regressions surface later than 14 days+(window misses: django 91%, node 62%), and those issues are outside the scored+set. Text match carries most of the ranking; dropping recency scored higher on+these repos, but the test repos were scored once and a change to the fusion+needs a new held-out set.++Known limits: symptom files map onto the files tracked at HEAD, so a file+renamed or deleted inside the window may name nothing; and the trace signal+matches frame function names by their last segment only, so a generic name+(`run`, `get`, `handle`) can match unrelated changes. Changing that matching+changes the ranking and needs a new freeze. Frame function names are matched against+the names in diff hunk headers only, so a change that adds a whole file gets+file-level but not function-level trace evidence.+diff --git a/docs/layers/CHANGES.md b/docs/layers/CHANGES.mdindex 5228060bb..fa08b70c4 100644--- a/docs/layers/CHANGES.md+++ b/docs/layers/CHANGES.md@@ -85,6 +85,18 @@ with `REPOWISE_SEAM_CHANGE_METADATA`. See`show` and the detail route accept a change id or any commit sha the change landed.Full flags: [CLI_REFERENCE.md](../reference/CLI_REFERENCE.md#repowise-changes).+## Suspects++`repowise suspects --symptom TEXT [--files F] [--trace FILE] [--since D] [--until D]` ranks the changes merged in the 14 days before `--until` against what was seen. Five signals rank the candidates (text match, import distance from the files the symptom names, co-change, recency, stack-trace hits) and are fused by reciprocal rank; each row lists the signals that fired and their evidence. Measured on 43 real regressions in django and node, the change a later revert or fix named was in the top 5 for 67% of issues, against 28% for ranking by shared files, and text match carries most of that ranking; the method is in [bug-history.md](../architecture/bug-history.md#suspects-ranking-measured). The same ranking is at `POST /api/repos/{id}/suspects`, in `get_context(include=["suspects"])` and as the chat tool `find_suspects`.++Most regressions surface later than 14 days after the change, so a change missing from the list is not cleared; widen `--since`. Files are mapped onto those tracked at HEAD, so a file renamed or deleted in the window may not match. The order says where to start reading, not what caused it. To confirm a suspect, let git find the first bad commit with a check that fails on the bug:++```bash+git bisect start <bad-sha> <good-sha>+git bisect run python -m pytest tests/test_invoices.py -x # exit 0 good, 1-124 bad, 125 skip+git bisect reset+```+## The record and its in-toto exportEvery surface serves one versioned JSON shape (`schema_version: 1`): id, identity,@@ -115,4 +127,4 @@ as correct when its file set matches the forge's:- Reviewers and labels stay `null` with the default source; git does not record them.- A partial clone (`--filter`) gets no Change Records: reading file stats there would fetch blobs.-- Changes before the `commit_limit` window are not read.+- Changes before the `commit_limit` window are not read, so suspects only rank changes inside it.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex e9845ab7a..c40382a85 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1624,6 +1624,16 @@ repowise changes export [--path PATH] [--since DATE] [--until DATE] [--format js---+### `repowise suspects`++Ranks the indexed changes merged in a window (default the 14 days before `--until`, which defaults to now) against a symptom: free text, files, a stack trace file. Each row lists the signals that fired (text match, import distance, co-change, recency, trace hits) with their evidence; the order is where to start reading, never a cause, and `git bisect run` confirms one. Text match carries most of the ranking, and most regressions surface later than 14 days, so a change outside the list is not cleared; widen `--since`. `--symptom` is read up to 20,000 characters and `--files` up to 50. Measured results and the bisect recipe are in [CHANGES.md](../layers/CHANGES.md#suspects).++```bash+repowise suspects [--symptom TEXT] [--files PATH]... [--trace FILE] [--since DATE] [--until DATE] [--limit N] [--path PATH] [--format table|json]+```++---+### `repowise check [REVSPEC]`Evaluates `.repowise/policies.yaml` (see [CONFIG.md](CONFIG.md#repowisepoliciesyaml)) against a change: components touched and their tags, provenance from public git markers, and, with an index, reaching tests, governing decisions crossed and bus factor. Rules that wrap a gate run `security check`, `coverage check` or `doc-drift --check` exactly as those commands run alone, and without a policy file every gate behaves as before while `check` reports nothing to evaluate. Exit 1 when a `fail` rule fires, 2 when the policy is invalid or a `fail` gate cannot be evaluated, else 0; `--sarif-file` writes SARIF 2.1.0 for code scanning or reviewdog and `--junit-file` a JUnit report from the same run.diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex cb6e758c3..b39dbabf8 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -171,12 +171,14 @@ Per target, under `targets`:| `cross_repo` | Workspace mode: `co_changes_with` partners in other repos and contract `consumers` / `providers` || `*_basis` | Beside an empty `callers`, `callees` or `used_by`: the language, how many call edges the index resolved for it, and the share that are guesses. An empty list means no resolved edge, not proof of none |-Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor count), `last_change`, `callers`, `callees`, `metrics` (PageRank, betweenness, percentiles), `community`, `skeleton`, `health`, `doc_drift`, `symbols` (every symbol of a file), `changes`, `provenance`.+Opt-in blocks: `full_doc`, `ownership` (primary owner, bus factor, contributor count), `last_change`, `callers`, `callees`, `metrics` (PageRank, betweenness, percentiles), `community`, `skeleton`, `health`, `doc_drift`, `symbols` (every symbol of a file), `changes`, `provenance`, `suspects`.**changes.** On a file target, `recent_changes` lists the newest five Change Records whose files include it, each `{id, ref, title, merged_at, category, provenance}`; `ref` is the forge's number (`#123`, `!12`) and is absent for an unnamed change, and `provenance` is `{label, coverage}` (`agent`, `human_attested` or `unknown`; absent when the change was stored without a label or attribution is off). `recent_changes_total` appears when more touched the file. The newest 500 candidate changes are read, and a change stores only its first 1,000 files, so a file past either limit can be missing from the list.**provenance.** A file's commits by source: `agent_commits`, `human_attested_commits`, `unknown_commits`, `coverage` (known over all commits), `agent_share` (agent over known commits) and a one-line `summary`. Below 30% coverage `agent_share` is null with `suppressed_reason: "coverage_below_floor"`, and the agent and human-attested counts are left out. Unknown is never counted as human. With attribution off the block is `{"unavailable": "attribution_off"}`.+**suspects.** One top-level block, not per target: `window` (`since`, `until`), `candidates` (changes merged in the 14 days before now), `texts_missing` (changes git could not read, ranked on title and files alone), `symptom_files` (the targets mapped onto files tracked at HEAD) and `suspects`, at most five rows of `{id, ref, title, merged_at, category, head_sha, files_changed, rank, signals}`, where `signals` maps each signal that fired (`text`, `graph`, `co-change`, `recency`, `trace`) to its own `rank` and `evidence`. `note` says the order is a reading order, not a cause; no row carries a score or probability.+**Change targets.** A `change:<id>` target (an id such as `pr-123`, or a commit sha the change landed) returns `type: "change"`, `id`, `ref`, `title`, `merged_at`, `category`, `shape` (`merge`, `squash`, `commit`), `head_sha`, `commit_count`, `files_changed`, `lines_added`, `lines_deleted`, `files` (paths, the first 25 with `files_total` and an omission ref past that), `linked_issues` when the messages close any, and `provenance`: `{label, agent_commits, human_attested_commits, unknown_commits, coverage}`, `{"unavailable": "attribution_off"}`, or `{"unavailable": "not_recorded"}` for a change stored while attribution was off. An unknown id returns `error` naming the id forms; a short sha that starts commits in several changes returns `error` with their ids as `candidates`.**Skeleton.** Sliced from the index's stored symbol bounds, with no parsing at query time: every signature, the import preamble, and the bodies of the top symbols ranked by centrality, hotspot and query match. Elision markers carry 1-indexed line ranges, so you can read any part back.diff --git a/packages/cli/src/repowise/cli/commands/context_cmd.py b/packages/cli/src/repowise/cli/commands/context_cmd.pyindex b211f07ea..72528a81b 100644--- a/packages/cli/src/repowise/cli/commands/context_cmd.py+++ b/packages/cli/src/repowise/cli/commands/context_cmd.py@@ -25,6 +25,7 @@ _INCLUDE_BLOCKS = ("symbols","changes","provenance",+ "suspects",)#: Card keys the projection replaces or drops. Everything else passes through.@@ -150,7 +151,9 @@ def project(payload: dict, targets: tuple[str, ...]) -> dict:}if payload.get("truncated"):out["truncated"] = True- for key in ("dropped_targets", "recovery", "dropped_symbols", "dropped_blocks", "omission_marker"):+ for key in (+ "dropped_targets", "recovery", "dropped_symbols", "dropped_blocks", "omission_marker", "suspects"+ ):# omission_marker is the only handle on what truncation banked, so a# `truncated: true` without it says content went missing and offers no# way to get it back.@@ -242,6 +245,11 @@ def _render(projected: dict) -> None:cards = projected.get("targets") or {}if not cards:console.print("[yellow]No context for those targets.[/yellow]")+ for row in (projected.get("suspects") or {}).get("suspects", []):+ console.print(+ f"suspect {row['rank']}: {escape(row.get('ref') or row['id'])} {escape(row['title'][:70])}"+ f" [dim]({', '.join(row['signals'])})[/dim]"+ )for card in cards.values():if card.get("error"):diff --git a/packages/cli/src/repowise/cli/commands/suspects_cmd.py b/packages/cli/src/repowise/cli/commands/suspects_cmd.pynew file mode 100644index 000000000..4cdc42148--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/suspects_cmd.py@@ -0,0 +1,111 @@+"""``repowise suspects`` - changes merged before a symptom, in the order to read them.++Ranks the indexed Change Records in a window (14 days before ``--until`` by+default) against what was seen: free text, files, a stack trace. Each row+lists the signals that fired and their evidence. The order is where to start+reading, never a cause; ``git bisect run`` confirms one.+"""++from __future__ import annotations++from datetime import UTC, datetime+from pathlib import Path++import click++from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async+from repowise.cli.output import emit_json, format_option+++async def _suspects(root: Path, symptom, since, until, limit: int) -> dict | None:+ from repowise.core.suspects.index import find_suspects++ async with repo_index_session(root) as opened:+ if opened is None:+ return None+ session, repo_id = opened+ return await find_suspects(+ session, repo_id, root, symptom, since=since, until=until, limit=limit+ )++[email protected]("suspects")[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")[email protected]("--symptom", default="", help="What was seen: an issue's text, an error message.")[email protected]("--files", "files", multiple=True, help="A file the symptom involves (repeatable).")+ "--trace",+ "trace",+ type=click.Path(exists=True, dir_okay=False, path_type=Path),+ default=None,+ help="A file holding a stack trace.",+)+ "--since", type=click.DateTime(), default=None, help="Merged on or after (UTC); default 14 days before --until."+)+ "--until", type=click.DateTime(), default=None, help="Merged before (UTC): when the symptom was seen; default now."+)[email protected]("--limit", default=10, show_default=True, type=click.IntRange(1, 200))+@format_option()+def suspects_command(+ repo: str | None,+ symptom: str,+ files: tuple[str, ...],+ trace: Path | None,+ since: datetime | None,+ until: datetime | None,+ limit: int,+ fmt: str,+) -> None:+ """Rank the changes merged in a window against a symptom, with the evidence for each."""+ from repowise.core.suspects import Symptom+ from repowise.core.suspects.rank import MAX_SYMPTOM_CHARS, MAX_SYMPTOM_FILES++ target = resolve_command_target(path=repo, no_workspace_flag=True)+ assert target.repo_path is not None+ root = Path(target.repo_path).resolve()+ since, until = (d.replace(tzinfo=UTC) if d else None for d in (since, until))+ trace_text = trace.read_text(encoding="utf-8", errors="replace") if trace else ""+ if not (symptom.strip() or files or trace_text.strip()):+ raise click.UsageError("Give a symptom: --symptom, --files or --trace.")+ if len(symptom) > MAX_SYMPTOM_CHARS or len(files) > MAX_SYMPTOM_FILES:+ raise click.UsageError(+ f"Keep --symptom under {MAX_SYMPTOM_CHARS} characters and --files to {MAX_SYMPTOM_FILES};"+ " only the head of a long log is read anyway."+ )+ got = run_async(+ _suspects(root, Symptom(text=symptom, files=files, trace=trace_text, at=until), since, until, limit)+ )+ if got is None:+ console.print("No index found. Run `repowise init` first.")+ raise SystemExit(1)+ if fmt == "json":+ emit_json(got)+ return+ from rich.markup import escape+ from rich.table import Table++ window = got["window"]+ console.print(+ f"{got['candidates']} change(s) merged {window['since'][:16]} to {window['until'][:16]}"+ )+ if not got["suspects"]:+ return+ table = Table("#", "Change", "Merged", "Title", "Signals (rank: evidence)")+ for row in got["suspects"]:+ signals = "\n".join(+ f"{name} {sig['rank']}: {escape('; '.join(sig['evidence'][:2]))}"+ for name, sig in row["signals"].items()+ )+ table.add_row(+ str(row["rank"]),+ escape(row.get("ref") or row["id"][:19]),+ (row["merged_at"] or "")[:10],+ escape(row["title"][:70]),+ signals,+ )+ console.print(table)+ if got.get("texts_missing"):+ console.print(f"[dim]{got['texts_missing']} change(s) git could not read: ranked on title and files.[/dim]")+ console.print(f"[dim]{got['note']}[/dim]")diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 26268d4ed..8e5af37b0 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -74,6 +74,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("components", "components_cmd:components_group"),("packages", "packages_cmd:packages_group"),("changes", "changes_cmd:changes_group"),+ ("suspects", "suspects_cmd:suspects_command"),("check", "check_cmd:check_command"),("events", "events_cmd:events_command"),("report", "report_cmd:report_group"),diff --git a/packages/server/src/repowise/server/mcp_server/_stack_trace.py b/packages/core/src/repowise/core/stack_trace.pysimilarity index 93%rename from packages/server/src/repowise/server/mcp_server/_stack_trace.pyrename to packages/core/src/repowise/core/stack_trace.pyindex 2892be0f2..c803559b7 100644--- a/packages/server/src/repowise/server/mcp_server/_stack_trace.py+++ b/packages/core/src/repowise/core/stack_trace.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport refrom collections.abc import Iterable+from functools import lru_cachefrom typing import NamedTuple@@ -158,6 +159,16 @@ def _segment_suffix(longer: str, shorter: str) -> bool:return longer == shorter or longer.endswith("/" + shorter)+def _normalize(paths: Iterable[str]) -> tuple[str, ...]:+ return tuple(sorted({p.replace("\\", "/") for p in paths}))+++@lru_cache(maxsize=4)+def _normalized(paths: frozenset[str]) -> tuple[str, ...]:+ """A frozen file set normalized once, not per call (its hash is cached too)."""+ return _normalize(paths)++def map_to_repo_paths(frames: Iterable[Frame], indexed_paths: Iterable[str]) -> list[str]:"""Repo files the frames name, in frame order, deduped.@@ -167,7 +178,11 @@ def map_to_repo_paths(frames: Iterable[Frame], indexed_paths: Iterable[str]) ->``_MAX_AMBIGUOUS`` files is dropped. Vendored frames never match on a barefile name, which would only say some installed package has that file."""- indexed = sorted({p.replace("\\", "/") for p in indexed_paths})+ indexed = (+ _normalized(indexed_paths)+ if isinstance(indexed_paths, frozenset)+ else _normalize(indexed_paths)+ )out: list[str] = []for frame in frames:if frame.vendored and "/" not in frame.path:diff --git a/packages/core/src/repowise/core/suspects/__init__.py b/packages/core/src/repowise/core/suspects/__init__.pynew file mode 100644index 000000000..67bd3b6fd--- /dev/null+++ b/packages/core/src/repowise/core/suspects/__init__.py@@ -0,0 +1,37 @@+"""Suspects: changes merged before a symptom, in the order to read them.++:mod:`.rank` holds the shapes and the fusion, :mod:`.signals` the local+signals on ``SeamRegistry("suspect-signal")``, :mod:`.git_text` what git adds+to a stored Change Record (message body, touched symbol names).+"""++from __future__ import annotations++from repowise.core.suspects import signals as _signals # noqa: F401 registers the defaults+from repowise.core.suspects.rank import (+ RRF_K,+ Candidate,+ Hit,+ PreparedSymptom,+ SignalRank,+ Suspect,+ SuspectContext,+ SuspectSignal,+ Symptom,+ rank_suspects,+ suspect_signals,+)++__all__ = [+ "RRF_K",+ "Candidate",+ "Hit",+ "PreparedSymptom",+ "SignalRank",+ "Suspect",+ "SuspectContext",+ "SuspectSignal",+ "Symptom",+ "rank_suspects",+ "suspect_signals",+]diff --git a/packages/core/src/repowise/core/suspects/git_text.py b/packages/core/src/repowise/core/suspects/git_text.pynew file mode 100644index 000000000..6c17a5f23--- /dev/null+++ b/packages/core/src/repowise/core/suspects/git_text.py@@ -0,0 +1,94 @@+"""What git says about a change beyond its stored record: message body and+the symbol names in its diff's hunk headers.++Hunk headers are git's function-context lines (``@@ -1,2 +1,3 @@ def foo(``),+so the names are the enclosing definitions of the touched code as git's+funcname rules see them. Ceiling: a change touching more than+``MAX_DIFF_FILES`` files reads no symbols, since its diff (a vendored+dependency update) can run to hundreds of megabytes.++Trailers that name people (``Signed-off-by``, ``Co-authored-by``,+``Reviewed-By`` and any trailer line carrying an email) are stripped from the+body, so no person's name reaches the text index or its evidence.+"""++from __future__ import annotations++import re+import subprocess+from collections.abc import Iterable+from pathlib import Path++MAX_DIFF_FILES = 100+_BATCH = 100+_HUNK_RE = re.compile(r"^@@ [^@]+ @@ ?(.*)$", re.MULTILINE)+_CALLABLE_RE = re.compile(r"([A-Za-z_]\w*)\s*\(")+_DEF_RE = re.compile(r"\b(?:class|struct|interface|enum|impl|trait|type|module)\s+([A-Za-z_]\w*)")+_PERSON_TRAILER_RE = re.compile(+ r"^[ \t]*(?:[A-Za-z][\w-]*-by|Cc|Author|Committer)[ \t]*:.*$"+ r"|^[ \t]*[A-Za-z][\w-]*[ \t]*:.*<[^<>\s]+@[^<>\s]+>.*$",+ re.IGNORECASE | re.MULTILINE,+)+++def strip_person_trailers(body: str) -> str:+ """*body* without trailer lines that name a person."""+ return _PERSON_TRAILER_RE.sub("", body).strip()+++def _git(repo: Path, *args: str) -> str | None:+ """Stdout, or ``None`` when git fails (one unknown sha fails the whole call)."""+ try:+ return subprocess.run(+ ["git", "-C", str(repo), *args],+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=True,+ ).stdout+ except (OSError, subprocess.CalledProcessError):+ return None+++def _log(repo: Path, args: list[str], shas: list[str]) -> str:+ """``git log`` over *shas* in batches; a failed batch is retried sha by sha."""+ parts: list[str] = []+ for i in range(0, len(shas), _BATCH):+ batch = shas[i : i + _BATCH]+ raw = _git(repo, "log", "--no-walk=unsorted", *args, *batch)+ if raw is None:+ raw = "".join(r for sha in batch if (r := _git(repo, "log", "--no-walk", *args, sha)))+ parts.append(raw)+ return "".join(parts)+++def hunk_symbols(diff: str) -> tuple[str, ...]:+ names: dict[str, None] = {}+ for context in _HUNK_RE.findall(diff):+ m = _CALLABLE_RE.search(context) or _DEF_RE.search(context)+ if m:+ names[m.group(1)] = None+ return tuple(names)+++def read_change_texts(+ repo_path: Path | str, heads: Iterable[tuple[str, int]]+) -> dict[str, tuple[str, tuple[str, ...]]]:+ """``head_sha -> (body, symbols)`` for ``(head_sha, files_changed)`` pairs.++ A sha git cannot read is left out; the caller counts what is missing.+ """+ repo = Path(repo_path)+ heads = [(s.strip(), n) for s, n in heads if s and s.strip()]+ out: dict[str, tuple[str, tuple[str, ...]]] = {}+ for rec in _log(repo, ["--format=%x00%H%n%b"], [s for s, _ in heads]).split("\x00"):+ sha, _, body = rec.partition("\n")+ if sha.strip():+ out[sha.strip()] = (strip_person_trailers(body), ())+ small = [s for s, n in heads if n <= MAX_DIFF_FILES and s in out]+ for rec in _log(repo, ["-m", "--first-parent", "-U0", "--format=%x00%H"], small).split("\x00"):+ sha, _, diff = rec.partition("\n")+ sha = sha.strip()+ if sha in out:+ out[sha] = (out[sha][0], hunk_symbols(diff))+ return out+++__all__ = ["MAX_DIFF_FILES", "hunk_symbols", "read_change_texts", "strip_person_trailers"]diff --git a/packages/core/src/repowise/core/suspects/index.py b/packages/core/src/repowise/core/suspects/index.pynew file mode 100644index 000000000..d7cc34196--- /dev/null+++ b/packages/core/src/repowise/core/suspects/index.py@@ -0,0 +1,163 @@+"""Suspects read from an index: the one entry every surface calls.++Candidates are the stored Change Records merged in ``[since, until)``; the+import graph and co-change partners come from the same index; message bodies+and touched symbol names from git. Each row is the change's list fields, its+rank, and every signal that fired with its own rank and evidence.++Symptom files are mapped onto the files tracked at HEAD, so a file renamed or+deleted inside the window may name no file and add no graph or co-change+evidence.+"""++from __future__ import annotations++import asyncio+import json+import subprocess+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any++from repowise.core.fts_query import meaningful_terms++from .git_text import read_change_texts+from .rank import Candidate, SuspectContext, Symptom, prepare, rank_suspects++#: The window the measurement used (prereg/suspects.md): 14 days before the symptom.+DEFAULT_WINDOW_DAYS = 14+DEFAULT_LIMIT = 10+#: Said on every answer: the order is a reading order, confirmation is bisect's.+NOTE = (+ "An order to read the changes in, from the evidence each row lists; not a cause "+ "and not a probability. Confirm with `git bisect run`."+)+++def _aware(value: datetime) -> datetime:+ return value if value.tzinfo else value.replace(tzinfo=UTC)+++def _tracked_files(repo_path: Path) -> frozenset[str]:+ try:+ out = subprocess.run(+ ["git", "-C", str(repo_path), "ls-files"],+ capture_output=True, text=True, encoding="utf-8", errors="replace", check=True,+ ).stdout+ except (OSError, subprocess.CalledProcessError):+ return frozenset()+ return frozenset(out.splitlines())+++async def _imports(session: Any, repo_id: str) -> dict[str, set[str]]:+ from sqlalchemy import select++ from repowise.core.persistence.models import GraphEdge++ rows = await session.execute(+ select(GraphEdge.source_node_id, GraphEdge.target_node_id).where(+ GraphEdge.repository_id == repo_id, GraphEdge.edge_type == "imports"+ )+ )+ adj: dict[str, set[str]] = {}+ for u, v in rows.all():+ if "::" in u or "::" in v or u == v:+ continue+ adj.setdefault(u, set()).add(v)+ adj.setdefault(v, set()).add(u)+ return adj+++def _row(row: Any, attribution: bool) -> dict[str, Any]:+ out: dict[str, Any] = {"id": row.change_id}+ if row.forge_ref:+ out["ref"] = row.forge_ref+ out.update(+ title=row.title,+ merged_at=_aware(row.merged_at).isoformat() if row.merged_at else None,+ category=row.category,+ head_sha=row.head_sha,+ files_changed=row.files_changed,+ )+ if attribution and row.provenance is not None:+ out["provenance"] = row.provenance+ return out+++async def find_suspects(+ session: Any,+ repo_id: str,+ repo_path: Path | str,+ symptom: Symptom,+ *,+ since: datetime | None = None,+ until: datetime | None = None,+ limit: int = DEFAULT_LIMIT,+) -> dict[str, Any]:+ """Ranked suspects for *symptom* among changes merged in ``[since, until)``.++ *until* defaults to the symptom time, else now; *since* to 14 days before it.+ """+ from repowise.core.attribution import attribution_enabled+ from repowise.core.persistence.crud import get_co_change_partners, list_changes+ from repowise.core.persistence.crud.changes import ChangeFilter++ repo_path = Path(repo_path)+ until = _aware(until or symptom.at or datetime.now(UTC))+ since = _aware(since) if since else until - timedelta(days=DEFAULT_WINDOW_DAYS)+ symptom = Symptom(symptom.text, symptom.files, symptom.trace, symptom.at or until)+ rows, _total = await list_changes(+ session, repo_id, ChangeFilter(since=since, until=until), limit=None+ )+ rows = [r for r in rows if r.merged_at is not None]+ window = {"since": since.isoformat(), "until": until.isoformat()}+ if not rows:+ return {"window": window, "candidates": 0, "suspects": [], "note": NOTE}++ files_of = {+ r.change_id: tuple(f["path"] for f in json.loads(r.files_json or "[]")) for r in rows+ }+ texts = await asyncio.to_thread(+ read_change_texts, repo_path, [(r.head_sha, r.files_changed) for r in rows]+ )+ candidates = [+ Candidate(+ r.change_id, r.title, _aware(r.merged_at), files_of[r.change_id],+ *texts.get(r.head_sha, ("", ())),+ )+ for r in rows+ ]+ repo_files = await asyncio.to_thread(_tracked_files, repo_path)+ prepared = prepare(symptom, SuspectContext(repo_files=repo_files))+ named = prepared.files+ ctx = SuspectContext(+ repo_files=repo_files,+ repo_terms=frozenset(meaningful_terms(repo_path.resolve().name.replace("-", " "))),+ imports=await _imports(session, repo_id) if named else {},+ co_change=await get_co_change_partners(session, repo_id, list(named)) if named else {},+ )+ ranked = await asyncio.to_thread(+ lambda: rank_suspects(symptom, candidates, ctx, prepared=prepared)+ )+ by_id = {r.change_id: r for r in rows}+ attribution = attribution_enabled(repo_path)+ out = []+ for s in ranked[: max(limit, 0)]:+ row = _row(by_id[s.change_id], attribution)+ row["rank"] = s.rank+ row["signals"] = {+ name: {"rank": sig.rank, "evidence": list(sig.evidence)} for name, sig in s.signals.items()+ }+ out.append(row)+ return {+ "window": window,+ "candidates": len(candidates),+ # Changes git could not read: ranked on their title and files alone.+ "texts_missing": sum(1 for r in rows if r.head_sha not in texts),+ "symptom_files": list(named),+ "suspects": out,+ "note": NOTE,+ }+++__all__ = ["DEFAULT_LIMIT", "DEFAULT_WINDOW_DAYS", "NOTE", "find_suspects"]diff --git a/packages/core/src/repowise/core/suspects/rank.py b/packages/core/src/repowise/core/suspects/rank.pynew file mode 100644index 000000000..fa20777b6--- /dev/null+++ b/packages/core/src/repowise/core/suspects/rank.py@@ -0,0 +1,211 @@+"""Changes in a window ranked against a symptom, by reciprocal rank fusion.++Candidates are the Change Records merged in the window before the symptom.+Each signal on ``SeamRegistry("suspect-signal")`` ranks the candidates it has+evidence for; the fused order is ``sum(1 / (k + rank))`` over the signals that+fired, k=60, equal weights (Cormack et al. 2009), ties newest first. A row+carries every signal that fired with its own rank and evidence. The output is+an order to read changes in, never a probability and never a cause.+"""++from __future__ import annotations++import logging+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass, field+from datetime import UTC, datetime+from typing import Protocol++from repowise.core.co_change import CoChangePartner+from repowise.core.registry.plugins import SeamRegistry, load_plugins+from repowise.core.stack_trace import Frame, map_to_repo_paths, parse_trace++RRF_K = 60+#: Input bounds: a pasted log can be huge and only its head is a symptom.+MAX_SYMPTOM_CHARS = 20_000+MAX_SYMPTOM_FILES = 50+MAX_PATH_MENTIONS = 200++_log = logging.getLogger(__name__)+++@dataclass(frozen=True)+class Symptom:+ """What was seen: free text (an issue, an error), files, a stack trace."""++ text: str = ""+ files: tuple[str, ...] = ()+ trace: str = ""+ #: When it was seen; candidates are changes merged before it.+ at: datetime | None = None+++@dataclass(frozen=True)+class Candidate:+ """One Change Record in the window, with what the signals read."""++ change_id: str+ title: str+ merged_at: datetime+ files: tuple[str, ...]+ body: str = ""+ #: Names git's hunk headers give for the code the change touched.+ symbols: tuple[str, ...] = ()+++@dataclass(frozen=True)+class SuspectContext:+ """The index facts signals read; an empty mapping means no evidence."""++ repo_files: frozenset[str] = frozenset()+ #: File to the files it imports or is imported by.+ imports: Mapping[str, Iterable[str]] = field(default_factory=dict)+ co_change: Mapping[str, Sequence[CoChangePartner]] = field(default_factory=dict)+ #: The repo's own name words: matched everywhere, so never shown as evidence.+ repo_terms: frozenset[str] = frozenset()+++@dataclass(frozen=True)+class PreparedSymptom:+ symptom: Symptom+ at: datetime+ #: Repo files the symptom names: given, in the text, or in trace frames.+ files: tuple[str, ...]+ frames: tuple[Frame, ...]+ trace_files: tuple[str, ...]+++@dataclass(frozen=True)+class Hit:+ """A signal's score for one candidate (higher ranks first) and why."""++ score: float+ evidence: tuple[str, ...] = ()+++class SuspectSignal(Protocol):+ def rank(+ self, symptom: PreparedSymptom, candidates: Sequence[Candidate], ctx: SuspectContext+ ) -> Mapping[str, Hit]:+ """Hits by ``change_id`` for the candidates this signal has evidence on."""+ ...+++@dataclass(frozen=True)+class SignalRank:+ rank: int+ evidence: tuple[str, ...]+++@dataclass(frozen=True)+class Suspect:+ change_id: str+ rank: int+ merged_at: datetime+ signals: dict[str, SignalRank]+++suspect_signals: SeamRegistry[SuspectSignal] = SeamRegistry("suspect-signal")+++def _aware(value: datetime) -> datetime:+ return value if value.tzinfo else value.replace(tzinfo=UTC)+++def _path_mentions(text: str) -> list[Frame]:+ from .signals import path_mentions++ return [Frame(p, 0, None) for p in path_mentions(text)[:MAX_PATH_MENTIONS]]+++def bounded(symptom: Symptom) -> Symptom:+ """*symptom* cut to the input bounds."""+ return Symptom(+ symptom.text[:MAX_SYMPTOM_CHARS],+ tuple(symptom.files[:MAX_SYMPTOM_FILES]),+ symptom.trace[:MAX_SYMPTOM_CHARS],+ symptom.at,+ )+++def prepare(symptom: Symptom, ctx: SuspectContext) -> PreparedSymptom:+ """The symptom read against the repo's files; reads only ``ctx.repo_files``."""+ symptom = bounded(symptom)+ frames = tuple(parse_trace(symptom.trace or symptom.text))+ trace_files = tuple(map_to_repo_paths(frames, ctx.repo_files))+ given = [f.replace("\\", "/").removeprefix("./") for f in symptom.files]+ named = map_to_repo_paths(_path_mentions(symptom.text), ctx.repo_files)+ files = tuple(dict.fromkeys([*given, *named, *trace_files]))[:MAX_SYMPTOM_FILES]+ at = _aware(symptom.at) if symptom.at else datetime.now(UTC)+ return PreparedSymptom(symptom, at, files, frames, trace_files)+++def _competition_ranks(hits: Mapping[str, Hit]) -> dict[str, int]:+ """1-based ranks, equal scores sharing the better rank (1, 1, 3)."""+ ordered = sorted(hits.items(), key=lambda kv: -kv[1].score)+ ranks: dict[str, int] = {}+ prev: float | None = None+ rank = 0+ for i, (cid, hit) in enumerate(ordered, start=1):+ if hit.score != prev:+ rank, prev = i, hit.score+ ranks[cid] = rank+ return ranks+++def rank_suspects(+ symptom: Symptom,+ candidates: Sequence[Candidate],+ ctx: SuspectContext,+ *,+ signals: Sequence[str] | None = None,+ k: int = RRF_K,+ prepared: PreparedSymptom | None = None,+) -> list[Suspect]:+ """Every candidate in fused order; *signals* restricts which signals run.++ *prepared* is :func:`prepare`'s result for this symptom and these repo+ files, when the caller already has it. A signal that raises did not fire.+ """+ load_plugins()+ names = [n for n in suspect_signals.names if signals is None or n in signals]+ prepared = prepared or prepare(symptom, ctx)+ fused: dict[str, float] = {c.change_id: 0.0 for c in candidates}+ fired: dict[str, dict[str, SignalRank]] = {c.change_id: {} for c in candidates}+ for name in names:+ try:+ found = suspect_signals.get(name).rank(prepared, candidates, ctx)+ hits = {cid: hit for cid, hit in found.items() if cid in fused}+ except Exception:+ _log.debug("suspect signal %s failed; it did not fire", name, exc_info=True)+ continue+ for cid, rank in _competition_ranks(hits).items():+ fused[cid] += 1.0 / (k + rank)+ fired[cid][name] = SignalRank(rank, hits[cid].evidence)+ order = sorted(+ candidates, key=lambda c: (-fused[c.change_id], -_aware(c.merged_at).timestamp(), c.change_id)+ )+ return [+ Suspect(c.change_id, i, _aware(c.merged_at), fired[c.change_id])+ for i, c in enumerate(order, start=1)+ ]+++__all__ = [+ "MAX_PATH_MENTIONS",+ "MAX_SYMPTOM_CHARS",+ "MAX_SYMPTOM_FILES",+ "RRF_K",+ "Candidate",+ "Hit",+ "PreparedSymptom",+ "SignalRank",+ "Suspect",+ "SuspectContext",+ "SuspectSignal",+ "Symptom",+ "bounded",+ "prepare",+ "rank_suspects",+ "suspect_signals",+]diff --git a/packages/core/src/repowise/core/suspects/signals.py b/packages/core/src/repowise/core/suspects/signals.pynew file mode 100644index 000000000..92168e12d--- /dev/null+++ b/packages/core/src/repowise/core/suspects/signals.py@@ -0,0 +1,236 @@+"""The local suspect signals, registered on ``SeamRegistry("suspect-signal")``.++- ``text``: BM25 (SQLite FTS5, in memory) of the symptom text against each+ change's title, body, file paths and touched symbol names.+- ``graph``: fewest import-graph hops from a symptom file to a changed file.+- ``co-change``: the strongest ROSE-style confidence (Zimmermann et al. 2004)+ of a rule from a symptom file to a changed file: of the symptom file's+ commits, the share that also touched it, minimum support 2.+- ``recency``: newest first.+- ``trace``: changed files and symbols that stack-trace frames name.++A plugin adds a signal with ``suspect_signals.register(name, impl)``; every+registered signal runs and fuses with equal weight.+"""++from __future__ import annotations++import re+import sqlite3+import unicodedata+from collections import Counter, deque+from collections.abc import Mapping, Sequence+from datetime import UTC++from repowise.core.co_change import MIN_CO_CHANGE_SUPPORT+from repowise.core.fts_query import PREFIX_MIN_CHARS, build_fts5_query, meaningful_terms++from .rank import Candidate, Hit, PreparedSymptom, SuspectContext, suspect_signals++_CAMEL = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")+_SPLIT = re.compile(r"[/\\._\-\s]+")+#: A path-like token with an extension; URLs and absolute paths keep their tail.+_PATH_TOKEN = re.compile(r"[\w@~.\-/\\]*[\w\-]\.[A-Za-z][\w]{0,7}\b")+_MAX_EVIDENCE = 5+#: Words that match nearly every change, so they say nothing as evidence.+_EVIDENCE_STOPWORDS = frozenset(+ {+ "after", "again", "already", "always", "any", "because", "before", "between",+ "both", "cannot", "come", "could", "does", "done", "during", "even", "every",+ "first", "from", "get", "gets", "getting", "got", "here", "into", "like", "make",+ "makes", "many", "more", "most", "much", "need", "needs", "new", "next", "now",+ "off", "once", "one", "only", "other", "out", "over", "same", "see", "seems",+ "shows", "show", "since", "some", "still", "such", "sure", "take", "than", "then",+ "there", "these", "thing", "things", "through", "under", "until", "use", "used",+ "uses", "using", "very", "want", "way", "well", "what", "when", "where", "which",+ "while", "will", "with", "within", "without", "work", "works", "would", "yet"+ }+)+++def path_mentions(text: str) -> list[str]:+ """Path-like tokens in free text, in order, deduped."""+ return list(dict.fromkeys(m.group(0).lstrip("/\\") for m in _PATH_TOKEN.finditer(text)))+++def _words(text: str) -> str:+ """Path and identifier parts as separate words, the originals kept."""+ parts = _SPLIT.split(text)+ return " ".join([text, *parts, *(_CAMEL.sub(" ", p) for p in parts if _CAMEL.search(p))])+++def _document(c: Candidate) -> str:+ return "\n".join([c.title, c.body, *(_words(f) for f in c.files), *(_words(s) for s in c.symbols)])+++class TextSignal:+ """BM25 over the candidates of one query; FTS5 is in the stdlib's SQLite."""++ def rank(+ self, symptom: PreparedSymptom, candidates: Sequence[Candidate], ctx: SuspectContext+ ) -> Mapping[str, Hit]:+ text = symptom.symptom.text+ terms = meaningful_terms(text)+ if not terms or not candidates:+ return {}+ db = sqlite3.connect(":memory:")+ try:+ db.execute("CREATE VIRTUAL TABLE doc USING fts5(cid UNINDEXED, body)")+ db.executemany(+ "INSERT INTO doc(cid, body) VALUES (?, ?)",+ [(c.change_id, _document(c)) for c in candidates],+ )+ rows = db.execute(+ "SELECT cid, bm25(doc), body FROM doc WHERE doc MATCH ?", (build_fts5_query(text),)+ ).fetchall()+ except sqlite3.OperationalError:+ return {}+ finally:+ db.close()+ wanted = list(dict.fromkeys(terms))+ matched = {cid: [t for t in wanted if _fts_matches(t, _fts_words(body))] for cid, _, body in rows}+ # Evidence only (the score is BM25's): the rarest matched terms first,+ # without the repo's own name or filler words that match every row.+ df = Counter(t for ts in matched.values() for t in ts)+ quiet = _EVIDENCE_STOPWORDS | ctx.repo_terms+ out: dict[str, Hit] = {}+ for cid, score, _body in rows:+ ranked = sorted(matched[cid], key=lambda t: (df[t], wanted.index(t)))+ shown = [t for t in ranked if t not in quiet][:_MAX_EVIDENCE] or ranked[:1]+ out[cid] = Hit(-score, tuple(f"term {t}" for t in shown))+ return out+++_FTS_TOKEN = re.compile(r"[^\W_]+")+++def _fold(text: str) -> str:+ """Lowercase without diacritics, as FTS5's unicode61 tokenizer reads text."""+ return "".join(c for c in unicodedata.normalize("NFKD", text.lower()) if not unicodedata.combining(c))+++def _fts_words(body: str) -> tuple[list[str], set[str]]:+ words = _FTS_TOKEN.findall(_fold(body))+ return words, set(words)+++def _fts_matches(term: str, words: tuple[list[str], set[str]]) -> bool:+ """Whether FTS5 matched *term* here: its tokens as a phrase, the last one by+ prefix when the term is long enough (:func:`~repowise.core.fts_query.match_term`)."""+ parts = _FTS_TOKEN.findall(_fold(term))+ seq, vocab = words+ prefix = len(term) >= PREFIX_MIN_CHARS+ if len(parts) == 1:+ return parts[0] in vocab or (prefix and any(w.startswith(parts[0]) for w in vocab))+ n = len(parts)+ for i in range(len(seq) - n + 1):+ if seq[i : i + n - 1] == parts[:-1] and (+ seq[i + n - 1] == parts[-1] or (prefix and seq[i + n - 1].startswith(parts[-1]))+ ):+ return True+ return False+++def _hops(start: Sequence[str], imports: Mapping[str, object]) -> dict[str, tuple[int, str]]:+ """Fewest undirected import hops to each reachable file, and from which start."""+ seen: dict[str, tuple[int, str]] = {s: (0, s) for s in start}+ queue = deque(start)+ while queue:+ node = queue.popleft()+ dist, origin = seen[node]+ for nxt in imports.get(node, ()): # type: ignore[union-attr]+ if nxt not in seen:+ seen[nxt] = (dist + 1, origin)+ queue.append(nxt)+ return seen+++class GraphSignal:+ def rank(+ self, symptom: PreparedSymptom, candidates: Sequence[Candidate], ctx: SuspectContext+ ) -> Mapping[str, Hit]:+ if not symptom.files or not ctx.imports:+ return {}+ reach = _hops(symptom.files, ctx.imports)+ out: dict[str, Hit] = {}+ for c in candidates:+ best = min(((reach[f][0], f, reach[f][1]) for f in c.files if f in reach), default=None)+ if best is not None:+ hops, changed, origin = best+ why = (+ f"changes {changed}, a symptom file"+ if hops == 0+ else f"{hops} import hop{'s' if hops != 1 else ''} from {origin} to {changed}"+ )+ out[c.change_id] = Hit(-hops, (why,))+ return out+++class CoChangeSignal:+ def rank(+ self, symptom: PreparedSymptom, candidates: Sequence[Candidate], ctx: SuspectContext+ ) -> Mapping[str, Hit]:+ rules: dict[str, tuple[float, str, int, int]] = {}+ for s in symptom.files:+ for p in ctx.co_change.get(s, ()):+ if p.support < MIN_CO_CHANGE_SUPPORT or p.self_commits <= 0:+ continue+ conf = min(p.support / p.self_commits, 1.0)+ if conf > rules.get(p.file_path, (0.0,))[0]:+ rules[p.file_path] = (conf, s, p.support, p.self_commits)+ out: dict[str, Hit] = {}+ for c in candidates:+ best = max((rules[f] + (f,) for f in c.files if f in rules), default=None)+ if best is not None:+ conf, s, support, total, f = best+ out[c.change_id] = Hit(+ conf, (f"{f} changed in {support} of {total} commits to {s}",)+ )+ return out+++class RecencySignal:+ def rank(+ self, symptom: PreparedSymptom, candidates: Sequence[Candidate], ctx: SuspectContext+ ) -> Mapping[str, Hit]:+ out: dict[str, Hit] = {}+ for c in candidates:+ at = c.merged_at if c.merged_at.tzinfo else c.merged_at.replace(tzinfo=UTC)+ hours = max((symptom.at - at).total_seconds() / 3600, 0.0)+ out[c.change_id] = Hit(at.timestamp(), (f"merged {hours:.0f} h before the symptom",))+ return out+++class TraceSignal:+ def rank(+ self, symptom: PreparedSymptom, candidates: Sequence[Candidate], ctx: SuspectContext+ ) -> Mapping[str, Hit]:+ if not symptom.frames:+ return {}+ trace_files = set(symptom.trace_files)+ functions = {f.function.rsplit(".", 1)[-1] for f in symptom.frames if f.function}+ out: dict[str, Hit] = {}+ for c in candidates:+ files = [f for f in c.files if f in trace_files]+ symbols = sorted(functions.intersection(c.symbols))+ if files or symbols:+ evidence = [f"frame file {f}" for f in files] + [f"frame function {s}" for s in symbols]+ out[c.change_id] = Hit(len(files) + len(symbols), tuple(evidence[:_MAX_EVIDENCE]))+ return out+++suspect_signals.register("text", TextSignal())+suspect_signals.register("graph", GraphSignal())+suspect_signals.register("co-change", CoChangeSignal())+suspect_signals.register("recency", RecencySignal())+suspect_signals.register("trace", TraceSignal())+++__all__ = [+ "CoChangeSignal",+ "GraphSignal",+ "RecencySignal",+ "TextSignal",+ "TraceSignal",+ "path_mentions",+]diff --git a/packages/server/src/repowise/server/chat_session.py b/packages/server/src/repowise/server/chat_session.pyindex b5a6fde87..f6c6e3dfb 100644--- a/packages/server/src/repowise/server/chat_session.py+++ b/packages/server/src/repowise/server/chat_session.py@@ -11,7 +11,8 @@ events as SSE, and an in-process caller uses the class directly.The tools a model is shown, and the only ones it can run, are the backend'scatalog for the principal narrowed by the policy's allowlist and safetyceiling, plus the chat-only ``show_view`` tool, which builds tables and-charts from this turn's results (:mod:`repowise.server.chat_views`).+charts from this turn's results (:mod:`repowise.server.chat_views`), and+the chat-only ``find_suspects`` (:mod:`repowise.server.chat_suspects`).Everything outside the loop goes through the seams in:mod:`repowise.server.chat_seams`."""@@ -63,6 +64,12 @@ from repowise.server.chat_seams import (from repowise.server.chat_store import SqlConversationStorefrom repowise.server.chat_suggestions import conversation_title, follow_up_suggestions, tool_namesfrom repowise.server.chat_summaries import _build_tool_summary+from repowise.server.chat_suspects import (+ SCOPE_TOOL,+ SUSPECTS_TOOL,+ find_suspects_schema,+ run_find_suspects,+)from repowise.server.chat_tools import ChatToolContract, LocalToolBackend, tool_schemasfrom repowise.server.chat_views import SHOW_VIEW_TOOL, TurnViews, show_view_schemafrom repowise.server.schemas.evidence import CardRef@@ -322,6 +329,7 @@ class _Turn:tokens_before: int,is_cancelled: IsCancelled,shows_views: bool = False,+ finds_suspects: bool = False,question: str = "",prior_calls: list[dict[str, Any]] | None = None,) -> None:@@ -329,6 +337,7 @@ class _Turn:self.tools = toolsself.catalog = {tool.entry.name: tool for tool in catalog}self.shows_views = shows_views+ self.finds_suspects = finds_suspectsself.views = TurnViews()self.policy = policyself.base = base@@ -364,6 +373,9 @@ class _Turn:"""if name == SHOW_VIEW_TOOL and self.shows_views:return self.views.show(arguments)+ if name == SUSPECTS_TOOL and self.finds_suspects:+ result = await run_find_suspects(arguments, getattr(self.tools, "repo_alias", None))+ return self.views.record(name, arguments, result, evidence_basis="inferred")tool = self.catalog.get(name)if tool is None:return {@@ -879,9 +891,18 @@ class ChatSession:# show_view is chat-only and read-only: never an MCP tool, offered# whenever there is a tool whose result it could be built from.shows_views = bool(catalog) and self.policy.admits_name(SHOW_VIEW_TOOL, "read_only")+ # find_suspects is chat-only too: it reads the index in process, so it+ # needs the local backend and follows get_context's admission.+ finds_suspects = (+ isinstance(self.tools, LocalToolBackend)+ and any(tool.entry.name == SCOPE_TOOL for tool in catalog)+ and self.policy.admits_name(SUSPECTS_TOOL, "read_only")+ )schemas = tool_schemas(catalog)if shows_views:schemas.append(show_view_schema([tool.entry.artifact_type for tool in catalog]))+ if finds_suspects:+ schemas.append(find_suspects_schema())turn = _Turn(provider=self.provider,tools=self.tools,@@ -893,6 +914,7 @@ class ChatSession:tokens_before=conversation.tokens_used,is_cancelled=is_cancelled,shows_views=shows_views,+ finds_suspects=finds_suspects,question=message,prior_calls=[calldiff --git a/packages/server/src/repowise/server/chat_suspects.py b/packages/server/src/repowise/server/chat_suspects.pynew file mode 100644index 000000000..d25168bb0--- /dev/null+++ b/packages/server/src/repowise/server/chat_suspects.py@@ -0,0 +1,88 @@+"""The chat-only ``find_suspects`` tool: changes before a symptom, in reading order.++MCP has no free-text symptom input (get_context's ``include=["suspects"]``+takes its targets as the symptom), so chat gets this tool for an incident+described in words, the input the suspects measurement scored. It reads the+same index through the in-process tool state, so it is offered only on the+local backend, and only when the session may run ``get_context``, which reads+the same data under the same scope.+"""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any++SUSPECTS_TOOL = "find_suspects"+#: The tool whose admission this one follows.+SCOPE_TOOL = "get_context"+++def find_suspects_schema() -> dict[str, Any]:+ return {+ "type": "function",+ "function": {+ "name": SUSPECTS_TOOL,+ "description": (+ "Rank the changes merged in a window (default the 14 days before `until`) "+ "against a symptom: an issue's text, an error, files, a stack trace. Each row "+ "lists the signals that fired and their evidence. It is an order to read "+ "changes in, never a cause or a probability; say so, and suggest "+ "`git bisect run` to confirm one."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "symptom": {"type": "string", "description": "What was seen, in words."},+ "files": {"type": "array", "items": {"type": "string"}},+ "trace": {"type": "string", "description": "A pasted stack trace."},+ "since": {"type": "string", "description": "ISO 8601 window start."},+ "until": {"type": "string", "description": "ISO 8601: when it was seen."},+ },+ "required": ["symptom"],+ },+ },+ }+++def _when(value: Any) -> datetime | None:+ if not isinstance(value, str) or not value:+ return None+ moment = datetime.fromisoformat(value.replace("Z", "+00:00"))+ return moment if moment.tzinfo else moment.replace(tzinfo=UTC)+++async def run_find_suspects(arguments: dict[str, Any], repo: str | None) -> dict[str, Any]:+ from repowise.core.persistence.database import get_session+ from repowise.core.suspects import Symptom+ from repowise.core.suspects.index import find_suspects+ from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context++ try:+ since, until = _when(arguments.get("since")), _when(arguments.get("until"))+ except ValueError:+ return {"error": "since and until must be ISO 8601 times", "error_code": "bad_arguments"}+ files = arguments.get("files") or []+ if not isinstance(files, list):+ files = []+ # Cut to the core's bounds (``bounded``): a pasted log keeps its head.+ symptom = Symptom(+ text=str(arguments.get("symptom") or ""),+ files=tuple(str(f) for f in files if isinstance(f, str)),+ trace=str(arguments.get("trace") or ""),+ at=until,+ )+ if not (symptom.text.strip() or symptom.files or symptom.trace.strip()):+ return {"error": "Give a symptom, files or a trace", "error_code": "bad_arguments"}+ try:+ ctx = await _resolve_repo_context(repo)+ async with get_session(ctx.session_factory) as session:+ repository = await _get_repo(session)+ return await find_suspects(+ session, repository.id, repository.local_path, symptom, since=since, until=until+ )+ except Exception as exc: # a tool failure is the model's to read, not the turn's end+ return {"error": f"{type(exc).__name__}: {exc}", "error_code": "tool_failed"}+++__all__ = ["SCOPE_TOOL", "SUSPECTS_TOOL", "find_suspects_schema", "run_find_suspects"]diff --git a/packages/server/src/repowise/server/mcp_server/_changes.py b/packages/server/src/repowise/server/mcp_server/_changes.pyindex b407e73d2..463d228a9 100644--- a/packages/server/src/repowise/server/mcp_server/_changes.py+++ b/packages/server/src/repowise/server/mcp_server/_changes.py@@ -1,8 +1,9 @@"""Change Records on the MCP surface.``change:<id>`` cards for get_context, recent changes per file behind-``include=["changes"]`` (get_context, get_risk) and the get_overview change-summary. All of it is opt-in.+``include=["changes"]`` (get_context, get_risk), ranked suspects behind+get_context's ``include=["suspects"]`` and the get_overview change summary.+All of it is opt-in.Provenance follows :mod:`repowise.core.attribution`: three-state, coveragebeside every share, unknown never counted as human, and nothing about AI while@@ -292,3 +293,30 @@ async def overview_changes(session: Any, repository: Any) -> dict[str, Any]:share = attribution_share(labels[AGENT], labels[HUMAN_ATTESTED], len(rows))block["provenance"] = _share_block(share, unit="changes")return block+++# -- get_context(include=["suspects"]) -----------------------------------------++#: Suspects listed; ``candidates`` counts the whole window.+SUSPECTS_CAP = 5+++async def suspects_block(session: Any, repository: Any, targets: list[str]) -> dict[str, Any]:+ """Changes merged in the last 14 days ranked against the targets as a symptom.++ File and symbol targets name the symptom's files; every target's text+ feeds the text signal. A ``change:`` or ``component:`` target is not part+ of the symptom.+ """+ from repowise.core.suspects import Symptom+ from repowise.core.suspects.index import find_suspects++ symptom_targets = [t for t in targets if not is_change_target(t) and not t.startswith("component:")]+ files = tuple(dict.fromkeys(t.split("::", 1)[0] for t in symptom_targets))+ return await find_suspects(+ session,+ repository.id,+ repository.local_path,+ Symptom(text=" ".join(symptom_targets), files=files),+ limit=SUSPECTS_CAP,+ )diff --git a/packages/server/src/repowise/server/mcp_server/_query_shape.py b/packages/server/src/repowise/server/mcp_server/_query_shape.pyindex 6491cd50c..cef008817 100644--- a/packages/server/src/repowise/server/mcp_server/_query_shape.py+++ b/packages/server/src/repowise/server/mcp_server/_query_shape.py@@ -12,7 +12,7 @@ import refrom collections.abc import Container, Sequencefrom functools import cache-from repowise.server.mcp_server._stack_trace import parse_trace+from repowise.core.stack_trace import parse_trace@cachediff --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 6b353c745..0cfb7ecc9 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@@ -35,6 +35,8 @@ Optional ``include`` parameter widens the response:- include=["doc_drift"] → documents that name this file, and their drift- include=["symbols"] → every symbol in a file card, not the ranked top 15- include=["changes"] → recent Change Records touching a file target+ - include=["suspects"] → changes merged in the last 14 days ranked against the+ targets as a symptom, each with the signals that fired- include=["provenance"]→ a file's commits by source (agent, human-attested,unknown) with coverage and the honest agent share@@ -60,7 +62,7 @@ from repowise.core.registry import ToolRecipefrom repowise.core.registry import mcp_tool_registry as mcpfrom repowise.server.mcp_server import _statefrom repowise.server.mcp_server._budget import OmissionCollector-from repowise.server.mcp_server._changes import change_cards, is_change_target+from repowise.server.mcp_server._changes import change_cards, is_change_target, suspects_blockfrom repowise.server.mcp_server._components import component_cards, is_component_targetfrom repowise.server.mcp_server._episodes import enrich_episode_counts as _enrich_episodesfrom repowise.server.mcp_server._helpers import (@@ -109,6 +111,7 @@ _INCLUDE_BLOCKS = frozenset("symbols","changes","provenance",+ "suspects",})@@ -157,8 +160,9 @@ async def get_context(include: opt-in blocks: full_doc | ownership | last_change | callers| callees | references | metrics | community | decisions | skeleton| skeleton+ | health | doc_drift (docs naming this file)- | symbols (all, not the top 15) | changes | provenance.- compact: default True; False adds structure+imports+docstrings.+ | symbols (all, not the top 15) | changes | provenance+ | suspects.+ compact: False adds structure+imports+docstrings.repo: usually omitted."""if repo == "all":@@ -260,6 +264,9 @@ async def get_context(exclude_spec=exclude_spec,collector=collector,)+ suspects = (+ await suspects_block(session, repository, targets) if "suspects" in include_set else None+ )results: list[dict[str, Any]] = []for t, r in zip(targets, raw_results, strict=True):@@ -292,6 +299,8 @@ async def get_context(targets=targets,),}+ if suspects is not None:+ response["suspects"] = suspects# A "raw" skeleton is the file's own source served untouched; the# signatures and smart modes elide bodies, so they are not whole files.whole_files = sum(diff --git a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.pyindex c40c42126..32298ce66 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py@@ -27,6 +27,11 @@ from sqlalchemy import case, func, or_, selectfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphNode, Page, WikiSymbol+from repowise.core.stack_trace import (+ frame_basenames,+ map_to_repo_paths,+ parse_trace,+)from repowise.core.test_paths import is_test_path, is_test_related_pathfrom repowise.server.mcp_server._graph_files import per_indexfrom repowise.server.mcp_server._helpers import (@@ -49,11 +54,6 @@ from repowise.server.mcp_server._retrieval_rank import (path_word_counts,path_words,)-from repowise.server.mcp_server._stack_trace import (- frame_basenames,- map_to_repo_paths,- parse_trace,-)from repowise.server.mcp_server._symbol_lookup import symbol_rank_key# Candidate ceiling: scoring/sorting happens in Python, so the SQL pre-filterdiff --git a/packages/server/src/repowise/server/routers/changes.py b/packages/server/src/repowise/server/routers/changes.pyindex 4358c75d7..8c45d1ccf 100644--- a/packages/server/src/repowise/server/routers/changes.py+++ b/packages/server/src/repowise/server/routers/changes.py@@ -1,8 +1,10 @@-"""/api/repos/{repo_id}/changes — merged changes reconstructed from git."""+"""/api/repos/{repo_id}/changes — merged changes reconstructed from git, and+``/suspects``, the changes in a window ranked against a symptom."""from __future__ import annotationsimport asyncio+from datetime import UTC, datetimefrom typing import Anyfrom fastapi import APIRouter, Depends, HTTPException, Query, Request@@ -25,12 +27,16 @@ from repowise.core.changes.evidence import ChangeEvidencefrom repowise.core.changes.record import change_recordfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_session+from repowise.core.suspects import Symptom+from repowise.core.suspects.index import find_suspectsfrom repowise.server.deps import get_db_session, resolve_request_session_factory, verify_api_keyfrom repowise.server.schemas.changes import (ChangeEvidenceSummary,ChangeListResponse,ChangeRecord,ChecklistsBuilt,+ SuspectsRequest,+ SuspectsResponse,summary_from_record,)@@ -188,3 +194,41 @@ async def _outcomes_and_keep(async with get_session(factory) as session:merged = await keep_outcomes(session, repo_id, change_id, item)return merged or with_item(kept, item)+++def _when(value: str | None, field: str) -> datetime | None:+ if not value:+ return None+ try:+ moment = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ raise HTTPException(status_code=422, detail=f"{field} is not an ISO 8601 time") from None+ return moment if moment.tzinfo else moment.replace(tzinfo=UTC)++[email protected]("/{repo_id}/suspects", response_model=SuspectsResponse)+async def rank_suspects(+ repo_id: str,+ body: SuspectsRequest,+ session: AsyncSession = Depends(get_db_session),+) -> SuspectsResponse:+ """The changes merged in a window, ranked against a symptom, with each row's evidence.++ An order to read changes in, never a cause or a probability.+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ if not (body.symptom.strip() or body.files or body.trace.strip()):+ raise HTTPException(status_code=422, detail="Give a symptom, files or a trace")+ until = _when(body.until, "until")+ got = await find_suspects(+ session,+ repo_id,+ repo.local_path,+ Symptom(text=body.symptom, files=tuple(body.files), trace=body.trace, at=until),+ since=_when(body.since, "since"),+ until=until,+ limit=body.limit,+ )+ return SuspectsResponse(**got)diff --git a/packages/server/src/repowise/server/schemas/changes.py b/packages/server/src/repowise/server/schemas/changes.pyindex f10d3965b..7eb16b305 100644--- a/packages/server/src/repowise/server/schemas/changes.py+++ b/packages/server/src/repowise/server/schemas/changes.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom typing import Any, Literal-from pydantic import BaseModel, model_serializer+from pydantic import BaseModel, Field, model_serializerclass ChangeIdentity(BaseModel):@@ -155,3 +155,46 @@ def summary_from_record(record: dict) -> ChangeListItem:**{k: v for k, v in record.items() if k in ChangeSummary.model_fields},commit_count=len(record["commits"]),)+++class SuspectsRequest(BaseModel):+ """A symptom and the window to rank the changes merged in."""++ symptom: str = Field("", max_length=20_000)+ files: list[str] = Field([], max_length=50)+ trace: str = Field("", max_length=20_000)+ #: ISO 8601; default 14 days before ``until``.+ since: str | None = None+ #: ISO 8601, when the symptom was seen; default now.+ until: str | None = None+ limit: int = Field(10, ge=1, le=200)+++class SuspectSignal(BaseModel):+ rank: int+ evidence: list[str]+++class Suspect(BaseModel):+ """One change in reading order; ``signals`` holds each signal that fired."""++ id: str+ ref: str | None = None+ title: str+ merged_at: str | None = None+ category: str+ head_sha: str+ files_changed: int+ provenance: str | None = None+ rank: int+ signals: dict[str, SuspectSignal]+++class SuspectsResponse(BaseModel):+ window: dict[str, str]+ candidates: int+ #: Changes git could not read; they are ranked on title and files alone.+ texts_missing: int = 0+ symptom_files: list[str] = []+ suspects: list[Suspect]+ note: strdiff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 772e07462..61c2c4e1e 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -3587,6 +3587,44 @@ export interface SetApiKeyRequest {repo_id?: string | null;}+/** One change in reading order; ``signals`` holds each signal that fired. */+export interface Suspect {+ id: string;+ ref?: string | null;+ title: string;+ merged_at?: string | null;+ category: string;+ head_sha: string;+ files_changed: number;+ provenance?: string | null;+ rank: number;+ signals: Record<string, SuspectSignal>;+}++export interface SuspectSignal {+ rank: number;+ evidence: string[];+}++/** A symptom and the window to rank the changes merged in. */+export interface SuspectsRequest {+ symptom?: string;+ files?: string[];+ trace?: string;+ since?: string | null;+ until?: string | null;+ limit?: number;+}++export interface SuspectsResponse {+ window: Record<string, string>;+ candidates: number;+ texts_missing?: number;+ symptom_files?: string[];+ suspects: Suspect[];+ note: string;+}+/*** Transparent breakdown of the composite importance score so the UI can* explain *why* a symbol ranks where it does. All fields are normalized todiff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex 116533b32..92cb4b338 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -41,7 +41,7 @@ _EXPECTED_NAMES = frozenset("impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "packages", "plugins","publish", "reindex", "report","restyle",- "risk", "saved", "savings", "search", "security", "serve", "status", "symbol",+ "risk", "saved", "savings", "search", "security", "serve", "status", "suspects", "symbol","telemetry", "uninstall", "update", "watch", "whats-new", "whoami", "why","wiki-styles", "workspace",}diff --git a/tests/unit/cli/test_suspects_cmd.py b/tests/unit/cli/test_suspects_cmd.pynew file mode 100644index 000000000..94f7ef95a--- /dev/null+++ b/tests/unit/cli/test_suspects_cmd.py@@ -0,0 +1,108 @@+"""`repowise suspects` against a real git repo and local index."""++from __future__ import annotations++import json+import subprocess+from datetime import UTC, datetime+from pathlib import Path++from click.testing import CliRunner++from repowise.cli.commands.suspects_cmd import suspects_command+from repowise.cli.helpers import run_async+++def _git(root: Path, *args: str) -> str:+ return subprocess.run(+ ["git", "-C", str(root), *args], capture_output=True, text=True, check=True,+ env={"GIT_AUTHOR_NAME": "a", "GIT_AUTHOR_EMAIL": "a@x", "GIT_COMMITTER_NAME": "a",+ "GIT_COMMITTER_EMAIL": "a@x", "PATH": __import__("os").environ["PATH"]},+ ).stdout.strip()+++def _commit(root: Path, path: str, body: str, message: str) -> str:+ (root / path).parent.mkdir(parents=True, exist_ok=True)+ (root / path).write_text(body, encoding="utf-8")+ _git(root, "add", path)+ _git(root, "commit", "-q", "-m", message)+ return _git(root, "rev-parse", "HEAD")+++async def _store(root: Path, changes: list[tuple[str, str, str, datetime]]) -> None:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )+ from repowise.core.persistence.crud import upsert_changes++ (root / ".repowise").mkdir(exist_ok=True)+ engine = create_engine(f"sqlite+aiosqlite:///{(root / '.repowise' / 'wiki.db').as_posix()}")+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(root))+ await upsert_changes(+ session,+ repo.id,+ [+ {+ "change_id": f"commit-{sha}",+ "identity_kind": "commit",+ "identity_value": sha,+ "shape": "commit",+ "forge": "generic",+ "title": title,+ "merged_at": at,+ "head_sha": sha,+ "commit_shas_json": json.dumps([sha]),+ "files_json": json.dumps([{"path": path, "added": 1, "deleted": 0}]),+ "files_changed": 1,+ "lines_added": 1,+ "lines_deleted": 0,+ "category": "feature",+ "metadata_source": "git",+ }+ for sha, title, path, at in changes+ ],+ )+ finally:+ await engine.dispose()+++def test_ranks_the_change_the_symptom_names(tmp_path):+ root = tmp_path / "repo"+ root.mkdir()+ _git(root, "init", "-q")+ a = _commit(root, "billing/invoice.py", "def total(lines):\n return 0\n", "Round invoice totals")+ b = _commit(root, "docs/readme.md", "hello\n", "Reword the readme")+ run_async(+ _store(+ root,+ [+ (a, "Round invoice totals", "billing/invoice.py", datetime(2026, 3, 1, tzinfo=UTC)),+ (b, "Reword the readme", "docs/readme.md", datetime(2026, 3, 2, tzinfo=UTC)),+ ],+ )+ )+ out = CliRunner().invoke(+ suspects_command,+ ["--path", str(root), "--symptom", "invoice totals are off in billing/invoice.py",+ "--until", "2026-03-03", "--format", "json"],+ )+ assert out.exit_code == 0, out.output+ data = json.loads(out.output)+ assert data["candidates"] == 2+ top = data["suspects"][0]+ assert top["id"] == f"commit-{a}" and top["rank"] == 1+ assert {"text", "recency"} <= set(top["signals"])+ assert data["symptom_files"] == ["billing/invoice.py"]+ assert "not a cause" in data["note"]+++def test_needs_a_symptom(tmp_path):+ out = CliRunner().invoke(suspects_command, ["--path", str(tmp_path)])+ assert out.exit_code != 0 and "Give a symptom" in out.outputdiff --git a/tests/unit/server/mcp/test_changes_mcp.py b/tests/unit/server/mcp/test_changes_mcp.pyindex 120a19a6c..fcfbd11df 100644--- a/tests/unit/server/mcp/test_changes_mcp.py+++ b/tests/unit/server/mcp/test_changes_mcp.py@@ -187,6 +187,26 @@ async def test_recent_changes_are_capped_with_their_total(setup_mcp, session):assert card["recent_changes_total"] == 8+async def test_suspects_rank_recent_changes_against_the_targets(setup_mcp, session):+ import time_machine++ from repowise.server.mcp_server import get_context++ await _seed(session)+ with time_machine.travel(datetime(2026, 3, 16, tzinfo=UTC), tick=False):+ plain = await get_context(targets=["src/db/models.py"])+ result = await get_context(targets=["src/db/models.py"], include=["suspects"])+ assert "suspects" not in plain+ block = result["suspects"]+ assert block["window"]["since"].startswith("2026-03-02")+ assert block["candidates"] == 3 # pr-2, pr-3, pr-4; pr-1 is older than 14 days+ top = block["suspects"][0]+ assert (top["id"], top["rank"]) == ("pr-2", 1)+ assert "text" in top["signals"] and "recency" in top["signals"]+ assert "not a cause" in block["note"]++@pytest.mark.asyncioasync def test_file_provenance_carries_coverage_and_withholds_below_the_floor(setup_mcp, session, tmp_pathdiff --git a/tests/unit/server/mcp/test_stack_trace.py b/tests/unit/server/mcp/test_stack_trace.pyindex ea6489ccb..57fd78df7 100644--- a/tests/unit/server/mcp/test_stack_trace.py+++ b/tests/unit/server/mcp/test_stack_trace.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport pytest+from repowise.core.stack_trace import Frame, map_to_repo_paths, parse_tracefrom repowise.server.mcp_server._query_shape import is_issue_shaped-from repowise.server.mcp_server._stack_trace import Frame, map_to_repo_paths, parse_tracePYTHON = """\Traceback (most recent call last):diff --git a/tests/unit/server/test_changes_routes.py b/tests/unit/server/test_changes_routes.pyindex cafc50b5e..750f6c8d7 100644--- a/tests/unit/server/test_changes_routes.py+++ b/tests/unit/server/test_changes_routes.py@@ -380,3 +380,23 @@ async def test_a_refresh_is_not_swallowed_by_an_outcomes_read_in_flight(await asyncio.sleep(0.01)done = (await client.get(base, params={"evidence": "true"})).json()assert [i["kind"] for i in done["evidence"]["items"]] == ["health_delta", "outcomes"]+++async def test_suspects_rank_the_window_with_evidence(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app, repo["id"])+ url = f"/api/repos/{repo['id']}/suspects"++ got = (+ await client.post(+ url, json={"symptom": "crash", "since": "2026-01-01T00:00:00Z", "until": "2026-01-10T00:00:00Z"}+ )+ ).json()+ assert got["candidates"] == 3+ assert [s["id"] for s in got["suspects"]][:1] == ["pr-2"]+ assert got["suspects"][0]["signals"]["text"]["evidence"] == ["term crash"]+ assert "probability" in got["note"]++ assert (await client.post(url, json={})).status_code == 422+ assert (await client.post(url, json={"symptom": "x", "until": "soon"})).status_code == 422diff --git a/tests/unit/server/test_chat_session.py b/tests/unit/server/test_chat_session.pyindex 67acfee4f..1f92524cf 100644--- a/tests/unit/server/test_chat_session.py+++ b/tests/unit/server/test_chat_session.py@@ -772,3 +772,46 @@ async def test_an_answer_without_figures_stores_no_check(store):assert "diagnostics" not in [e["type"] for e in events]content = (await store.messages(session.id))[-1].contentassert "figures" not in content and "diagnostics" not in content+++# ---------------------------------------------------------------------------+# find_suspects: chat-only, local backend, follows get_context's admission+# ---------------------------------------------------------------------------+++async def test_find_suspects_is_offered_on_the_local_backend_and_runs(store, monkeypatch):+ import repowise.server.chat_session as chat_session_mod+ from repowise.server.chat_suspects import SUSPECTS_TOOL+ from repowise.server.chat_tools import LocalToolBackend++ class FakeLocal(LocalToolBackend):+ def __init__(self) -> None:+ super().__init__("/tmp/demo", repo_alias="demo")+ self.inner = FakeTools()++ def catalog_for(self, policy, principal):+ return self.inner.catalog_for(policy, principal)++ async def execute(self, name, arguments):+ return await self.inner.execute(name, arguments)++ seen: list = []++ async def fake_run(arguments, repo):+ seen.append((arguments, repo))+ return {"suspects": [{"id": "pr-2", "rank": 1, "signals": {"text": {"rank": 1, "evidence": []}}}]}++ monkeypatch.setattr(chat_session_mod, "run_find_suspects", fake_run)+ provider = ScriptedProvider([[_tool("t1", SUSPECTS_TOOL, {"symptom": "login fails"})], [_text("pr-2")]])+ session = await _open(store, provider, tools=FakeLocal())+ result = await session.send("what broke login?")++ assert SUSPECTS_TOOL in provider.calls[0]["tools"]+ assert seen == [({"symptom": "login fails"}, "demo")]+ assert [t.ok for t in result.tool_trace] == [True]++ narrow = ScriptedProvider([[_text("x")]])+ await (+ await _open(store, narrow, tools=FakeLocal(), policy=SessionPolicy(tool_allowlist=frozenset({"get_risk"})))+ ).send("q")+ assert SUSPECTS_TOOL not in narrow.calls[0]["tools"]diff --git a/tests/unit/test_suspects.py b/tests/unit/test_suspects.pynew file mode 100644index 000000000..a27cf6ef9--- /dev/null+++ b/tests/unit/test_suspects.py@@ -0,0 +1,158 @@+"""Suspect ranking: signals, fusion and the seam."""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++from repowise.core.co_change import CoChangePartner+from repowise.core.suspects import (+ Candidate,+ Hit,+ SuspectContext,+ Symptom,+ rank_suspects,+ suspect_signals,+)+from repowise.core.suspects.git_text import hunk_symbols+from repowise.core.suspects.signals import path_mentions++NOW = datetime(2026, 1, 10, tzinfo=UTC)+QUERY = "django/db/models/query.py"+COMPILER = "django/db/models/sql/compiler.py"+++def _ctx() -> SuspectContext:+ return SuspectContext(+ repo_files=frozenset({QUERY, COMPILER, "docs/index.txt"}),+ imports={QUERY: [COMPILER], COMPILER: [QUERY]},+ co_change={QUERY: [CoChangePartner(COMPILER, 1.0, support=3, self_commits=10)]},+ )+++def _candidates() -> list[Candidate]:+ return [+ Candidate("a", "Fix queryset filter", NOW - timedelta(days=1), (QUERY,), symbols=("filter",)),+ Candidate("b", "Docs typo", NOW - timedelta(hours=2), ("docs/index.txt",)),+ Candidate("c", "Refactor sql compiler", NOW - timedelta(days=5), (COMPILER,), symbols=("as_sql",)),+ ]+++TRACE = 'Traceback (most recent call last):\n File "/srv/app/django/db/models/sql/compiler.py", line 10, in as_sql\n'+++def test_every_candidate_is_ranked_with_the_signals_that_fired():+ out = rank_suspects(Symptom(text="queryset filter crash in query.py\n" + TRACE, at=NOW), _candidates(), _ctx())+ assert [s.change_id for s in out] == ["c", "a", "b"]+ assert [s.rank for s in out] == [1, 2, 3]+ top = out[0].signals+ assert set(top) == {"text", "graph", "co-change", "recency", "trace"}+ assert top["trace"].evidence == (f"frame file {COMPILER}", "frame function as_sql")+ assert top["co-change"].evidence == (f"{COMPILER} changed in 3 of 10 commits to {QUERY}",)+ assert set(out[2].signals) == {"recency"}+++def test_no_symptom_evidence_leaves_recency_order():+ out = rank_suspects(Symptom(text="", at=NOW), _candidates(), SuspectContext())+ assert [s.change_id for s in out] == ["b", "a", "c"]+++def test_signals_argument_restricts_the_fusion():+ out = rank_suspects(Symptom(text="sql compiler", at=NOW), _candidates(), _ctx(), signals=["text"])+ assert out[0].change_id == "c"+ assert set(out[0].signals) == {"text"}+++def test_ties_share_a_rank_within_a_signal():+ out = rank_suspects(Symptom(files=(QUERY, COMPILER), at=NOW), _candidates(), _ctx(), signals=["graph"])+ graph = {s.change_id: s.signals["graph"].rank for s in out if "graph" in s.signals}+ assert graph == {"a": 1, "c": 1}+ assert out[0].change_id == "a" # fused tie: newest first+++def test_a_registered_plugin_signal_fuses_with_the_defaults():+ class Pin:+ def rank(self, symptom, candidates, ctx):+ return {"c": Hit(1.0, ("pinned",))}++ suspect_signals.register("test-pin", Pin())+ try:+ out = rank_suspects(Symptom(text="", at=NOW), _candidates(), SuspectContext())+ assert out[0].change_id == "c"+ assert out[0].signals["test-pin"].evidence == ("pinned",)+ finally:+ suspect_signals._impls.pop("test-pin")+++def test_path_mentions_reads_urls_and_bare_names():+ text = "See https://github.com/o/r/blob/main/django/db/models/query.py#L12 and compiler.py, version 3.2"+ assert path_mentions(text) == ["github.com/o/r/blob/main/django/db/models/query.py", "compiler.py"]+++def test_hunk_symbols_reads_function_context():+ diff = "@@ -1,2 +1,3 @@ def as_sql(self, compiler):\n+x\n@@ -9 +9 @@ class Query(BaseExpression):\n@@ -20 +20 @@\n"+ assert hunk_symbols(diff) == ("as_sql", "Query")+++def test_a_raising_signal_did_not_fire():+ class Broken:+ def rank(self, symptom, candidates, ctx):+ raise RuntimeError("boom")++ suspect_signals.register("test-broken", Broken())+ try:+ out = rank_suspects(Symptom(text="", at=NOW), _candidates(), SuspectContext())+ assert [s.change_id for s in out] == ["b", "a", "c"]+ assert all("test-broken" not in s.signals for s in out)+ finally:+ suspect_signals._impls.pop("test-broken")+++def test_text_evidence_follows_the_fts_prefix_rule():+ cands = [Candidate("a", "Invalidates the cache", NOW, ("x.py",))]+ out = rank_suspects(Symptom(text="invalidat", at=NOW), cands, SuspectContext(), signals=["text"])+ assert out[0].signals["text"].evidence == ("term invalidat",)+++def test_person_trailers_never_reach_the_text(tmp_path):+ import subprocess++ from repowise.core.suspects.git_text import read_change_texts, strip_person_trailers++ body = "Why.\n\nPR-URL: https://h/pull/1\nReviewed-By: Ann Lee <[email protected]>\nSigned-off-by: Bob\nCo-authored-by: C <[email protected]>"+ assert strip_person_trailers(body) == "Why.\n\nPR-URL: https://h/pull/1"++ env = {"GIT_AUTHOR_NAME": "a", "GIT_AUTHOR_EMAIL": "a@x", "GIT_COMMITTER_NAME": "a",+ "GIT_COMMITTER_EMAIL": "a@x", "PATH": __import__("os").environ["PATH"]}+ def git(*a):+ return subprocess.run(["git", "-C", str(tmp_path), *a], capture_output=True, text=True,+ check=True, env=env).stdout.strip()+ git("init", "-q")+ (tmp_path / "f.py").write_text("def f():\n return 1\n")+ git("add", "f.py")+ git("commit", "-q", "-m", "Add f", "-m", body)+ head = git("rev-parse", "HEAD")+ # An unknown and an empty sha in the batch cost only themselves.+ got = read_change_texts(tmp_path, [(head, 1), ("f" * 40, 1), ("", 1)])+ assert list(got) == [head]+ assert "Ann" not in got[head][0] and "Bob" not in got[head][0]+++def test_text_evidence_skips_filler_and_the_repo_name_but_is_never_empty():+ cands = [+ Candidate("a", "repowise shows the invoice total", NOW, ("billing/invoice.py",)),+ Candidate("b", "repowise shows the readme", NOW, ("docs/readme.md",)),+ ]+ ctx = SuspectContext(repo_terms=frozenset({"repowise"}))+ out = {+ s.change_id: s.signals["text"].evidence+ for s in rank_suspects(Symptom(text="repowise shows invoice", at=NOW), cands, ctx, signals=["text"])+ }+ assert out["a"] == ("term invoice",)+ assert out["b"] == ("term repowise",) # nothing else matched: the top term stays+++def test_one_import_hop_reads_singular():+ ctx = SuspectContext(imports={QUERY: [COMPILER], COMPILER: [QUERY]})+ out = rank_suspects(Symptom(files=(QUERY,), at=NOW), _candidates(), ctx, signals=["graph"])+ hop = next(s for s in out if s.change_id == "c").signals["graph"].evidence+ assert hop == (f"1 import hop from {QUERY} to {COMPILER}",)