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(risk): branch overlap, the other open branches editing the files you edit (#2131)
Raghav Chamadiya18bbba9ad150
diff --git a/README.md b/README.mdindex dc8b2135b..ebf450c25 100644--- a/README.md+++ b/README.md@@ -199,7 +199,7 @@ Full guide: **[docs/agent/DISTILL.md →](docs/agent/DISTILL.md)**## Know what's dangerous before you merge-Three deterministic signals, all computed from the graph and git history, no LLM:+Four deterministic signals, all computed from the graph and git history, no LLM:- **Change risk.** Score any commit or `base..HEAD` range **0-10** from the shape ofthe diff, ranked against your repo's own recent commits. PR mode returns directives@@ -213,6 +213,12 @@ Three deterministic signals, all computed from the graph and git history, no LLMtests reach a file and which ones a diff actually exercises, from the call graph,with or without a coverage report.([reference →](docs/layers/TEST_INTELLIGENCE.md))+- **Change coordination.** Which other open branches edit the files you are editing,+ every row saying why it is listed (`same file`, or a co-change pair with the commit+ counts behind it), and whether the diff in front of you is one change or several+ groups the index links nothing between. Both stay quiet when there is nothing to+ report. `repowise overlap` and `repowise risk`.+ ([reference →](docs/layers/CHANGE_RISK.md#branch-overlap))Plus the free **[Repowise PR Bot](#the-pr-bot)**, which puts all of it on every pullrequest. Zero LLM calls.diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 7d348257f..7f1b93547 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -662,6 +662,79 @@ precision on this repo's frozen judgments, which is enough to count fixes andnot enough to accuse one commit of causing them. The block is absent entirelyon an index with no fix history.+In workspace mode the response also holds `cross_repo`, built from the artifacts+of the last `repowise update --workspace` rather than from a graph traversal. It+appears when the commit touches a file that provides a contract some other repo+consumes, or when the breaking-change report attributes a break to one of the+changed files. `consumers[]` names each link with its `provider_file`, the+consumer's `repo`, `file` and `contract_id`, the `contract_type` and the+`match_type` that joined them, plus `provider_symbol_id` and `symbol_id` when the+link is symbol-level; `consumer_repos` lists the other repos in one place.+`breaking_changes[]` carries the `contract_id`, `type`, `kind`, `severity`,+`detail`, `provider_file` and `impacted_repos` of each contract that changed+incompatibly. `breaking_changes_available` says whether a detection pass ran at+all, so an empty list reads as silence rather than as an all-clear, and+`breaking_changes_as_of` stamps that half only. `consumers` is capped at ten and+`breaking_changes` at five, with `consumers_truncated` and+`breaking_changes_truncated` counting what the caps left out; the block answers+whether this commit crosses a repo boundary, and `get_blast_radius` is the tool+for the full traversal. It is absent outside workspace mode, without contract+artifacts, and when the commit touches no published file.++`branch_overlap` names the other open branches editing the files this change+edits. It is git-only, so it appears whether or not the repo is indexed; an index+only orders the shared files and adds the history rows. `base` and `current` name+the two ends of the comparison, and each `branches[]` entry carries the branch+name, `ahead` and `behind` commit counts, `last_commit` (the date), and `files[]`.+Every file row states its `basis` in words, either `same file` or+`co-change pair, N of M commits`, the second carrying the `partner` file of this+change it pairs with and appearing only under a branch that already shares a file+directly, at most three per branch. `scanned`, `total` and `truncated` report the+branch scan itself, which is bounded to the newest 50 branches by committer date.+There is no score and no percentage in the block. `branches` is capped at five and+each entry's `files` at ten, both through the shared response budget: a capped+list gains `<key>_total`, `<key>_emitted`, `<key>_truncated`, `<key>_omitted` and+`<key>_reduced_reason` beside it, and the omitted rows go to the omission store,+so on `branches_truncated` or `files_truncated` the response carries an+`omission_marker` and `repowise expand <ref>` returns the rest. `truncated` is a+different fact: it reports the branch scan bound, not a cap. The block is absent when the change has+no counted files, when no other branch edits a shared file, and when the scan+exceeds its 20-second ceiling or git cannot answer.++`change_shape.independent_changes` says when the diff is several changes rather+than one. It groups the changed files by connectivity, over index edges (imports,+calls, type references, framework and dynamic edges), stored co-change pairs, and,+when `revspec` is a `base..head` range, the files each commit of that range+touched, which links them to each other. A single commit and uncommitted work+carry no commit evidence, so only a range reads it. Only a changed file that is in+the index, is not a test, and is written in a language whose resolver can emit an+import edge is eligible to be grouped: docs, config and data files are never in a+group, not even through a co-change pair, and tests never join or connect one.+`count` is the number of groups; each `groups[]` entry lists its `files` and its+`bridging_files`, the files that alone hold the group together, where moving one+out would split it (named only for groups of three or more files, and most often+the file two commits of the range share). `ungrouped_files` carries every changed+file left out of the grouping, and `summary` names the reasons in those terms:+docs, config, tests, files not in the index, or files it has never linked. `basis` states in words+what was actually checked, and its sentence changes with the subject: it names a+shared commit alongside the import, call, type reference and co-change pair when+the commits of a range were read, and omits it when there were none to read. Under+either wording it is a claim about this index and not about the code. There is no+separate key saying which sentence you got; the sentence itself says it.+`ungrouped_files` is capped at ten through the shared response budget, so a capped+list gains `ungrouped_files_total`, `_emitted`, `_truncated`, `_omitted` and+`_reduced_reason` beside it and the omitted names go to the omission store,+recoverable with `repowise expand <ref>`; nothing else in the block is capped. The+block needs an index and is absent without one, and it is absent whenever the diff+is one change: fewer than two changed files, fewer than two of them eligible to be+grouped, or fewer than two groups surviving. Under a response over budget it is+the first thing shed, ahead of the rest of `change_shape`; `branch_overlap` sheds+after `prior_fixes` and before `cross_repo`.++The freshness envelope is scoped to the files this change edits, whether or not+the repo is indexed: `branch_overlap` reads files on other branches, and that+never widens what the response is about.+**When to use:** Before merging a commit or PR range, especially when you needto assess the change itself rather than the risk of an already-indexed file.diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.mdindex 2e3c47ca4..c64475974 100644--- a/docs/layers/CHANGE_RISK.md+++ b/docs/layers/CHANGE_RISK.md@@ -232,6 +232,77 @@ once and answers subsequent `get_change_risk` calls without repeating it. A newcommit, a moved branch, or a different set of filters produces a differentanchor or a different filter set, and so a fresh walk.+## Independent changes++This is a structural property of the diff, not a score: it answers whether the+files in front of you are one change or several. The changed files are grouped by+connectivity, and one group is separate from another only because nothing+connected them.++Not every changed file is eligible to be grouped. A file is grouped only when it+has a file node in the index, is not a test file, and is written in a language+whose resolver can emit an import edge at all. That rules out documentation,+configuration and data files: a lockfile or a markdown page is a node with no+edges, so "nothing links it" is a fact about the language rather than about this+change. It rules out test files too, because no index records the tie from a test+to the code it exercises, and an integration test otherwise attaches to whichever+shared harness the diff happens to contain. Files that fail either test are never+placed in a group, not even through a co-change pair, and they never bridge two+groups: only eligible files are in the graph at all, and any link with one end+outside that set is dropped before grouping.++Three kinds of link connect two eligible files:++- **Index edges.** Every non-containment edge whose two ends belong to two+ different changed files: imports, calls projected to the files that own them,+ type references, framework and dynamic edges, and reads. Edges whose ends belong+ to the same file are dropped, which is how the containment types (`defines`,+ `has_method`) stay out without being enumerated, and an edge to a dependency+ outside the repository links nothing.+- **Stored co-change pairs.** Two files history moves together are one change even+ when nothing imports anything.+- **Commit co-membership, for a `base..head` range only.** The files one commit+ touched are linked to each other, so a file two commits share joins them. That+ is the author's own statement that the files belong together, which is stronger+ evidence than any edge, and it is what `bridging_files` most often names. A+ single commit and the working tree carry no such evidence: one commit says+ nothing about what moves with what, so the range's commit list is read only when+ the subject is a range.++A group also has to carry at least one file the index has in fact linked to+something, whether through an edge, a stored co-change partner, or a shared+commit. Elsewhere, an absent edge is not evidence, so the files fall out of the+grouping instead.++Everything not grouped is reported as `ungrouped_files` and never counted as an+independent change, and the summary says so in those terms: *N changed file(s)+is/are left out of the grouping: docs, config, tests, files not in the index, or files it has never+linked.* `bridging_files` names the articulation points of a group's own subgraph,+the files that alone hold the group together: move one out and the group splits.+It is computed only for groups of three or more files, since removing either end+of a pair leaves one file, which is not a split.++There is no score, no percentage, and no adjective on the result. The `basis`+field states in words what was actually checked, and it is not the same sentence+in both cases. When the commits of a range were read, it is *no import, call, type+reference, co-change pair or shared commit in the index and this range links one+group to another*; when there were no commits to read, the shared commit drops out+of the sentence and it is *no import, call, type reference or co-change pair in+the index links one group to another*. That wording is deliberate in either form:+a missing edge is a claim about this index, not about the code, and the sentence+never claims a check that did not happen.++The report is silent unless it has something to say. Nothing is produced when+fewer than two changed files exist, when fewer than two of them are eligible to be+grouped, or when fewer than two groups survive. A change that is one change gets+no report.++It surfaces in two places. `repowise risk` prints the groups under the driver+table, naming each group's files, its bridging files, and the first ten ungrouped+paths; `--format json` carries the same object under `independent_changes`. In+`get_change_risk` it is `change_shape.independent_changes`, which needs an index+and is absent without one.+## Calibration & accuracyConstants are learned offline against the defect corpus (AG-SZZ bug-inducing@@ -354,3 +425,60 @@ current contracts against the previously-indexed set during`repowise update --workspace`; non-breaking changes (an added optional field, anew endpoint) never appear. See[Breaking-Change Guard](../scale/WORKSPACES.md#breaking-change-guard) for the full model.++## Branch overlap++Branch overlap answers one question: which other open branches edit the files+this change edits. It is git first, so it works in a fresh clone with no index.++The scan starts from one `git for-each-ref` over `refs/heads` and+`refs/remotes`, sorted by committer date, newest first. Symbolic remote heads+are skipped, refs sharing a tip commit collapse to one entry (the local name+where there is one, otherwise the shortest remote name), and the base ref, the+change's own ref, and any ref whose tip is the base's or the change's commit are+dropped. Branches stacked on the current one, and the ones it is stacked on, are+dropped too: either shares every file by construction, which is one change split+over two refs rather than two changes racing. The scan is bounded to the newest+50 branches by committer date, raised or lowered with `--limit`, and what was+left out is reported through `scanned` and `total` rather than dropped silently.++For each scanned branch the file list is `git diff --name-only base...branch`,+which is what that branch did since it forked, not what the base did in the+meantime. That list is intersected with the change's own changed files. Noise+paths (workflows, lockfiles, generated and vendored files, localization blobs)+are removed from both sides by the shared noise filter, and dependency manifests+(`package.json`, `pyproject.toml`, `go.mod`, `Cargo.toml`, `Gemfile`,+`composer.json`, `requirements.txt`, `setup.py`, `pom.xml`, `build.gradle`,+`build.gradle.kts`) are removed with them, because every dependency bump edits+the manifest and sharing one says nothing about the work. A branch with no shared+file after that filtering produces no entry, ever.++Every row states its basis in words, and there are exactly two:++- **`same file`.** A direct hit: both branches change that path.+- **`co-change pair, N of M commits`.** A secondary row, shown only beneath a+ branch that already has a direct hit. It names a file the other branch edits+ that is not itself a direct hit and that the index's stored co-change record+ pairs with one of this change's files, with that file carried as `partner`. It+ is made only when both counts are recorded and the pair moved together at least+ half the time (`N * 2 >= M`), and at most three appear per branch, so one file+ that pairs with everything cannot drown out the files truly shared.++An entry also carries `ahead` and `behind` (commits only on the branch, then only+on the base, from one `git rev-list --left-right --count`) and the date of its+last commit. Branches are ordered by how many files they share directly, then by+most recent commit, then by name; the co-change rows are appended afterwards and+never reorder the list. There is no score and no percentage anywhere in the+output. With an index, the shared files inside an entry are ordered by the same+hub metric the PR blast radius uses (temporal hotspot and pagerank of the file);+that metric orders rows and is never rendered. Without an index the git answer+stands and the shared files are alphabetical, with no co-change rows.++What it does not claim: it compares paths, not hunks, so a shared file is a+reason to talk to the other branch's author and not a predicted merge conflict.+The co-change rows are historical correlation, never a structural link.++Silence is the default. `repowise overlap` prints one line when no other branch+edits a shared file, naming how many branches were scanned of how many exist, and+`get_change_risk` omits the `branch_overlap` block entirely in that case. The+block is also omitted when the branch scan times out.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 8eef339ab..dc8f7b427 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -2,7 +2,7 @@Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](../start/QUICKSTART.md).-Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).+Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `health`, `risk`, `overlap`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. `init` never requires a key: without one it renders the wiki from structure. It calls an LLM only when a provider is resolvable or `--prose` is passed. The exceptions: `update` (unless `--index-only` or `--no-docs`), `generate`, `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `security`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.@@ -31,6 +31,7 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details**Health and risk**[`health`](#repowise-health-path) ·[`risk`](#repowise-risk-revspec) ·+[`overlap`](#repowise-overlap) ·[`dead-code`](#repowise-dead-code-path) ·[`security`](#repowise-security) ·[`impacted-tests`](#repowise-impacted-tests-revspec) ·@@ -779,10 +780,58 @@ repowise risk -t src/auth.py --changed-file src/auth.py # PR mode + directiveNote `--path` on this command already means "the git repository", which is whythe files are named with `--target`.+**Independent changes.** When the index can be read, the command also prints+whether the diff is one change or several: the changed files grouped by what+connects them, which is the links the index holds (imports, calls, type+references, stored co-change pairs) plus, for a `base..head` range, the files each+commit touched, since putting two files in one commit is the author's own+statement that they belong together. Only indexed, non-test source files a+resolver can link are grouped; docs, config, data and tests are always printed+under `Left out of the grouping:`, never as a change of their own, and only the+first ten names are listed. Each group prints its files and the files that alone+hold it together, where moving one out would split the group. A closing `Basis:`+line says what was checked, naming a shared commit only when there were commits to+read. It is silent when the diff is one change, and it carries no score.+`--format json` puts the same object under `independent_changes`. See+[Independent changes](../layers/CHANGE_RISK.md#independent-changes).+See [`docs/layers/CHANGE_RISK.md`](../layers/CHANGE_RISK.md) for the scoring model.---+### `repowise overlap`++Which other open branches edit the files this change edits. Pure git for the+answer, so it works in a fresh clone with no index; when an index is readable it+orders the shared files and adds the files history pairs with them. Every row+states its basis in words, `same file` or `co-change pair, N of M commits`, and+there is no score anywhere in the output.++Branches stacked on the current one (and the ones it is stacked on) are skipped,+as are noise paths and dependency manifests, which every branch touches. A branch+that shares no file produces no row. The scan is bounded to the newest branches by+committer date and reports how many it scanned of how many exist.++**Options:**++| Flag | Description |+|------|-------------|+| `--base` | Base ref to diff both sides against (default: the repository's trunk, from `origin/HEAD`, else `main` or `master`) |+| `--branch` | The change to compare (default: `HEAD`) |+| `--path` | Path to the git repository (default: current directory) |+| `--limit` | How many branches to diff, newest committer date first (default 50) |+| `--format` | Output format: `table` (default) or `json` |++```bash+repowise overlap # who else is editing what you are editing+repowise overlap --base main --limit 100 # a wider scan against an explicit base+```++When nothing overlaps, the command prints one line saying so with the scan+counts. See [Branch overlap](../layers/CHANGE_RISK.md#branch-overlap).++---+### `repowise security`Security signal scanning. Working-tree scanning already runs duringdiff --git a/packages/cli/src/repowise/cli/commands/overlap_cmd.py b/packages/cli/src/repowise/cli/commands/overlap_cmd.pynew file mode 100644index 000000000..ee09e7db4--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/overlap_cmd.py@@ -0,0 +1,130 @@+"""``repowise overlap`` - other open branches editing the files this change edits.++Git answers who touches the same file; the repository's own index, when there+is one, orders those files and adds the ones history pairs with them. Without+an index the git answer stands, so the command works in a fresh clone.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++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+from repowise.core.analysis.branch_overlap import BRANCH_SCAN_LIMIT, BranchOverlap+++def _require_ref(root: Path, ref: str) -> None:+ """Refuse a ref that names no commit: git diffs it to nothing, which reads+ as "no changes" rather than as the pruned remote or typo it is."""+ from repowise.core import git_refs++ if not git_refs.resolve(str(root), ref):+ raise click.ClickException(f"Unknown ref {ref!r}.")+++def _repo_path(path: str | None) -> Path:+ """The repository to read. One repo, always: a branch scan is one repo's git."""+ target = resolve_command_target(path=path, no_workspace_flag=True)+ assert target.repo_path is not None+ return Path(target.repo_path).resolve()+++async def _overlap(root: Path, changed: list[str], **kwargs: Any) -> BranchOverlap:+ """The overlap for *changed*, using the repository's index when it is readable."""+ from sqlalchemy.exc import SQLAlchemyError++ from repowise.core.analysis.branch_overlap import rank_with_index, scan_branches++ scan = scan_branches(str(root), changed, **kwargs)+ # The index is opened only to rank what git already found.+ async with repo_index_session(root) as opened:+ if opened is not None:+ session, repo_id = opened+ try:+ return await rank_with_index(session, repo_id, scan)+ except (SQLAlchemyError, OSError, LookupError):+ # An index written by an older version can fail the query itself.+ pass+ # An absent, stale or locked index costs the ranking, not the answer.+ return scan.overlap+++def _render(data: dict[str, Any]) -> None:+ """The branches and the files they share, with each row's basis in words."""+ from rich.markup import escape++ summary = escape(str(data.get("summary") or ""))+ branches = data.get("branches") or []+ if not branches:+ console.print(summary)+ return++ console.print(f"[bold]{summary}[/bold]")+ # One width for every row so the basis column lines up across branches.+ width = max(len(str(row["basis"])) for entry in branches for row in entry["files"])+ for entry in branches:+ console.print(+ f"\n{escape(str(entry['branch']))} ahead {entry['ahead']}, "+ f"behind {entry['behind']}, last commit {entry['last_commit']}"+ )+ for row in entry["files"]:+ partner = row.get("partner")+ suffix = f" (with {escape(str(partner))})" if partner else ""+ basis = escape(str(row["basis"])).ljust(width)+ console.print(f" {basis} {escape(str(row['file']))}{suffix}")++ if data.get("truncated"):+ console.print(+ f"\n[dim]Scanned the newest {data['scanned']} of {data['total']} branches; "+ "raise --limit to scan more.[/dim]"+ )++[email protected]("overlap")[email protected]("--base", default=None, help="Base ref (defaults to the repository's trunk).")[email protected]("--branch", default="HEAD", help="The change to compare. Defaults to HEAD.")[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")+ "--limit",+ type=click.IntRange(min=1),+ default=BRANCH_SCAN_LIMIT,+ show_default=True,+ help="How many branches to diff, newest committer date first.",+)+@format_option()+def overlap_command(+ base: str | None, branch: str, repo: str | None, limit: int, fmt: str+) -> None:+ """Show which other branches edit the files this change edits."""+ from repowise.core import git_refs++ root = _repo_path(repo)+ base = base or git_refs.default_base(str(root))+ _require_ref(root, base)+ _require_ref(root, branch)++ changed = git_refs.changed_files(str(root), base, branch)+ if not changed:+ message = f"Nothing changed on {branch} since {base}."+ if fmt == "json":+ # The same keys as any other run, so a consumer parses one shape.+ empty = BranchOverlap(base, git_refs.current_branch(str(root)) or branch, (), 0, 0)+ emit_json({**empty.to_dict(), "summary": message})+ else:+ console.print(message)+ return++ result = run_async(_overlap(root, changed, base=base, current=branch, limit=limit))+ if fmt == "json":+ emit_json(result.to_dict())+ return+ _render(result.to_dict())diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex faa491a9d..d5ad5f178 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -67,6 +67,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("dead-code", "dead_code_cmd:dead_code_command"),("health", "health_cmd:health_command"),("risk", "risk_cmd:risk_command"),+ ("overlap", "overlap_cmd:overlap_command"),("decision", "decision_cmd:decision_group"),("coverage", "coverage_cmd:coverage_group"),("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),diff --git a/packages/core/src/repowise/core/analysis/branch_overlap.py b/packages/core/src/repowise/core/analysis/branch_overlap.pynew file mode 100644index 000000000..4d4754cd0--- /dev/null+++ b/packages/core/src/repowise/core/analysis/branch_overlap.py@@ -0,0 +1,377 @@+"""Other open branches that edit the files this change edits.++Git alone answers who touches the same file. With an index the shared files are+ordered by how central they are, and history adds the files a branch edits that+move with ours. Without an index the git answer stands unchanged.++One bulk read picks which branches earn an exact diff, and a commit two+branches share is credited to one of them, so a branch can be missed there+but never listed on a file it does not edit.+"""++from __future__ import annotations++from collections.abc import Iterable+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass, field, replace+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core import git_refs+from repowise.core.co_change import CoChangePartner, parse_partners+from repowise.core.persistence.batches import chunked+from repowise.core.persistence.models import GitMetadata, GraphNode+from repowise.core.workspace.cross_repo import _is_noise_path++from .pr_blast import PRBlastRadiusAnalyzer++# Newest branches diffed. A repository with hundreds of stale refs would spend+# more on the scan than the answer is worth; what was left out is reported+# through ``scanned`` and ``total`` rather than dropped silently.+BRANCH_SCAN_LIMIT = 50++# History rows corroborate a direct hit, they do not compete with it: past a+# few, one file that pairs with everything drowns out the files truly shared.+CO_CHANGE_ROWS_PER_BRANCH = 3++# Every dependency bump edits the manifest, so sharing one says nothing about+# the work. Kept here rather than in the shared noise list, which is counted on.+_MANIFEST_NAMES = frozenset(+ {+ "go.mod",+ "package.json",+ "pyproject.toml",+ "Cargo.toml",+ "Gemfile",+ "composer.json",+ "requirements.txt",+ "setup.py",+ "pom.xml",+ "build.gradle",+ "build.gradle.kts",+ }+)++# Git serves concurrent reads, and the exact diffs are the only per-hit cost left.+_DIFF_WORKERS = 4++_SAME_FILE = "same file"+++@dataclass(frozen=True)+class OverlapRow:+ """One file another branch edits, and the reason it is listed."""++ file: str+ basis: str+ partner: str | None = None+++@dataclass(frozen=True)+class BranchOverlapEntry:+ """One other branch, and where it meets this change."""++ branch: str+ committed_at: str+ committed_unix: int+ ahead: int+ behind: int+ rows: tuple[OverlapRow, ...]+++@dataclass(frozen=True)+class BranchOverlap:+ """Every branch that edits a file this change edits, and what was scanned."""++ base: str+ current: str+ branches: tuple[BranchOverlapEntry, ...]+ scanned: int+ total: int++ def to_dict(self) -> dict[str, Any]:+ return {+ "base": self.base,+ "current": self.current,+ "branches": [+ {+ "branch": entry.branch,+ "ahead": entry.ahead,+ "behind": entry.behind,+ "last_commit": entry.committed_at[:10],+ "files": [_row_dict(row) for row in entry.rows],+ }+ for entry in self.branches+ ],+ "scanned": self.scanned,+ "total": self.total,+ "truncated": self.scanned < self.total,+ "summary": self._summary(),+ }++ def _summary(self) -> str:+ if not self.branches:+ return (+ "No other open branch edits a file this change edits "+ f"({self.scanned} scanned of {self.total})."+ )+ return (+ f"{len(self.branches)} of {self.scanned} open branches "+ f"({self.total} exist) edit files this change also edits."+ )+++@dataclass(frozen=True)+class BranchScan:+ """The git answer, with what the index step needs to go further.++ Held apart from :class:`BranchOverlap` so the git work finishes before a+ database session is opened, rather than under one.+ """++ overlap: BranchOverlap+ others: dict[str, frozenset[str]] = field(default_factory=dict)+ ours: frozenset[str] = frozenset()+++def _row_dict(row: OverlapRow) -> dict[str, Any]:+ out: dict[str, Any] = {"file": row.file}+ if row.partner:+ out["partner"] = row.partner+ out["basis"] = row.basis+ return out+++def _signal(paths: Iterable[str]) -> frozenset[str]:+ """Paths worth pairing: a lockfile or manifest two branches both touch means nothing."""+ return frozenset(+ path+ for path in paths+ if path+ and not _is_noise_path(path)+ and path.replace("\\", "/").rsplit("/", 1)[-1] not in _MANIFEST_NAMES+ )+++def _prefer(candidate: git_refs.BranchRef, kept: git_refs.BranchRef) -> bool:+ """Whether *candidate* is the better name for a tip already seen."""+ if candidate.is_remote != kept.is_remote:+ return kept.is_remote+ return len(candidate.name) < len(kept.name)+++def _same_line_of_work(repo_path: str, current: str) -> set[str]:+ """Branches stacked on this one or that this one is stacked on: one change+ split over two refs shares every file, which is not two changes racing."""+ return git_refs.refs_containing(repo_path, current) | git_refs.refs_merged_into(+ repo_path, current+ )+++def _candidates(+ repo_path: str, skip_names: set[str], skip_shas: set[str]+) -> list[git_refs.BranchRef]:+ """Branches worth diffing, newest first, one entry per distinct tip."""+ by_sha: dict[str, git_refs.BranchRef] = {}+ for ref in git_refs.list_branches(repo_path):+ if ref.name in skip_names or ref.sha in skip_shas:+ continue+ kept = by_sha.get(ref.sha)+ # Replacing the value keeps the newest-first position of the first sighting.+ if kept is None or _prefer(ref, kept):+ by_sha[ref.sha] = ref+ return list(by_sha.values())+++def _worth_diffing(preview: frozenset[str] | None, ours: frozenset[str]) -> bool:+ """Absent means no commits of its own; empty means merge-only, so look anyway."""+ if preview is None:+ return False+ return not preview or bool(preview & ours)+++def _order(entries: list[BranchOverlapEntry]) -> tuple[BranchOverlapEntry, ...]:+ """Most shared files first, then the most recent branch, then by name."""+ ordered = sorted(entries, key=lambda entry: entry.branch)+ ordered.sort(key=lambda entry: entry.committed_unix, reverse=True)+ ordered.sort(key=lambda entry: len(entry.rows), reverse=True)+ return tuple(ordered)+++def scan_branches(+ repo_path: str,+ changed_files: Iterable[str],+ *,+ base: str,+ current: str = "HEAD",+ limit: int = BRANCH_SCAN_LIMIT,+) -> BranchScan:+ """Branch overlap from git alone: shared files, alphabetical, no history rows."""+ ours = _signal(changed_files)+ if not ours:+ return BranchScan(BranchOverlap(base, current, (), 0, 0))++ resolved = current+ if current == "HEAD":+ resolved = git_refs.current_branch(repo_path) or current+ refs = _candidates(+ repo_path,+ {base, current, resolved} | _same_line_of_work(repo_path, current),+ {+ sha+ for sha in (git_refs.resolve(repo_path, base), git_refs.resolve(repo_path, current))+ if sha+ },+ )++ scanned = refs[:limit]+ touched = git_refs.files_by_ref(repo_path, base, [ref.name for ref in scanned])+ # No bulk answer at all means a git too old for %S: diff every branch instead.+ probe_each = not touched and bool(scanned)++ probes = [+ ref for ref in scanned if probe_each or _worth_diffing(touched.get(ref.name), ours)+ ]++ def diff(ref: git_refs.BranchRef) -> frozenset[str]:+ # Rows come from the exact three-dot diff, never from the bulk read: a file+ # changed and reverted on a branch is in the bulk read but not in the diff.+ return _signal(git_refs.changed_files(repo_path, base, ref.name))++ hit: list[tuple[git_refs.BranchRef, list[str]]] = []+ others: dict[str, frozenset[str]] = {}+ with ThreadPoolExecutor(max_workers=_DIFF_WORKERS) as pool:+ # map keeps the candidate order, so the answer does not depend on timing.+ for ref, theirs in zip(probes, pool.map(diff, probes), strict=True):+ shared = sorted(theirs & ours)+ # No shared file means no entry: history alone never puts a branch on the list.+ if not shared:+ continue+ hit.append((ref, shared))+ others[ref.name] = theirs++ counts = git_refs.ahead_behind_many(repo_path, base, [ref.ref for ref, _ in hit if ref.ref])+ entries: list[BranchOverlapEntry] = []+ for ref, shared in hit:+ # A git too old for the bulk count still answers one ref at a time.+ ahead, behind = counts.get(ref.name) or git_refs.ahead_behind(repo_path, base, ref.name)+ entries.append(+ BranchOverlapEntry(+ branch=ref.name,+ committed_at=ref.committed_at,+ committed_unix=ref.committed_unix,+ ahead=ahead,+ behind=behind,+ rows=tuple(OverlapRow(file=path, basis=_SAME_FILE) for path in shared),+ )+ )++ overlap = BranchOverlap(+ base=base,+ current=resolved,+ branches=_order(entries),+ scanned=len(scanned),+ total=len(refs),+ )+ return BranchScan(overlap=overlap, others=others, ours=ours)+++async def _read_index(+ session: AsyncSession, repo_id: str, hits: list[str], ours: list[str]+) -> tuple[dict[str, float], dict[str, list[CoChangePartner]]]:+ """``(shared file -> hub score, our file -> co-change partners)``, two batched reads."""+ pagerank: dict[str, float] = {}+ for chunk in chunked(hits):+ result = await session.execute(+ select(GraphNode.node_id, GraphNode.pagerank).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_type == "file",+ GraphNode.node_id.in_(chunk),+ )+ )+ pagerank.update({node_id: float(rank or 0.0) for node_id, rank in result.all()})++ temporal: dict[str, float] = {}+ partners: dict[str, list[CoChangePartner]] = {}+ for chunk in chunked(ours):+ result = await session.execute(+ select(+ GitMetadata.file_path,+ GitMetadata.temporal_hotspot_score,+ GitMetadata.co_change_partners_json,+ ).where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.file_path.in_(chunk),+ )+ )+ for path, score, raw in result.all():+ temporal[path] = float(score or 0.0)+ partners[path] = parse_partners(raw)++ hub = {+ path: PRBlastRadiusAnalyzer._score_file(temporal.get(path, 0.0), pagerank.get(path, 0.0))+ for path in hits+ }+ return hub, partners+++def _co_change_rows(+ partners: dict[str, list[CoChangePartner]], theirs: frozenset[str], hits: set[str]+) -> list[OverlapRow]:+ """Files the branch edits that history pairs with one of ours, strongest first."""+ best: dict[str, tuple[int, OverlapRow]] = {}+ for our_file in sorted(partners):+ for partner in partners[our_file]:+ path = partner.file_path+ if path in hits or path not in theirs:+ continue+ # Without both counts the row cannot state its own basis, so it is not made.+ if not partner.support or not partner.self_commits:+ continue+ # Below half, the basis on the wire would read as a pair that mostly does not hold.+ if partner.support * 2 < partner.self_commits:+ continue+ seen = best.get(path)+ if seen is None or partner.support > seen[0]:+ best[path] = (+ partner.support,+ OverlapRow(+ file=path,+ basis=f"co-change pair, {partner.support} of {partner.self_commits} commits",+ partner=our_file,+ ),+ )+ ranked = sorted(best.values(), key=lambda item: (-item[0], item[1].file))+ return [row for _, row in ranked[:CO_CHANGE_ROWS_PER_BRANCH]]+++def _rerank(+ entry: BranchOverlapEntry,+ hub: dict[str, float],+ partners: dict[str, list[CoChangePartner]],+ theirs: frozenset[str],+) -> BranchOverlapEntry:+ """Shared files by hub score, then the history rows."""+ hits = {row.file for row in entry.rows}+ direct = sorted(entry.rows, key=lambda row: (-hub.get(row.file, 0.0), row.file))+ return replace(entry, rows=tuple(direct) + tuple(_co_change_rows(partners, theirs, hits)))+++async def rank_with_index(session: AsyncSession, repo_id: str, scan: BranchScan) -> BranchOverlap:+ """The scan with its shared files ordered by the index and history rows added."""+ overlap = scan.overlap+ if not overlap.branches:+ return overlap++ hits = sorted({row.file for entry in overlap.branches for row in entry.rows})+ hub, partners = await _read_index(session, repo_id, hits, sorted(scan.ours))+ # Entry order is set by the direct hits, so adding history rows must not reorder.+ return replace(+ overlap,+ branches=tuple(+ _rerank(entry, hub, partners, scan.others.get(entry.branch, frozenset()))+ for entry in overlap.branches+ ),+ )diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex 0b3255b9d..9e100799e 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -69,11 +69,13 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {# Cheapest loss first. Diff-shape context and history go before the# delta and the tests, so what to do survives what the diff weighs."exclude_patterns",+ "change_shape.independent_changes","change_shape","fix_history.files[]","fix_history.files","fix_history","prior_fixes",+ "branch_overlap","cross_repo","impacted_tests","health_delta.limits",diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex d9f7c8366..b6020b54f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -28,7 +28,7 @@ from repowise.core.analysis.change_risk import ()from repowise.core.analysis.pr_blast import rank_tests_by_reachfrom repowise.core.registry import mcp_tool_registry as mcp-from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server._budget import OmissionCollector, cap_collectionfrom repowise.server.mcp_server._budget.contracts import response_budget_shed_orderfrom repowise.server.mcp_server._change_health import (directive as _directive,@@ -71,6 +71,20 @@ _PRIOR_FIXES_LIMIT = 10_CROSS_REPO_BREAKING_LIMIT = 5_CROSS_REPO_CONSUMER_LIMIT = 10+#: Ceiling on the branch scan, bounded so a repository with hundreds of refs+#: cannot hold the response.+_BRANCH_OVERLAP_TIMEOUT_SECONDS = 20++#: Caps on the branch-overlap block. It answers "is anyone else editing these+#: files", not "list every branch", so both lists stay short and their tails go+#: to the omission store.+_BRANCH_OVERLAP_LIMIT = 5+_BRANCH_OVERLAP_FILES_LIMIT = 10++#: Cap on the files the index cannot link. The count is already in the block's+#: summary, so the names are supporting detail and their tail is recoverable.+_UNGROUPED_FILES_LIMIT = 10+# Compatibility projection for direct callers and older tests. The shared# response contract remains the single source of truth for this order._SHED_ORDER = response_budget_shed_order("get_change_risk")@@ -131,6 +145,10 @@ async def get_change_risk(``prior_fixes`` counts past fixes overlapping this diff. ``change_shape``ranks the diff's size and spread against recent commits.+ ``branch_overlap`` names other open branches editing the same files, each+ row stating its basis. ``change_shape.independent_changes`` says when the+ diff is several changes the index does not connect.+Args:revspec: Commit or ``base..head`` range. Omit to review uncommittedwork, or ``HEAD`` when the tree is clean.@@ -183,19 +201,16 @@ async def get_change_risk(# extensions + riskignore + request excludes), so nothing downstream# disagrees with the score about which files the change touches. Read once# and shared: both blocks below need it and git is the expensive part.- # The test and fix blocks need the index; the cross-repo block needs only- # workspace contracts, so an unindexed member still gets one rather than- # going silently blind. Nothing else pays the git call.- changed: dict[str, set[int]] = {}- changed_error: tuple[str, str] | None = None- if getattr(ctx, "session_factory", None) is not None or _has_contract_data():- changed, changed_error = await _changed_in_scope(- str(ctx.path),- revspec,- normalize_extensions(tuple(extensions or ())),- result.riskignore_excludes + result.request_excludes,- working_tree=result.working_tree,- )+ # The test and fix blocks need the index and the cross-repo block needs+ # workspace contracts, but the branch-overlap block needs only git, so every+ # call pays this read rather than an unindexed repo going blind.+ changed, changed_error = await _changed_in_scope(+ str(ctx.path),+ revspec,+ normalize_extensions(tuple(extensions or ())),+ result.riskignore_excludes + result.request_excludes,+ working_tree=result.working_tree,+ )collector = OmissionCollector("get_change_risk", repo_root=ctx.path)# The delta is the expensive half and needs nothing the enrichments need,# so it runs alongside them rather than after.@@ -222,6 +237,14 @@ async def get_change_risk(cross_repo = _cross_repo_block(alias, sorted(changed), impact, collector)if cross_repo is not None:payload["cross_repo"] = cross_repo+ # A drill-down returns one finding and nothing else, so neither block+ # would reach the caller; both are pure cost on that path.+ overlap = independent = None+ if finding_id is None:+ overlap = await _branch_overlap_block(ctx, changed, collector)+ if overlap is not None:+ payload["branch_overlap"] = overlap+ independent = await _independent_changes_block(ctx, changed, collector, revspec)except BaseException:# Never leave the comparison running for a request that is already over.delta_task.cancel()@@ -231,7 +254,7 @@ async def get_change_risk(if finding_id is not None:return _drill_down(payload, delta, finding_id, revspec)_attach_health(payload, delta, revspec, expand="findings" in include_set)- payload["change_shape"] = _change_shape(payload, diagnostics)+ payload["change_shape"] = _change_shape(payload, diagnostics, independent)# source: live_git marks that the *score* is computed from the working# checkout's git. The two blocks above are index-backed, so the freshness# fields do apply to them, scoped to the change's files. None (not []) when@@ -387,10 +410,15 @@ def _attach_health(payload: dict, delta: Any, revspec: str | None, *, expand: bopayload.update(ordered)-def _change_shape(payload: dict, diagnostics: dict) -> dict[str, Any]:+def _change_shape(+ payload: dict, diagnostics: dict, independent: dict[str, Any] | None = None+) -> dict[str, Any]:"""The ranked diff-shape reading, kept compact and clearly supporting."""shape = {f: payload[f] for f in _CHANGE_SHAPE_FIELDS if f in payload}shape["measures"] = "diff size and spread, not danger"+ # How many changes this diff is belongs beside its size, not above it.+ if independent is not None:+ shape["independent_changes"] = independentif diagnostics:shape["diagnostics_via"] = "get_change_risk(include=['diagnostics'])"return shape@@ -471,16 +499,6 @@ def _filter_changed(return out-def _has_contract_data() -> bool:- """Whether workspace contracts are loaded, so the cross-repo block can speak."""- from repowise.server.mcp_server import _state-- if not _is_workspace_mode():- return False- enricher = _state._cross_repo_enricher- return bool(enricher is not None and getattr(enricher, "has_contract_data", False))--def _cross_repo_block(alias: str,changed_files: list[str],@@ -820,6 +838,123 @@ async def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[strreturn block+async def _independent_changes_block(+ ctx: Any,+ changed: dict[str, set[int]],+ collector: OmissionCollector,+ revspec: str | None = None,+) -> dict[str, Any] | None:+ """The changed files split into groups nothing in the index links, or ``None``.++ Silent for a single changed file and without an index: the split is a claim+ about what the index holds, so an unindexed repo makes no claim at all.+ """+ from repowise.core.analysis.independent_changes import independent_changes+ from repowise.core.git_refs import commit_file_sets+ from repowise.core.persistence.database import get_session++ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is None or len(changed) < 2:+ return None+ # Returns [] without a git call for anything that is not a range, so the+ # range test lives in one place rather than here as well.+ sets = await asyncio.to_thread(+ commit_file_sets, str(ctx.path), _normalize_revspec(revspec)+ )+ try:+ async with get_session(session_factory) as session:+ repo_id = (await _get_repo(session)).id+ result = await independent_changes(+ session, repo_id, list(changed), commit_sets=sets+ )+ except (LookupError, SQLAlchemyError):+ return None+ if result is None:+ return None+ block = result.to_dict()+ cap_collection(+ block,+ "ungrouped_files",+ block["ungrouped_files"],+ _UNGROUPED_FILES_LIMIT,+ collector,+ label=(+ "change_shape.independent_changes.ungrouped_files "+ f"beyond cap={_UNGROUPED_FILES_LIMIT}"+ ),+ )+ return block+++def _scan_from_trunk(path: str, files: list[str]) -> Any:+ """The base lookup and the scan, both git, in one hop off the event loop."""+ from repowise.core.analysis.branch_overlap import scan_branches+ from repowise.core.git_refs import default_base++ return scan_branches(path, files, base=default_base(path))+++async def _scan_overlap(ctx: Any, files: list[str]) -> Any:+ """Run the branch scan, with the index when one opens and without when it does not."""+ from repowise.core.analysis.branch_overlap import rank_with_index+ from repowise.core.persistence.database import get_session++ path = str(ctx.path)+ scan = await asyncio.to_thread(_scan_from_trunk, path, files)+ session_factory = getattr(ctx, "session_factory", None)+ if session_factory is not None:+ try:+ # The session opens only for the index step, never across the git work.+ async with get_session(session_factory) as session:+ return await rank_with_index(session, (await _get_repo(session)).id, scan)+ except (LookupError, SQLAlchemyError):+ pass+ return scan.overlap+++async def _branch_overlap_block(+ ctx: Any, changed: dict[str, set[int]], collector: OmissionCollector+) -> dict[str, Any] | None:+ """Other open branches editing the files this change edits, or ``None``.++ Git alone answers it, so a repo without an index still gets the block; an+ index only ranks the shared files and adds the history rows. ``None`` when+ no other branch overlaps, because an all-clear block is noise.+ """+ if not changed:+ return None+ try:+ overlap = await asyncio.wait_for(+ _scan_overlap(ctx, sorted(changed)), timeout=_BRANCH_OVERLAP_TIMEOUT_SECONDS+ )+ except (TimeoutError, subprocess.SubprocessError, OSError):+ return None++ block = overlap.to_dict()+ if not block["branches"]:+ return None+ # Branches first: an entry the cap drops goes to the store whole, and only+ # the entries that survive can carry an index the reader can find.+ kept = cap_collection(+ block,+ "branches",+ block["branches"],+ _BRANCH_OVERLAP_LIMIT,+ collector,+ label=f"branch_overlap.branches beyond cap={_BRANCH_OVERLAP_LIMIT}",+ )+ for i, entry in enumerate(kept):+ cap_collection(+ entry,+ "files",+ entry["files"],+ _BRANCH_OVERLAP_FILES_LIMIT,+ collector,+ label=f"branch_overlap.branches[{i}].files beyond cap={_BRANCH_OVERLAP_FILES_LIMIT}",+ )+ return block++#: A file has to carry this much of the change's lines before the response will#: say the risk sits there. Below it the change is spread out and naming one#: file would be a stronger claim than the numbers support.diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex f3a32f430..b765db9d8 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -241,7 +241,17 @@ export interface RiskReportArtifactData {/** `get_change_risk` action-first blocks. */directive?: ChangeRiskDirective;health_delta?: ChangeHealthDeltaData;- change_shape?: Record<string, unknown>;+ change_shape?: {+ independent_changes?: {+ count?: number;+ summary?: string;+ basis?: string;+ ungrouped_files?: string[];+ groups?: Array<{ files: string[]; bridging_files?: string[] }>;+ [k: string]: unknown;+ };+ [k: string]: unknown;+ };impacted_tests?: { tests_to_run?: string[]; status?: string; summary?: string };/** Bug-fix record of the touched files: the "historically fragile" signal. */fix_history?: {@@ -249,6 +259,24 @@ export interface RiskReportArtifactData {files?: Array<{ path: string; churn: number; fix_pressure: number }>;};prior_fixes?: { files_with_fixes?: number; total_fixes?: number };+ /** Other open branches editing the files this change edits. */+ branch_overlap?: {+ base?: string;+ current?: string;+ scanned?: number;+ total?: number;+ truncated?: boolean;+ summary?: string;+ branches?: Array<{+ branch: string;+ ahead?: number;+ behind?: number;+ last_commit?: string;+ files?: Array<{ file: string; basis: string; partner?: string }>;+ [k: string]: unknown;+ }>;+ [k: string]: unknown;+ };[k: string]: unknown;}diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.jsonindex 3333ebd56..c0af018d6 100644--- a/tests/fixtures/mcp/tool_response_shapes.json+++ b/tests/fixtures/mcp/tool_response_shapes.json@@ -136,9 +136,33 @@"source": null,"timing_ms": null},+ "branch_overlap": {+ "base": null,+ "branches": [+ {+ "ahead": null,+ "behind": null,+ "branch": null,+ "files": [+ {+ "basis": null,+ "file": null,+ "partner": null+ }+ ],+ "last_commit": null+ }+ ],+ "current": null,+ "scanned": null,+ "summary": null,+ "total": null,+ "truncated": null+ },"change_shape": {"classification": null,"diagnostics_via": null,+ "independent_changes": null,"fallback_band": null,"is_fix": null,"measures": null,diff --git a/tests/unit/analysis/test_branch_overlap.py b/tests/unit/analysis/test_branch_overlap.pynew file mode 100644index 000000000..57ec875cd--- /dev/null+++ b/tests/unit/analysis/test_branch_overlap.py@@ -0,0 +1,456 @@+"""Which other branches edit the files this change edits.++The git half runs against a real repository built under ``tmp_path``: branch+listing, three-dot diffs and ahead/behind are the whole question, so a fake+would only assert that the fake agrees with itself. The index half seeds a real+wiki.db for the same reason.+"""++from __future__ import annotations++import json+import os+import subprocess++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from repowise.core.analysis.branch_overlap import rank_with_index, scan_branches+from repowise.core.git_refs import ahead_behind_many, files_by_ref+from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import (+ GitMetadata,+ GraphNode,+ Repository,+ _new_uuid,+)++_REPO_ID = "repo1"++# Our changed files, as a caller would hand them over: two real files plus a+# lockfile the noise filter must drop.+_OURS = ["hub.py", "shared.py", "package-lock.json", "go.mod"]+++def _overlap(repo, ours=None, **kwargs):+ """The git-only answer, which is what ``scan_branches`` wraps."""+ return scan_branches(str(repo), _OURS if ours is None else ours, base="main", **kwargs).overlap+++def _run(repo, *args, when: str | None = None) -> str:+ env = None+ if when is not None:+ env = {"GIT_AUTHOR_DATE": when, "GIT_COMMITTER_DATE": when}+ result = subprocess.run(+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", *args],+ cwd=str(repo),+ check=True,+ capture_output=True,+ text=True,+ env={**os.environ, **(env or {})},+ )+ return result.stdout.strip()+++def _commit(repo, message: str, files: dict[str, str], when: str) -> None:+ for name, text in files.items():+ (repo / name).write_text(text, encoding="utf-8")+ _run(repo, "add", "-A")+ _run(repo, "commit", "-m", message, when=when)+++def repo(tmp_path):+ """A repository whose branches cover every outcome the scan can produce."""+ path = tmp_path / "repo"+ path.mkdir()+ _run(path, "init", "-b", "main")+ _commit(+ path,+ "base",+ {+ "shared.py": "0\n",+ "hub.py": "0\n",+ "other.py": "0\n",+ "partner.py": "0\n",+ "zero.py": "0\n",+ "p3.py": "0\n",+ "go.mod": "0\n",+ "p4.py": "0\n",+ "package-lock.json": "{}\n",+ },+ "2026-01-01T00:00:00+00:00",+ )++ # Oldest branch, and a hit: it decides which branch the limit leaves out.+ _run(path, "checkout", "-b", "oldest")+ _commit(path, "oldest", {"shared.py": "oldest\n"}, "2026-01-02T00:00:00+00:00")++ _run(path, "checkout", "main")+ _run(path, "checkout", "-b", "elsewhere")+ _commit(path, "elsewhere", {"other.py": "elsewhere\n"}, "2026-01-03T00:00:00+00:00")++ _run(path, "checkout", "main")+ _run(path, "checkout", "-b", "bump")+ _commit(path, "bump", {"go.mod": "bumped' + NL + '"}, "2026-01-03T12:00:00+00:00")++ _run(path, "checkout", "main")+ _run(path, "checkout", "-b", "noisy")+ _commit(path, "noisy", {"package-lock.json": '{"a": 1}\n'}, "2026-01-04T00:00:00+00:00")++ _run(path, "checkout", "main")+ _run(path, "checkout", "-b", "already-merged")+ _commit(path, "merged", {"shared.py": "merged\n"}, "2026-01-05T00:00:00+00:00")+ _run(path, "checkout", "main")+ _run(path, "merge", "--no-ff", "-m", "merge", "already-merged", when="2026-01-06T00:00:00+00:00")++ _run(path, "checkout", "-b", "hitter")+ _commit(+ path,+ "hitter",+ {+ "shared.py": "hitter\n",+ "hub.py": "hitter\n",+ "partner.py": "1\n",+ "zero.py": "1\n",+ "p3.py": "1\n",+ "p4.py": "1\n",+ "package-lock.json": '{"b": 2}\n',+ "go.mod": "hitter\n",+ },+ "2026-01-07T00:00:00+00:00",+ )+ # A remote-tracking twin of the same tip: one entry, under the local name.+ _run(path, "update-ref", "refs/remotes/origin/hitter", _run(path, "rev-parse", "hitter"))++ # A commit on main after the branch point, so the branch is behind as well as ahead.+ _run(path, "checkout", "main")+ _commit(path, "moved on", {"other.py": "moved\n"}, "2026-01-08T00:00:00+00:00")++ _run(path, "checkout", "-b", "feat/x")+ _commit(path, "ours", {"shared.py": "ours\n", "hub.py": "ours\n"}, "2026-01-09T00:00:00+00:00")++ # Stacked on top of this change: the same line of work, not a parallel edit.+ _run(path, "checkout", "-b", "stacked")+ _commit(path, "stacked", {"shared.py": "stacked\n"}, "2026-01-10T00:00:00+00:00")+ _run(path, "checkout", "feat/x")+ return path+++# ---------------------------------------------------------------------------+# Git+++def test_only_branches_sharing_a_file_appear(repo):+ result = _overlap(repo)++ assert [entry.branch for entry in result.branches] == ["hitter", "oldest"]+ assert result.current == "feat/x"+ assert result.base == "main"+ assert [row.file for row in result.branches[1].rows] == ["shared.py"]+++def test_scanned_and_total_count_every_candidate(repo):+ result = _overlap(repo)++ # oldest, elsewhere, bump, noisy, hitter: the remote twin collapsed into "hitter".+ assert (result.scanned, result.total) == (5, 5)+ assert result.to_dict()["truncated"] is False+++def test_the_limit_leaves_out_the_oldest_branch(repo):+ result = _overlap(repo, limit=4)++ assert (result.scanned, result.total) == (4, 5)+ assert [entry.branch for entry in result.branches] == ["hitter"]+ assert result.to_dict()["truncated"] is True+++def test_a_branch_this_change_is_stacked_on_is_not_listed(repo):+ """A parent edits our files by construction: one change, two refs."""+ names = [entry.branch for entry in _overlap(repo).branches]++ assert "already-merged" not in names+++def test_a_branch_stacked_on_this_change_is_not_listed(repo):+ """A branch containing HEAD shares every file, and is not a parallel edit."""+ result = _overlap(repo)++ assert "stacked" not in [entry.branch for entry in result.branches]+ # Neither stacked ref counts as a candidate that was passed over.+ assert result.total == 5+++def test_a_branch_touching_other_files_is_absent(repo):+ names = [entry.branch for entry in _overlap(repo).branches]++ assert "elsewhere" not in names+++def test_a_shared_dependency_manifest_is_not_an_overlap(repo):+ """Every bump edits the manifest, so sharing it is not shared work."""+ names = [entry.branch for entry in _overlap(repo).branches]++ assert "bump" not in names+++def test_a_shared_lockfile_is_not_an_overlap(repo):+ names = [entry.branch for entry in _overlap(repo).branches]++ assert "noisy" not in names+++def test_the_remote_twin_collapses_into_the_local_name(repo):+ names = [entry.branch for entry in _overlap(repo).branches]++ assert names.count("hitter") == 1+ assert "origin/hitter" not in names+++def test_the_base_and_the_current_branch_are_skipped(repo):+ names = [entry.branch for entry in _overlap(repo).branches]++ assert "main" not in names+ assert "feat/x" not in names+++def test_ahead_is_the_branch_and_behind_is_the_base(repo):+ entry = _overlap(repo).branches[0]++ assert entry.branch == "hitter"+ assert (entry.ahead, entry.behind) == (1, 1)+++def test_git_alone_lists_shared_files_alphabetically(repo):+ entry = _overlap(repo).branches[0]++ assert [(row.file, row.basis) for row in entry.rows] == [+ ("hub.py", "same file"),+ ("shared.py", "same file"),+ ]+++def test_nothing_shared_gives_the_empty_summary(repo):+ result = _overlap(repo, ["untouched.py"])++ assert result.branches == ()+ assert result.to_dict()["summary"] == (+ "No other open branch edits a file this change edits (5 scanned of 5)."+ )+++def test_the_summary_counts_the_branches_that_overlap(repo):+ assert _overlap(repo).to_dict()["summary"] == (+ "2 of 5 open branches (5 exist) edit files this change also edits."+ )+++# ---------------------------------------------------------------------------+# The bulk read that decides which branches earn an exact diff+++def test_one_read_names_every_file_a_ref_changed(repo):+ assert files_by_ref(str(repo), "main", ["stacked"]) == {+ "stacked": frozenset({"shared.py", "hub.py"})+ }+++def test_a_ref_with_no_commits_of_its_own_is_absent(repo):+ assert files_by_ref(str(repo), "main", ["already-merged"]) == {}+++def test_one_read_counts_ahead_and_behind_for_every_ref(repo):+ """Ahead is the branch's own commits, behind is what the base gained since."""+ assert ahead_behind_many(str(repo), "main", ["refs/heads/hitter", "refs/heads/oldest"]) == {+ "hitter": (1, 1),+ "oldest": (1, 3),+ }+++def test_a_shared_commit_is_credited_to_one_ref(repo):+ result = files_by_ref(str(repo), "main", ["stacked", "feat/x"])++ # "stacked" sits on "feat/x", so the commit they share counts once.+ assert result["feat/x"] == frozenset({"shared.py", "hub.py"})+ assert result["stacked"] == frozenset({"shared.py"})+++# ---------------------------------------------------------------------------+# Index+++async def _seed(tmp_path, *, partners: list[dict]) -> async_sessionmaker:+ """A wiki.db where shared.py outranks hub.py and carries the given partners."""+ db_path = tmp_path / "wiki.db"+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ session.add(Repository(id=_REPO_ID, name="repo", local_path=str(tmp_path)))+ # hub.py has the higher pagerank; shared.py still wins on temporal weight.+ for path, rank in (("shared.py", 0.2), ("hub.py", 0.3), ("partner.py", 0.1)):+ session.add(+ GraphNode(+ id=_new_uuid(),+ repository_id=_REPO_ID,+ node_id=path,+ node_type="file",+ pagerank=rank,+ )+ )+ session.add(+ GitMetadata(+ id=_new_uuid(),+ repository_id=_REPO_ID,+ file_path="shared.py",+ temporal_hotspot_score=2.0,+ co_change_partners_json=json.dumps(partners),+ )+ )+ session.add(+ GitMetadata(+ id=_new_uuid(),+ repository_id=_REPO_ID,+ file_path="hub.py",+ temporal_hotspot_score=0.0,+ )+ )+ await session.commit()+ return factory+++def _partner(path: str, *, frequency: int, self_commits: int = 9) -> dict:+ return {+ "file_path": path,+ "co_change_count": 5.0,+ "frequency": frequency,+ "self_commits": self_commits,+ }+++async def _hitter(tmp_path, repo, partners: list[dict]):+ factory = await _seed(tmp_path, partners=partners)+ scan = scan_branches(str(repo), _OURS, base="main")+ async with factory() as session:+ result = await rank_with_index(session, _REPO_ID, scan)+ return next(entry for entry in result.branches if entry.branch == "hitter"), result+++async def test_shared_files_are_ordered_by_the_hub_metric(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [])++ # Alphabetical order would put hub.py first.+ assert [row.file for row in entry.rows] == ["shared.py", "hub.py"]+++async def test_a_co_change_row_follows_the_shared_files(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [_partner("partner.py", frequency=6)])++ assert [row.file for row in entry.rows] == ["shared.py", "hub.py", "partner.py"]+ row = entry.rows[-1]+ assert row.basis == "co-change pair, 6 of 9 commits"+ assert row.partner == "shared.py"+++async def test_a_partner_without_a_count_states_no_basis(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [_partner("zero.py", frequency=0)])++ assert [row.file for row in entry.rows] == ["shared.py", "hub.py"]+++async def test_a_partner_that_is_already_shared_is_not_repeated(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [_partner("hub.py", frequency=7)])++ assert [row.file for row in entry.rows] == ["shared.py", "hub.py"]+ assert all(row.basis == "same file" for row in entry.rows)+++async def test_history_alone_never_puts_a_branch_on_the_list(tmp_path, repo):+ _, result = await _hitter(tmp_path, repo, [_partner("other.py", frequency=6)])++ # "elsewhere" edits other.py and nothing else: a co-change pair is not a hit.+ assert "elsewhere" not in [entry.branch for entry in result.branches]+++async def test_a_pair_that_mostly_does_not_hold_makes_no_row(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [_partner("partner.py", frequency=12, self_commits=43)])++ assert [row.file for row in entry.rows] == ["shared.py", "hub.py"]+++async def test_a_pair_that_holds_half_the_time_makes_a_row(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [_partner("partner.py", frequency=14, self_commits=21)])++ assert entry.rows[-1].basis == "co-change pair, 14 of 21 commits"+++async def test_history_rows_are_capped_per_branch(tmp_path, repo):+ entry, _ = await _hitter(+ tmp_path,+ repo,+ [+ _partner("partner.py", frequency=8),+ _partner("zero.py", frequency=7),+ _partner("p3.py", frequency=6),+ _partner("p4.py", frequency=5),+ ],+ )++ assert [row.file for row in entry.rows] == [+ "shared.py",+ "hub.py",+ "partner.py",+ "zero.py",+ "p3.py",+ ]+++async def test_a_scan_that_found_nothing_is_not_ranked(tmp_path, repo):+ """Nothing shared means no index read, and the git answer is returned as it is."""+ factory = await _seed(tmp_path, partners=[])+ scan = scan_branches(str(repo), ["untouched.py"], base="main")+ async with factory() as session:+ assert await rank_with_index(session, _REPO_ID, scan) is scan.overlap+++async def test_a_shared_lockfile_or_manifest_never_becomes_a_row(tmp_path, repo):+ """The hit branch also edits both, and neither reaches the rows."""+ entry, _ = await _hitter(tmp_path, repo, [])++ assert [row.file for row in entry.rows] == ["shared.py", "hub.py"]+++async def test_a_pair_at_exactly_half_makes_a_row(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [_partner("partner.py", frequency=12, self_commits=24)])++ assert entry.rows[-1].basis == "co-change pair, 12 of 24 commits"+++async def test_a_pair_just_under_half_makes_no_row(tmp_path, repo):+ entry, _ = await _hitter(tmp_path, repo, [_partner("partner.py", frequency=12, self_commits=25)])++ assert [row.file for row in entry.rows] == ["shared.py", "hub.py"]+++async def test_the_wire_shape_names_every_field(tmp_path, repo):+ _, result = await _hitter(tmp_path, repo, [_partner("partner.py", frequency=6)])+ payload = result.to_dict()++ assert set(payload) == {+ "base",+ "current",+ "branches",+ "scanned",+ "total",+ "truncated",+ "summary",+ }+ branch = payload["branches"][0]+ assert set(branch) == {"branch", "ahead", "behind", "last_commit", "files"}+ assert branch["last_commit"] == "2026-01-07"+ assert branch["files"] == [+ {"file": "shared.py", "basis": "same file"},+ {"file": "hub.py", "basis": "same file"},+ {"file": "partner.py", "partner": "shared.py", "basis": "co-change pair, 6 of 9 commits"},+ ]diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex 66791737b..633ed477c 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -36,7 +36,8 @@ _EXPECTED_NAMES = frozenset("agents", "ask", "augment", "context", "corrections", "costs", "coverage","dead-code", "decision", "delete", "distill", "doctor", "expand","export", "generate", "generate-claude-md", "health", "hook",- "impacted-tests", "init", "login", "logout", "mcp", "reindex", "restyle",+ "impacted-tests", "init", "login", "logout", "mcp", "overlap", "reindex",+ "restyle","risk", "saved", "search", "security", "serve", "status", "symbol","telemetry", "uninstall", "update", "watch", "whats-new", "whoami", "why","wiki-styles", "workspace",diff --git a/tests/unit/cli/test_overlap_cmd.py b/tests/unit/cli/test_overlap_cmd.pynew file mode 100644index 000000000..0e5abcb13--- /dev/null+++ b/tests/unit/cli/test_overlap_cmd.py@@ -0,0 +1,233 @@+"""``repowise overlap`` over a real temporary repository.++Branch listing and three-dot diffs are the whole question the command asks, so+the tests build real repositories rather than a fake that would only agree with+itself. None of them has an index: the git-only path is what a fresh clone gets.+"""++from __future__ import annotations++import json+import os+import subprocess++import pytest+from click.testing import CliRunner++from repowise.cli.commands.overlap_cmd import overlap_command+++def _run(repo, *args) -> str:+ result = subprocess.run(+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", *args],+ cwd=str(repo),+ check=True,+ capture_output=True,+ text=True,+ env={**os.environ, "GIT_AUTHOR_DATE": "2026-01-01T00:00:00+00:00",+ "GIT_COMMITTER_DATE": "2026-01-01T00:00:00+00:00"},+ )+ return result.stdout.strip()+++def _commit(repo, message: str, files: dict[str, str]) -> None:+ for name, text in files.items():+ (repo / name).write_text(text, encoding="utf-8")+ _run(repo, "add", "-A")+ _run(repo, "commit", "-m", message)+++def _build(tmp_path, name: str, *, rival: bool) -> object:+ """A repo on ``feat/x``, optionally with another branch editing the same file."""+ path = tmp_path / name+ path.mkdir()+ _run(path, "init", "-b", "main")+ _commit(+ path, "base", {"shared.py": "0\n", "partner.py": "0\n", "other.py": "0\n"}+ )+ if rival:+ _run(path, "checkout", "-b", "rival")+ _commit(path, "rival", {"shared.py": "rival\n"})+ _run(path, "checkout", "main")+ _run(path, "checkout", "-b", "feat/x")+ _commit(path, "ours", {"shared.py": "ours\n"})+ return path+++def repo(tmp_path):+ return _build(tmp_path, "shared", rival=True)+++def lonely(tmp_path):+ return _build(tmp_path, "lonely", rival=False)+++def _invoke(repo, *extra: str):+ result = CliRunner().invoke(overlap_command, ["--path", str(repo), "--base", "main", *extra])+ assert result.exit_code == 0, result.output+ return result.output+++def crowded(tmp_path):+ """Two other branches editing the file this change edits."""+ path = _build(tmp_path, "crowded", rival=True)+ _run(path, "checkout", "main")+ _run(path, "checkout", "-b", "second")+ _commit(path, "second", {"shared.py": "second\n"})+ _run(path, "checkout", "feat/x")+ return path+++def test_a_narrow_limit_says_what_it_did_not_scan(crowded):+ output = _invoke(crowded, "--limit", "1")++ assert "Scanned the newest 1 of 2 branches; raise --limit to scan more." in output+++def test_a_limit_below_one_is_refused(repo):+ result = CliRunner().invoke(overlap_command, ["--path", str(repo), "--limit", "0"])++ assert result.exit_code != 0+++def test_a_branch_editing_the_same_file_is_listed(repo):+ output = _invoke(repo)++ assert "rival" in output+ assert "same file" in output+ assert "shared.py" in output+ # The basis is stated in words: never a score or a percentage.+ assert "%" not in output+++def test_a_branch_that_shares_nothing_prints_only_the_summary(lonely):+ output = _invoke(lonely).strip()++ assert output.splitlines() == [+ "No other open branch edits a file this change edits (0 scanned of 0)."+ ]+++def test_json_carries_the_full_document(repo):+ payload = json.loads(_invoke(repo, "--format", "json"))++ assert set(payload) == {+ "base",+ "current",+ "branches",+ "scanned",+ "total",+ "truncated",+ "summary",+ }+ assert payload["base"] == "main"+ assert payload["current"] == "feat/x"+ assert payload["branches"][0]["files"] == [{"file": "shared.py", "basis": "same file"}]+++def test_a_change_with_nothing_in_it_says_so(repo):+ _run(repo, "checkout", "main")++ assert _invoke(repo).strip() == "Nothing changed on HEAD since main."+++def test_an_unknown_ref_is_refused(repo):+ """A pruned or misspelled ref diffs to nothing, so silence would mislead."""+ result = CliRunner().invoke(+ overlap_command, ["--path", str(repo), "--base", "main", "--branch", "does-not-exist"]+ )++ assert result.exit_code != 0+ assert "Unknown ref 'does-not-exist'." in result.output+++def test_a_repo_without_an_index_still_answers(repo):+ assert not (repo / ".repowise").exists()++ assert "rival" in _invoke(repo)+++def _seed_index(repo, *, partners: list[dict] | None = None) -> None:+ """Just enough store for the command to open a session and look the repo up.++ With *partners*, shared.py also carries those co-change records.+ """+ import asyncio++ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++ from repowise.core.persistence.database import init_db+ from repowise.core.persistence.models import GitMetadata, GraphNode, Repository, _new_uuid++ async def write() -> None:+ db_path = repo / ".repowise" / "wiki.db"+ db_path.parent.mkdir(parents=True, exist_ok=True)+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")+ await init_db(engine)+ async with async_sessionmaker(engine, expire_on_commit=False)() as session:+ session.add(Repository(id="repo1", name="repo", local_path=str(repo.resolve())))+ if partners is not None:+ session.add(+ GraphNode(+ id=_new_uuid(),+ repository_id="repo1",+ node_id="shared.py",+ node_type="file",+ )+ )+ session.add(+ GitMetadata(+ id=_new_uuid(),+ repository_id="repo1",+ file_path="shared.py",+ co_change_partners_json=json.dumps(partners),+ )+ )+ await session.commit()+ await engine.dispose()++ asyncio.run(write())+++def test_an_indexed_repo_names_the_file_a_history_row_pairs_with(repo):+ """With an index the reader also sees which of our files the partner pairs with."""+ _run(repo, "checkout", "rival")+ _commit(repo, "rival edits the partner too", {"partner.py": "rival\n"})+ _run(repo, "checkout", "feat/x")+ _seed_index(+ repo,+ partners=[+ {+ "file_path": "partner.py",+ "co_change_count": 5.0,+ "frequency": 6,+ "self_commits": 9,+ }+ ],+ )++ output = _invoke(repo)++ assert "co-change pair, 6 of 9 commits" in output+ assert "partner.py (with shared.py)" in output+++def test_an_index_the_query_cannot_read_leaves_the_git_answer(repo, monkeypatch):+ """An index written by an older version costs the ranking, not the answer."""+ from sqlalchemy.exc import SQLAlchemyError++ from repowise.core.analysis import branch_overlap as module++ _seed_index(repo)++ async def _fail(*args, **kwargs):+ raise SQLAlchemyError("old schema")++ monkeypatch.setattr(module, "rank_with_index", _fail)+ output = _invoke(repo)++ assert "rival" in output+ assert "shared.py" in outputdiff --git a/tests/unit/server/mcp/test_branch_overlap_block.py b/tests/unit/server/mcp/test_branch_overlap_block.pynew file mode 100644index 000000000..a705966f6--- /dev/null+++ b/tests/unit/server/mcp/test_branch_overlap_block.py@@ -0,0 +1,323 @@+"""get_change_risk's branch_overlap block: who else is editing these files.++Git alone answers it, so the block appears without an index. It is silent when+no other branch shares a file, every row states its basis in words, and the+caps say by how much they cut.+"""++from __future__ import annotations++import subprocess+from pathlib import Path+from types import SimpleNamespace++from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server.tool_change_risk import (+ _BRANCH_OVERLAP_FILES_LIMIT,+ _BRANCH_OVERLAP_LIMIT,+ _SHED_ORDER,+ _branch_overlap_block,+)+++def _git(repo: Path, *args: str) -> None:+ subprocess.run(+ ["git", "-c", "[email protected]", "-c", "user.name=T", *args],+ cwd=repo,+ check=True,+ capture_output=True,+ )+++def _commit(repo: Path, files: dict[str, str], message: str) -> None:+ for name, body in files.items():+ path = repo / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(body, encoding="utf-8")+ _git(repo, "add", "-A")+ _git(repo, "commit", "-m", message)+++def _repo(tmp_path: Path, *, others: dict[str, dict[str, str]]) -> Path:+ """A repo on ``main`` plus one branch per entry of *others*, then back on a work branch."""+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(repo, "init", "-b", "main")+ _commit(repo, {"a.py": "a\n", "b.py": "b\n", "c.py": "c\n"}, "base")+ for branch, files in others.items():+ _git(repo, "checkout", "-b", branch, "main")+ _commit(repo, files, f"work on {branch}")+ _git(repo, "checkout", "-b", "work", "main")+ _commit(repo, {"a.py": "a mine\n"}, "our change")+ return repo+++def _ctx(repo: Path) -> SimpleNamespace:+ """A context with no session factory: the git-only block."""+ return SimpleNamespace(path=str(repo))+++async def test_block_is_silent_with_nothing_changed(tmp_path):+ repo = _repo(tmp_path, others={"other": {"a.py": "a theirs\n"}})+ collector = OmissionCollector("t", repo_root=tmp_path)+ assert await _branch_overlap_block(_ctx(repo), {}, collector) is None+++async def test_block_is_silent_when_no_branch_shares_a_file(tmp_path):+ repo = _repo(tmp_path, others={"elsewhere": {"c.py": "c theirs\n"}})+ block = await _branch_overlap_block(+ _ctx(repo), {"a.py": {1}}, OmissionCollector("t", repo_root=tmp_path)+ )+ assert block is None+++async def test_block_names_only_the_overlapping_branch_and_states_its_basis(tmp_path):+ repo = _repo(+ tmp_path,+ others={"overlapping": {"a.py": "a theirs\n"}, "elsewhere": {"c.py": "c theirs\n"}},+ )++ block = await _branch_overlap_block(+ _ctx(repo), {"a.py": {1}}, OmissionCollector("t", repo_root=tmp_path)+ )++ assert block is not None+ assert [entry["branch"] for entry in block["branches"]] == ["overlapping"]+ entry = block["branches"][0]+ assert [row["file"] for row in entry["files"]] == ["a.py"]+ # Every row says in words why it is listed, and nothing carries a score.+ assert all(row["basis"] for row in entry["files"])+ assert all("score" not in row for row in entry["files"])+ assert block["base"] == "main"+ assert block["current"] == "work"+ assert block["scanned"] >= 2+ assert "edit files this change also edits" in block["summary"]+++async def test_branch_list_is_capped_and_says_by_how_much(tmp_path):+ over = _BRANCH_OVERLAP_LIMIT + 2+ repo = _repo(+ tmp_path,+ others={f"branch{i}": {"a.py": f"a from {i}\n"} for i in range(over)},+ )++ block = await _branch_overlap_block(+ _ctx(repo), {"a.py": {1}}, OmissionCollector("t", repo_root=tmp_path)+ )++ assert block is not None+ assert len(block["branches"]) == _BRANCH_OVERLAP_LIMIT+ assert block["branches_total"] == over+ assert block["branches_truncated"] is True+ assert block["branches_emitted"] == _BRANCH_OVERLAP_LIMIT+++async def test_an_uncut_block_carries_no_truncation_fields(tmp_path):+ repo = _repo(tmp_path, others={"overlapping": {"a.py": "a theirs\n"}})+ block = await _branch_overlap_block(+ _ctx(repo), {"a.py": {1}}, OmissionCollector("t", repo_root=tmp_path)+ )+ assert block is not None+ assert "branches_total" not in block+ assert "files_total" not in block["branches"][0]+++async def test_the_per_branch_file_list_is_capped(tmp_path):+ over = _BRANCH_OVERLAP_FILES_LIMIT + 3+ shared = {f"src/f{i}.py": f"{i}\n" for i in range(over)}+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(repo, "init", "-b", "main")+ _commit(repo, shared, "base")+ _git(repo, "checkout", "-b", "overlapping", "main")+ _commit(repo, {name: "theirs\n" for name in shared}, "their change")+ _git(repo, "checkout", "-b", "work", "main")+ _commit(repo, {name: "mine\n" for name in shared}, "our change")++ block = await _branch_overlap_block(+ _ctx(repo),+ {name: {1} for name in shared},+ OmissionCollector("t", repo_root=tmp_path),+ )++ assert block is not None+ entry = block["branches"][0]+ assert len(entry["files"]) == _BRANCH_OVERLAP_FILES_LIMIT+ assert entry["files_total"] == over+ assert entry["files_truncated"] is True+++async def test_a_dropped_branch_reaches_the_store_with_its_files_intact(tmp_path):+ """The branch cap runs first, so a dropped entry is stored whole."""+ over_files = _BRANCH_OVERLAP_FILES_LIMIT + 2+ shared = {f"src/f{i}.py": f"{i}\n" for i in range(over_files)}+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(repo, "init", "-b", "main")+ _commit(repo, shared, "base")+ for i in range(_BRANCH_OVERLAP_LIMIT + 1):+ _git(repo, "checkout", "-b", f"branch{i}", "main")+ _commit(repo, {name: f"theirs {i}\n" for name in shared}, f"work {i}")+ _git(repo, "checkout", "-b", "work", "main")+ _commit(repo, {name: "mine\n" for name in shared}, "our change")++ collector = OmissionCollector("get_change_risk", repo_root=tmp_path)+ block = await _branch_overlap_block(+ _ctx(repo), {name: {1} for name in shared}, collector+ )++ assert block is not None+ assert block["branches_truncated"] is True+ payload: dict = {"branch_overlap": block}+ collector.attach(payload)++ stored = _stored_text(tmp_path, payload)+ # The dropped entry keeps every file: it was never cut in place, and the+ # per-entry labels only name indexes the response actually carries.+ assert stored.count(f"src/f{over_files - 1}.py") >= 1+ for entry in block["branches"]:+ assert len(entry["files"]) == _BRANCH_OVERLAP_FILES_LIMIT+ assert entry["files_total"] == over_files+++def _stored_text(tmp_path: Path, payload: dict) -> str:+ """Everything this response pushed to the omission store, as one string."""+ from repowise.core.distill.store import OmissionStore, default_store_path++ refs = payload["_meta"]["omitted"]["refs"]+ store = OmissionStore(default_store_path(tmp_path))+ try:+ return "\n".join(store.get(ref) or "" for ref in refs)+ finally:+ store.close()+++async def test_a_scan_that_cannot_answer_yields_no_block(tmp_path, monkeypatch):+ """A timeout or a wedged git is silence, never a half-built block."""+ from repowise.server.mcp_server import tool_change_risk as module++ repo = _repo(tmp_path, others={"overlapping": {"a.py": "a theirs\n"}})++ async def _raises(*_args, **_kwargs):+ raise OSError("git is gone")++ monkeypatch.setattr(module, "_scan_overlap", _raises)+ collector = OmissionCollector("t", repo_root=tmp_path)+ assert await _branch_overlap_block(_ctx(repo), {"a.py": {1}}, collector) is None++ async def _never_returns(*_args, **_kwargs):+ raise TimeoutError++ monkeypatch.setattr(module, "_scan_overlap", _never_returns)+ assert await _branch_overlap_block(_ctx(repo), {"a.py": {1}}, collector) is None+++def test_branch_overlap_participates_in_the_response_ceiling(tmp_path):+ """A block outside the shed order can never be shed, so it has to be in it."""+ from repowise.server.mcp_server._budget import fit_to_budget++ # Shed after the fix record and before the consumer list: who else is in+ # these files outlives what the diff weighs and is cheaper than what breaks.+ assert _SHED_ORDER.index("prior_fixes") < _SHED_ORDER.index("branch_overlap")+ assert _SHED_ORDER.index("branch_overlap") < _SHED_ORDER.index("cross_repo")+ assert _SHED_ORDER.index("change_shape.independent_changes") < _SHED_ORDER.index("change_shape")++ payload = {+ "score": 7.0,+ "branch_overlap": {"branches": [{"branch": "b", "pad": "x" * 400}] * 200},+ "cross_repo": {"consumers": [{"repo": "frontend"}]},+ }+ collector = OmissionCollector("get_change_risk", repo_root=tmp_path)+ fit_to_budget(payload, _SHED_ORDER, collector)++ assert "branch_overlap" not in payload+ assert payload["truncated"] is True+ assert payload["cross_repo"]["consumers"] == [{"repo": "frontend"}]+++async def test_get_change_risk_carries_the_block_end_to_end(tmp_path, monkeypatch):+ from repowise.server.mcp_server import tool_change_risk as module++ repo = _repo(tmp_path, others={"overlapping": {"a.py": "a theirs\n"}})++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ payload = await module.get_change_risk("HEAD", baseline=0)++ assert [e["branch"] for e in payload["branch_overlap"]["branches"]] == ["overlapping"]+ # No index, so the diff is never split into changes the index cannot see.+ assert "independent_changes" not in payload["change_shape"]+++async def test_reading_other_branches_does_not_widen_the_response_targets(tmp_path, monkeypatch):+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++ from repowise.core.persistence.database import init_db+ from repowise.core.persistence.models import Repository+ from repowise.server.mcp_server import tool_change_risk as module++ repo = _repo(tmp_path, others={"overlapping": {"a.py": "a theirs\n"}})+ engine = create_async_engine(f"sqlite+aiosqlite:///{(tmp_path / 'wiki.db').as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ session.add(Repository(id="repo1", name="repo", local_path=str(repo)))+ await session.commit()++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo), session_factory=factory)++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ seen: dict = {}+ build_meta = module._build_meta++ def _capture(**kwargs):+ seen.update(kwargs)+ return build_meta(**kwargs)++ monkeypatch.setattr(module, "_build_meta", _capture)+ payload = await module.get_change_risk("HEAD", baseline=0)++ assert payload["branch_overlap"]["branches"][0]["branch"] == "overlapping"+ # The block reads files on other branches; what the response is about, and+ # what its freshness is scoped to, is still only the files this change edits.+ assert seen["targets"] == ["a.py"]+++async def test_targets_are_the_changed_files_without_an_index(tmp_path, monkeypatch):+ """The block needs only git, so an unindexed call now scopes freshness too."""+ from repowise.server.mcp_server import tool_change_risk as module++ repo = _repo(tmp_path, others={})++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ seen: dict = {}+ build_meta = module._build_meta++ def _capture(**kwargs):+ seen.update(kwargs)+ return build_meta(**kwargs)++ monkeypatch.setattr(module, "_build_meta", _capture)+ await module.get_change_risk("HEAD", baseline=0)++ assert seen["targets"] == ["a.py"]+++async def test_get_change_risk_omits_the_block_without_another_branch(tmp_path, monkeypatch):+ from repowise.server.mcp_server import tool_change_risk as module++ repo = _repo(tmp_path, others={})++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo))++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ payload = await module.get_change_risk("HEAD", baseline=0)++ assert "branch_overlap" not in payloaddiff --git a/tests/unit/server/mcp/test_independent_changes_block.py b/tests/unit/server/mcp/test_independent_changes_block.pynew file mode 100644index 000000000..93c9ee450--- /dev/null+++ b/tests/unit/server/mcp/test_independent_changes_block.py@@ -0,0 +1,233 @@+"""get_change_risk's change_shape.independent_changes block.++The block says a diff is several changes the index does not connect. It is+silent without an index, for a single changed file, and whenever the changed+files hang together, so an ordinary change grows no new block.+"""++from __future__ import annotations++from types import SimpleNamespace++from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from repowise.core.persistence.database import init_db+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository, _new_uuid+from repowise.server.mcp_server._budget import OmissionCollector+from repowise.server.mcp_server.tool_change_risk import (+ _UNGROUPED_FILES_LIMIT,+ _change_shape,+ _independent_changes_block,+)++_REPO_ID = "repo1"+++def _collector(tmp_path) -> OmissionCollector:+ return OmissionCollector("get_change_risk", repo_root=tmp_path)+++async def _ctx(tmp_path, files: list[str], edges: list[tuple[str, str]]) -> SimpleNamespace:+ """A context over a real wiki.db holding *files* as file nodes and *edges* between them."""+ tmp_path.mkdir(parents=True, exist_ok=True)+ db_path = tmp_path / "wiki.db"+ engine = create_async_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ session.add(Repository(id=_REPO_ID, name="repo", local_path=str(tmp_path)))+ for path in files:+ session.add(+ GraphNode(+ id=_new_uuid(),+ repository_id=_REPO_ID,+ node_id=path,+ node_type="file",+ name=path,+ file_path=path,+ language="python",+ )+ )+ for source, target in edges:+ session.add(+ GraphEdge(+ id=_new_uuid(),+ repository_id=_REPO_ID,+ source_node_id=source,+ target_node_id=target,+ edge_type="imports",+ )+ )+ await session.commit()+ return SimpleNamespace(path=str(tmp_path), session_factory=factory)+++async def test_block_is_silent_without_an_index(tmp_path):+ ctx = SimpleNamespace(path="/repo")+ changed = {"a.py": {1}, "b.py": {2}}+ assert await _independent_changes_block(ctx, changed, _collector(tmp_path)) is None+++async def test_block_is_silent_for_fewer_than_two_changed_files(tmp_path):+ ctx = SimpleNamespace(path="/repo", session_factory=object())+ assert await _independent_changes_block(ctx, {}, _collector(tmp_path)) is None+ assert await _independent_changes_block(ctx, {"a.py": {1}}, _collector(tmp_path)) is None+++async def test_block_is_silent_when_the_index_connects_the_changed_files(tmp_path):+ ctx = await _ctx(tmp_path, ["a.py", "b.py"], [("a.py", "b.py")])+ changed = {"a.py": {1}, "b.py": {2}}+ assert await _independent_changes_block(ctx, changed, _collector(tmp_path)) is None+++async def test_block_reports_the_groups_and_states_its_basis(tmp_path):+ """Two connected pairs with nothing between them are two changes, not one."""+ ctx = await _ctx(+ tmp_path,+ ["a.py", "b.py", "c.py", "d.py"],+ [("a.py", "b.py"), ("c.py", "d.py")],+ )++ block = await _independent_changes_block(+ ctx, {"a.py": {1}, "b.py": {1}, "c.py": {1}, "d.py": {1}}, _collector(tmp_path)+ )++ assert block is not None+ assert block["count"] == 2+ assert sorted(g["files"] for g in block["groups"]) == [["a.py", "b.py"], ["c.py", "d.py"]]+ # The claim is about the index, and the block says so rather than implying+ # the code itself has no connection.+ assert "index" in block["basis"]+ assert "independent changes" in block["summary"]+ # No score, percentage or adjective anywhere on the wire.+ assert "score" not in block+++async def test_a_file_the_index_does_not_hold_is_never_grouped(tmp_path):+ ctx = await _ctx(+ tmp_path,+ ["a.py", "b.py", "c.py", "d.py"],+ [("a.py", "b.py"), ("c.py", "d.py")],+ )++ block = await _independent_changes_block(+ ctx,+ {"a.py": {1}, "b.py": {1}, "c.py": {1}, "d.py": {1}, "new.py": {1}},+ _collector(tmp_path),+ )++ assert block is not None+ assert block["ungrouped_files"] == ["new.py"]+ assert all("new.py" not in g["files"] for g in block["groups"])+++async def test_the_ungrouped_file_list_is_capped_and_says_by_how_much(tmp_path):+ """A docs-heavy release commit can leave hundreds of unlinkable files."""+ over = _UNGROUPED_FILES_LIMIT + 3+ loose = [f"docs/page{i}.md" for i in range(over)]+ ctx = await _ctx(+ tmp_path,+ ["a.py", "b.py", "c.py", "d.py"],+ [("a.py", "b.py"), ("c.py", "d.py")],+ )++ changed = {p: {1} for p in ["a.py", "b.py", "c.py", "d.py", *loose]}+ block = await _independent_changes_block(ctx, changed, _collector(tmp_path))++ assert block is not None+ assert len(block["ungrouped_files"]) == _UNGROUPED_FILES_LIMIT+ assert block["ungrouped_files_total"] == over+ assert block["ungrouped_files_truncated"] is True+++async def test_a_range_hands_the_core_what_each_commit_touched(tmp_path, monkeypatch):+ """Which files moved together across the range is the strongest link there is."""+ import subprocess++ from repowise.core.analysis import independent_changes as core++ repo = tmp_path / "repo"+ repo.mkdir()++ def _git(*args: str) -> None:+ subprocess.run(+ ["git", "-c", "[email protected]", "-c", "user.name=T", *args],+ cwd=repo,+ check=True,+ capture_output=True,+ )++ _git("init", "-b", "main")+ for i, files in enumerate([["a.py", "b.py"], ["c.py"]]):+ for name in files:+ (repo / name).write_text(f"{name} {i}\n", encoding="utf-8")+ _git("add", "-A")+ _git("commit", "-m", f"c{i}")++ ctx = await _ctx(tmp_path / "index", ["a.py", "b.py", "c.py"], [])+ ctx.path = str(repo)+ seen: dict = {}++ async def _capture(session, repo_id, changed_files, *, commit_sets=()):+ seen["commit_sets"] = [set(s) for s in commit_sets]+ return None++ monkeypatch.setattr(core, "independent_changes", _capture)+ await _independent_changes_block(+ ctx, {"a.py": {1}, "b.py": {1}, "c.py": {1}}, _collector(tmp_path), "HEAD~1..HEAD"+ )++ assert seen["commit_sets"] == [{"c.py"}]+++async def test_get_change_risk_carries_the_split_end_to_end(tmp_path, monkeypatch):+ """Two changed files the index links to nothing become two changes."""+ import subprocess++ from repowise.server.mcp_server import tool_change_risk as module++ repo = tmp_path / "repo"+ repo.mkdir()++ def _git(*args: str) -> None:+ subprocess.run(+ ["git", "-c", "[email protected]", "-c", "user.name=T", *args],+ cwd=repo,+ check=True,+ capture_output=True,+ )++ _git("init", "-b", "main")+ for name in ("a.py", "b.py"):+ (repo / name).write_text("start" + chr(10), encoding="utf-8")+ _git("add", "-A")+ _git("commit", "-m", "base")+ for name in ("a.py", "b.py"):+ (repo / name).write_text("changed" + chr(10), encoding="utf-8")+ _git("add", "-A")+ _git("commit", "-m", "two unrelated edits")++ # Each changed file is linked to a file outside the diff and to nothing+ # inside it, which is what makes them two changes rather than two unknowns.+ ctx = await _ctx(+ tmp_path / "index",+ ["a.py", "b.py", "lib/one.py", "lib/two.py"],+ [("a.py", "lib/one.py"), ("b.py", "lib/two.py")],+ )++ async def _context(_: str | None) -> SimpleNamespace:+ return SimpleNamespace(path=str(repo), session_factory=ctx.session_factory)++ monkeypatch.setattr(module, "_resolve_repo_context", _context)+ payload = await module.get_change_risk("HEAD", baseline=0)++ split = payload["change_shape"]["independent_changes"]+ assert split["count"] == 2+ assert sorted(g["files"] for g in split["groups"]) == [["a.py"], ["b.py"]]+++def test_change_shape_carries_the_block_only_when_there_is_one():+ payload = {"score": 3.0, "classification": "moderate"}+ assert "independent_changes" not in _change_shape(payload, {})+ shape = _change_shape(payload, {}, {"count": 2})+ assert shape["independent_changes"] == {"count": 2}diff --git a/website/cli-reference.md b/website/cli-reference.mdindex 8aad8fa67..39f1dbb45 100644--- a/website/cli-reference.md+++ b/website/cli-reference.md@@ -562,6 +562,47 @@ repowise risk main..HEAD # score a branch / PR rangerepowise risk --ext .ts,.tsx```+With a readable index the command also prints whether the diff is one change or+several: the changed files grouped by the links the index holds plus, for a+`base..head` range, the files each commit touched. Only indexed, non-test source+files a resolver can link are grouped; docs, config, data and tests are always+printed under `Left out of the grouping:`. Each group names its files and the+files that alone hold it together, and a closing `Basis:` line says what was+checked. Silent when the diff is one change, and it carries no score.++---++## `overlap`++Which other open branches edit the files this change edits. Git answers it, so it+works with no index; an index orders the shared files and adds the files history+pairs with them. Every row states its basis in words, `same file` or+`co-change pair, N of M commits`. No score. Branches stacked on the current one+are skipped, as are noise paths and dependency manifests.++```bash+repowise overlap [OPTIONS]+```++### Options++| Flag | Type | Default | Description |+|------|------|---------|-------------|+| `--base` | ref | trunk | Base ref both sides are diffed against (`origin/HEAD`, else `main` or `master`) |+| `--branch` | ref | HEAD | The change to compare |+| `--path` | path | cwd | Git repository path |+| `--limit` | int | 50 | How many branches to diff, newest committer date first |+| `--format` | choice | table | `table` or `json` |++### Examples++```bash+repowise overlap # who else is editing what you are editing+repowise overlap --base main --limit 100 # a wider scan against an explicit base+```++When nothing overlaps, the command prints one line saying so with the scan counts.+---## `security`