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(report): estate sections for health and churn per repo, the riskiest seams and where to start (#4561)
Raghav Chamadiyaec50d45892d5
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.mdindex 214ad4593..f624f7860 100644--- a/docs/architecture/workspace.md+++ b/docs/architecture/workspace.md@@ -177,7 +177,7 @@ both ways).| `breaking_change` | `contract_links`, previous and new stores | Provider breaks with the consumer files they reach || `test_impact.analyze_workspace_test_impact` | `contract_links`, each consumer repo's test reachability from the link's `consumer_symbol_id` | Tests to run, unresolved rows with reasons || `diagnostics.build_diagnostics` | Contracts, `contract_links`, extraction stats | Counts, unmatched reasons, weak links, coverage |-| `report estate` (`report/sections/estate_*.py`) | `system_graph.json`, `contracts.json`, `graph_evidence`, the architecture metrics | Estate summary, system map and architecture, contracts and dangling calls |+| `report estate` (`report/sections/estate_*.py`) | `system_graph.json`, `contracts.json`, `graph_evidence`, the architecture metrics, `workspace.db` health, each member index | Estate summary, system map and architecture, contracts and dangling calls, health and churn per repo, riskiest seams (`seams.rank_seams`), where to start |Service links reach the graph views (cycles, metrics, conformance, blast radius).Breaking changes, test impact and diagnostics read `contract_links` only, since adiff --git a/docs/layers/REPORTS.md b/docs/layers/REPORTS.mdindex 83fe25850..21ad0aef0 100644--- a/docs/layers/REPORTS.md+++ b/docs/layers/REPORTS.md@@ -10,7 +10,7 @@ opens offline.| `report assessment` | Component posture, hotspots, bus factor, dead code by tier, test reach, contracts, governing decisions, provenance coverage and what moved in the last quarter | Acquirer, board, platform lead, migration committee || `report changes` | Every change merged in a period: components and owning teams, review record, reaching tests, policy verdict, provenance and later outcome, with a period summary | Auditor reviewing change management (SOC 2 CC8.1, ISO 27001 A.8.32, PCI DSS 6.5) || `report inventory` | Components with owner teams, languages, entry points and the packages they import | Software inventory review (PCI DSS 6.3.2) |-| `report estate` | A workspace's repos and services, the system map and architecture with the evidence behind them, contracts and the calls that reached no provider | Platform lead, acquirer, team taking over an estate |+| `report estate` | A workspace's repos and services, the system map and architecture with the evidence behind them, contracts and the calls that reached no provider, health and churn per repo, the riskiest seams and where to start | Platform lead, acquirer, team taking over an estate |```bashrepowise report assessment --format html --out assessment.htmldiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 955928791..7fbf9fc54 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1553,6 +1553,9 @@ repowise report estate --format html --out estate.html| `estate-summary` | Repos configured, indexed, read and in the graph; contracts read at an older commit than the index; services; the graph's evidence state with its reasons | `measured`; services `inferred`; `unresolved` when evidence is insufficient || `estate-map` | Service dependency edges by kind with strategy and confidence; architecture score, propagation cost, core, cycles, roles | `inferred`; score `unresolved` when evidence is insufficient, and named partial beside it when partial || `estate-contracts` | Providers, consumers and links by type and repo pair; HTTP calls read, located but unresolved, and files calling out through code no extractor reads; each consumer that matched no provider in another service (consumer, file, target, contract id), capped with a count of the rest; calls to public hosts counted apart | `measured` |+| `estate-health` | Per repo: average file health from the workspace store's newest snapshot; churn hotspots (recent commit churn, not defects) and bug magnets from each index, with their top files; a repo with fewer than 2 commits indexed is listed as not measured | `measured`; `unresolved` without the store or any history |+| `estate-seams` | Service pairs joined by an edge, ranked by link confidence x reach x (1 + co-change no contract explains), every input shown per pair; a fixed heuristic, not a calibrated risk | `inferred`; `unresolved` when evidence is insufficient |+| `estate-start` | Services ranked by how many others a change to them reaches; per repo, the most central production files with the least written documentation | `inferred` |Outside a workspace it exits 1. A section is a `Section(scope="workspace", report="estate")` in`repowise/core/report/sections/`; it runs once with a `WorkspaceReportContext`.diff --git a/packages/cli/src/repowise/cli/commands/report_estate_cmd.py b/packages/cli/src/repowise/cli/commands/report_estate_cmd.pyindex 5fea58905..202d1d1f0 100644--- a/packages/cli/src/repowise/cli/commands/report_estate_cmd.py+++ b/packages/cli/src/repowise/cli/commands/report_estate_cmd.py@@ -31,7 +31,8 @@ from repowise.cli.helpers import (@click.option("--out", "out_path", type=click.Path(dir_okay=False), help="Write to this file.")def estate_command(path: str | None, wanted: str | None, fmt: str, out_path: str | None) -> None:"""Estate report: repositories and services, the system map and architecture with- the evidence behind them, contracts and the calls that reached no provider."""+ the evidence behind them, contracts and the calls that reached no provider, health+ and churn per repo, the riskiest seams and where to start."""from repowise.cli._helpers.target import WorkspaceNotFoundfrom repowise.cli.commands.report_assessment_cmd import (_build,diff --git a/packages/core/src/repowise/core/analysis/knowledge_map.py b/packages/core/src/repowise/core/analysis/knowledge_map.pyindex 42f72ada0..78e7d6bd4 100644--- a/packages/core/src/repowise/core/analysis/knowledge_map.py+++ b/packages/core/src/repowise/core/analysis/knowledge_map.py@@ -18,6 +18,14 @@ SILO_OWNER_PCT = 0.8#: Onboarding targets returned per repository.ONBOARDING_LIMIT = 10+#: Graph node ids that are not a file a reader can open: an import outside the+#: repo, a framework entry, or a symbol (``path::Name``).+_NOT_A_FILE = ("external:", "framework:")+++def _is_file(node_id: str) -> bool:+ return not node_id.startswith(_NOT_A_FILE) and "::" not in node_id+def rank_silos(git_rows: Iterable[Any]) -> list[dict[str, Any]]:"""Files whose primary owner holds more than :data:`SILO_OWNER_PCT`, riskiest first.@@ -58,7 +66,8 @@ def onboarding_targets("""High-centrality files carrying the least documentation.``file_nodes`` are non-test graph nodes with ``node_id`` and ``pagerank``;- nodes without a positive pagerank are skipped. ``doc_size`` maps a path to+ nodes without a positive pagerank, and nodes that are not files (external+ imports, framework entries, symbols), are skipped. ``doc_size`` maps a path toits file page's word count, or any measure that ranks like one; 0 or absentwhen undocumented. Rows report it as ``doc_words``, so a caller ranking by aproxy must swap exact words in. Sorted by size, then pagerank descending;@@ -71,7 +80,7 @@ def onboarding_targets("doc_words": doc_size.get(field(n, "node_id"), 0),}for n in file_nodes- if (field(n, "pagerank") or 0.0) > 0.0+ if (field(n, "pagerank") or 0.0) > 0.0 and _is_file(field(n, "node_id"))]candidates.sort(key=lambda c: (c["doc_words"], -c["pagerank"]))return candidates[:limit]diff --git a/packages/core/src/repowise/core/report/model.py b/packages/core/src/repowise/core/report/model.pyindex 410139c7b..9e385aec9 100644--- a/packages/core/src/repowise/core/report/model.py+++ b/packages/core/src/repowise/core/report/model.py@@ -219,6 +219,49 @@ class WorkspaceReportContext:graph = self.system_graph()return self._load("evidence", lambda: graph_evidence(graph) if graph else None)+ def repo_health(self) -> dict[str, dict[str, Any]] | None:+ """Each member's stored health headline from ``workspace.db``, ``None`` without one."""+ from repowise.core.workspace.store import read_repo_health, store_path++ return self._load("health", lambda: read_repo_health(store_path(self.ws_root)))++ async def each_index(+ self, key: str, read: Callable[[Any, str], Awaitable[Any]]+ ) -> dict[str, Any]:+ """``alias -> await read(session, repository_id)`` over every member with an+ index, cached under *key*. A member whose index cannot be opened or read+ maps to the exception instead, so a section can say which one it missed.+ """+ if key in self._cache:+ return self._cache[key]+ from repowise.core.workspace.registry import open_repo_db, repo_db_path+ from repowise.core.workspace.repo_index import checkout_repository++ out: dict[str, Any] = {}+ for entry in self.config().repos:+ root = (self.ws_root / entry.path).resolve()+ if not repo_db_path(root).is_file():+ continue+ try:+ engine, sessions = await open_repo_db(root)+ except Exception as exc: # one unreadable index must not lose the rest+ out[entry.alias] = exc+ continue+ try:+ async with sessions() as session:+ repo = await checkout_repository(session, root)+ out[entry.alias] = (+ await read(session, repo.id)+ if repo is not None+ else LookupError("the index holds no repository row")+ )+ except Exception as exc:+ out[entry.alias] = exc+ finally:+ await engine.dispose()+ self._cache[key] = out+ return out+#: Where a section runs: once per repository, or once per workspace.SCOPES = ("repo", "workspace")diff --git a/packages/core/src/repowise/core/report/sections/_estate.py b/packages/core/src/repowise/core/report/sections/_estate.pyindex 7287266cd..5fd6157e3 100644--- a/packages/core/src/repowise/core/report/sections/_estate.py+++ b/packages/core/src/repowise/core/report/sections/_estate.py@@ -1,10 +1,11 @@-"""What the estate sections share: the missing-artifact item and the evidence wording."""+"""What the estate sections share: the missing-artifact item, the evidence wording+and the git facts read from each member's index."""from __future__ import annotationsfrom typing import Any-from repowise.core.report.model import check+from repowise.core.report.model import WorkspaceReportContext, checkdef missing_graph(name: str, method: str) -> list[dict[str, Any]]:@@ -31,3 +32,72 @@ def evidence_note(evidence: Any) -> str:return ""codes = ", ".join(r.code.replace("_", " ") for r in evidence.reasons)return f"; {evidence.state} evidence ({codes})"+++#: Files listed per repo for a churn or bug-magnet roll-up; the rest are counted.+TOP_FILES = 5+++async def _git_facts(session: Any, repository_id: str) -> dict[str, Any]:+ from sqlalchemy import func, select++ from repowise.core.persistence.crud import code_file_rows+ from repowise.core.persistence.models import GitCommit, GitMetadata++ commits, newest = (+ await session.execute(+ select(func.count(), func.max(GitCommit.committed_at)).where(+ GitCommit.repository_id == repository_id+ )+ )+ ).one()+ files, with_fixes = (+ await session.execute(+ select(func.count(), func.count().filter(GitMetadata.prior_defect_count > 0)).where(+ code_file_rows(repository_id)+ )+ )+ ).one()+ hot = (+ await session.execute(+ select(GitMetadata.file_path)+ .where(code_file_rows(repository_id), GitMetadata.is_hotspot.is_(True))+ .order_by(GitMetadata.temporal_hotspot_score.desc(), GitMetadata.file_path)+ )+ ).scalars().all()+ magnets = (+ await session.execute(+ select(GitMetadata.file_path, GitMetadata.prior_defect_count, GitMetadata.last_fix_at)+ .where(code_file_rows(repository_id), GitMetadata.bug_magnet.is_(True))+ .order_by(GitMetadata.fix_mass.desc(), GitMetadata.file_path)+ )+ ).all()+ return {+ "commits": int(commits or 0),+ "newest_commit": newest.date().isoformat() if newest else None,+ "files": int(files or 0),+ "files_with_fixes": int(with_fixes or 0),+ "hotspots": len(hot),+ "top_hotspots": list(hot[:TOP_FILES]),+ "bug_magnets": len(magnets),+ "top_bug_magnets": [+ {+ "file": path,+ "fixes": int(fixes or 0),+ "last_fix": last.date().isoformat() if last else None,+ }+ for path, fixes, last in magnets[:TOP_FILES]+ ],+ }+++async def git_history(ctx: WorkspaceReportContext) -> dict[str, Any]:+ """``alias -> git facts`` per indexed member (an exception when its index was unreadable):+ commits indexed and the newest one's date, code files, churn hotspots and bug magnets+ with their top files."""+ return await ctx.each_index("git_history", _git_facts)+++def unread(rows: dict[str, Any]) -> list[str]:+ """Members whose index could not be read, as ``alias (error)``."""+ return [f"{a} ({type(v).__name__})" for a, v in sorted(rows.items()) if isinstance(v, Exception)]diff --git a/packages/core/src/repowise/core/report/sections/estate_health.py b/packages/core/src/repowise/core/report/sections/estate_health.pynew file mode 100644index 000000000..7ffd25523--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/estate_health.py@@ -0,0 +1,243 @@+"""Health, churn hotspots and bug magnets, one row per repository of the estate."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ Section,+ WorkspaceReportContext,+ capped,+ capped_names,+ check,+ report_sections,+)+from repowise.core.report.sections._estate import git_history, unread+from repowise.core.workspace.seams import MIN_HISTORY_COMMITS++_HEALTH = (+ "each repo's newest health snapshot as the workspace store (.repowise-workspace/"+ "workspace.db) holds it: the average file health on the 1-10 scale 'repowise health' uses"+)+_CHURN = (+ "files each index's git history flags as hotspots: the top quarter by recent commit "+ "churn that also clears the activity floors. Churn only; it says nothing about defects"+)+_MAGNETS = (+ "files each index's git history flags as bug magnets: bug-fix commits in the trailing "+ "defect window (about six months), recent fixes weighted most, past the three-fix trigger"+)+++def _alias(entry: dict[str, Any]) -> str:+ return entry.get("alias") or entry.get("name")+++def _health(ctx: WorkspaceReportContext) -> dict[str, Any]:+ stored = ctx.repo_health()+ if stored is None:+ return check(+ "health",+ reason=(+ "the workspace store is missing or unreadable; 'repowise update --workspace' "+ "writes it"+ ),+ method=_HEALTH,+ basis="unresolved",+ )+ rows, not_indexed, absent, none = [], [], [], []+ for entry in ctx.repos:+ alias = _alias(entry)+ if not entry.get("indexed", True):+ not_indexed.append(alias)+ continue+ row = stored.get(alias)+ if row is None:+ absent.append(alias)+ continue+ if not row["health"] or row["health"].get("average_health") is None:+ none.append(alias)+ continue+ h = row["health"]+ rows.append(+ {+ "repo": alias,+ "average_health": h["average_health"],+ "maintainability_average": h.get("maintainability_average"),+ "hotspot_health": h.get("hotspot_health"),+ "taken_at": h.get("taken_at"),+ "store_commit": row["indexed_commit"],+ "index_commit": entry.get("head_commit"),+ }+ )+ rows.sort(key=lambda r: (r["average_health"], r["repo"]))+ lines = []+ for r in rows:+ line = f"{r['repo']}: {r['average_health']:g} average file health"+ if r["hotspot_health"] is not None:+ line += f", {r['hotspot_health']:g} over its churn hotspots"+ line += f" (snapshot {(r['taken_at'] or 'undated')[:10]}"+ stale = r["store_commit"] and r["index_commit"] and r["store_commit"] != r["index_commit"]+ line += f"; stored at {r['store_commit'][:12]}, index now at {r['index_commit'][:12]})" if stale else ")"+ lines.append(line)+ details = capped(lines)+ if none:+ details.append(f"indexed with no health snapshot: {capped_names(none)}")+ if absent:+ details.append(+ f"not in the workspace store yet ('repowise update --workspace' adds them): "+ f"{capped_names(absent)}"+ )+ if not_indexed:+ details.append(f"not indexed: {capped_names(not_indexed)}")+ if rows:+ low, high = rows[0], rows[-1]+ reason = (+ f"{len(rows)} of {len(ctx.repos)} repo(s) carry a health snapshot; average file "+ f"health runs from {low['average_health']:g} ({low['repo']}) to "+ f"{high['average_health']:g} ({high['repo']}) out of 10"+ )+ else:+ reason = f"none of {len(ctx.repos)} repo(s) carries a stored health snapshot"+ return check(+ "health",+ reason=reason,+ details=details,+ method=_HEALTH + "; repos are not averaged together, each reads on its own",+ basis="measured" if rows else "unresolved",+ data={"repositories": rows},+ )+++def _split(ctx: WorkspaceReportContext, history: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:+ """``(alias -> facts with enough history, notes on the rest)``."""+ measured: dict[str, Any] = {}+ short, missing = [], []+ for entry in ctx.repos:+ alias = _alias(entry)+ facts = history.get(alias)+ if facts is None or isinstance(facts, Exception):+ if entry.get("indexed", True) and facts is None:+ missing.append(alias)+ continue+ if facts["commits"] < MIN_HISTORY_COMMITS:+ short.append(f"{alias} ({facts['commits']})")+ else:+ measured[alias] = facts+ notes = []+ if short:+ notes.append(+ f"too little history to measure (commits indexed): {capped_names(short)}"+ )+ if missing:+ notes.append(f"no git facts in the index: {capped_names(missing)}")+ if failed := unread(history):+ notes.append(f"index could not be read: {capped_names(failed)}")+ not_indexed = [_alias(e) for e in ctx.repos if not e.get("indexed", True)]+ if not_indexed:+ notes.append(f"not indexed: {capped_names(not_indexed)}")+ return measured, notes+++def _dated(aliases: list[str], facts: dict[str, Any]) -> list[str]:+ """``alias (newest commit <date>)``: a quiet repo may simply have stopped changing."""+ return [+ f"{a} (newest commit {facts[a]['newest_commit']})" if facts[a]["newest_commit"] else a+ for a in aliases+ ]+++def _top(files: list[str], total: int) -> str:+ rest = total - len(files)+ return ", ".join(files) + (f" and {rest} more" if rest > 0 else "")+++def _churn(ctx: WorkspaceReportContext, history: dict[str, Any]) -> dict[str, Any]:+ measured, notes = _split(ctx, history)+ hot = sorted(+ ((a, f) for a, f in measured.items() if f["hotspots"]), key=lambda kv: (-kv[1]["hotspots"], kv[0])+ )+ total = sum(f["hotspots"] for f in measured.values())+ lines = [+ f"{a}: {f['hotspots']} of {f['files']} code file(s), {f['commits']} commits indexed: "+ f"{_top(f['top_hotspots'], f['hotspots'])}"+ for a, f in hot+ ]+ quiet = sorted(a for a, f in measured.items() if not f["hotspots"])+ if quiet:+ lines.append(f"history read, no churn hotspot: {capped_names(_dated(quiet, measured))}")+ return check(+ "churn-hotspots",+ reason=(+ f"{total} churn hotspot file(s) across {len(hot)} of {len(measured)} repo(s) with "+ f"enough history; a hotspot here means frequent recent change, not a defect"+ if measured+ else "no repo holds enough indexed history to measure churn"+ ),+ details=[*capped(lines), *notes],+ method=_CHURN,+ basis="measured" if measured else "unresolved",+ data={"repositories": {a: _row(f, "hotspots") for a, f in sorted(measured.items())}},+ )+++def _magnets(ctx: WorkspaceReportContext, history: dict[str, Any]) -> dict[str, Any]:+ measured, notes = _split(ctx, history)+ top = sorted(+ ((a, m) for a, f in measured.items() for m in f["top_bug_magnets"]),+ key=lambda am: (-am[1]["fixes"], am[0], am[1]["file"]),+ )+ total = sum(f["bug_magnets"] for f in measured.values())+ lines = [+ f"{a} {m['file']}: {m['fixes']} bug-fix commit(s) in the window"+ + (f", last {m['last_fix']}" if m["last_fix"] else "")+ for a, m in top+ ]+ clean = sorted(a for a, f in measured.items() if not f["files_with_fixes"])+ if clean:+ lines.append(+ f"history read, no bug-fix commit in the window: {capped_names(_dated(clean, measured))}"+ )+ with_magnets = sum(1 for f in measured.values() if f["bug_magnets"])+ return check(+ "bug-magnets",+ reason=(+ f"{total} bug magnet file(s) across {with_magnets} of {len(measured)} repo(s) with "+ f"enough history"+ if measured+ else "no repo holds enough indexed history to count bug-fix commits"+ ),+ details=[*capped(lines), *notes],+ method=_MAGNETS + "; at most five files listed per repo, each repo's total is in data",+ basis="measured" if measured else "unresolved",+ data={"repositories": {a: _row(f, "bug_magnets") for a, f in sorted(measured.items())}},+ )+++def _row(facts: dict[str, Any], kind: str) -> dict[str, Any]:+ return {+ "commits": facts["commits"],+ "newest_commit": facts["newest_commit"],+ "files": facts["files"],+ kind: facts[kind],+ f"top_{kind}": facts[f"top_{kind}"],+ **({"files_with_fixes": facts["files_with_fixes"]} if kind == "bug_magnets" else {}),+ }+++async def collect(ctx: WorkspaceReportContext) -> list[dict[str, Any]]:+ history = await git_history(ctx)+ return [_health(ctx), _churn(ctx, history), _magnets(ctx, history)]+++report_sections.register(+ "estate-health",+ Section(+ title="Health, churn and bug magnets by repository",+ summary="Each repo's stored health, its churn hotspots and its bug magnets, side by side.",+ collect=collect,+ order=40,+ report="estate",+ scope="workspace",+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/estate_seams.py b/packages/core/src/repowise/core/report/sections/estate_seams.pynew file mode 100644index 000000000..dc17161c5--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/estate_seams.py@@ -0,0 +1,119 @@+"""The riskiest seams between services, ranked by a stated heuristic with its inputs shown."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ Section,+ WorkspaceReportContext,+ capped,+ capped_names,+ check,+ report_sections,+)+from repowise.core.report.sections._estate import (+ evidence_note,+ git_history,+ missing_graph,+ unread,+)++_METHOD = (+ "a heuristic over the stored system graph, not a calibrated risk: each pair of services "+ "joined by an edge scores link confidence x reach (services a change to the depended-on "+ "side reaches, at most 3 hops) x (1 + co-change no contract explains); a pair joined by "+ "co-change alone scores co-change x reach. Co-change is read from the graph's co-change "+ "edges; for a pair no contract links, it is not measured when a repo's index holds fewer "+ "than 2 commits, and that pair's score is then a floor"+)+#: Seams listed in the text; the JSON keeps every one.+_LISTED = 10+++def _line(seam: Any) -> str:+ a, b = seam.services+ score = f"{seam.score:g}" if seam.score is not None else "not scored"+ if seam.score_is_floor:+ score = f"at least {score}"+ parts = [f"{a} {seam.direction} {b}: seam score {score}"]+ parts.append(+ f"{'+'.join(seam.kinds)}, confidence {seam.confidence:.2f}" if seam.kinds else "no structural edge"+ )+ parts.append(f"reach {seam.reach} service(s)")+ if seam.declared and seam.co_change:+ parts.append(f"co-change {seam.co_change:.2f}, behind a contract")+ elif seam.declared:+ parts.append("behind a contract")+ elif seam.co_change is None:+ parts.append("co-change not measured")+ elif seam.co_change:+ parts.append(f"co-change {seam.co_change:.2f} with no contract")+ else:+ parts.append("no co-change")+ return ", ".join(parts)+++async def collect(ctx: WorkspaceReportContext) -> list[dict[str, Any]]:+ from repowise.core.workspace.seams import rank_seams++ graph = ctx.system_graph()+ if graph is None:+ return missing_graph("seams", _METHOD)+ evidence = ctx.evidence()+ if evidence.state == "insufficient":+ return [+ check(+ "seams",+ reason=f"not determined: {evidence.summary}",+ method=_METHOD,+ basis="unresolved",+ )+ ]+ history = await git_history(ctx)+ commits = {a: f["commits"] for a, f in history.items() if not isinstance(f, Exception)}+ seams = rank_seams(graph, commits)+ unmeasured = sorted({note.split(": ", 1)[1] for s in seams for note in s.missing})+ details = capped([_line(s) for s in seams], limit=_LISTED)+ if unmeasured:+ details.append(f"co-change not measured: {capped_names(unmeasured)}")+ if failed := unread(history):+ details.append(f"index could not be read, history unknown: {', '.join(failed)}")+ open_pairs = [s for s in seams if not s.declared]+ measured = [s for s in open_pairs if s.co_change is not None]+ hidden = sum(1 for s in measured if s.co_change)+ co_change = (+ f"{len(open_pairs)} with no contract between them, of which {hidden} change together "+ f"(co-change measured for {len(measured)})"+ if open_pairs+ else "every one behind a contract"+ )+ return [+ check(+ "seams",+ reason=(+ f"{len(seams)} service pair(s) joined by an edge, {co_change}; ranked by a "+ "fixed heuristic, highest first" + evidence_note(evidence)+ if seams+ else "no edge joins two services, so there is no seam to rank"+ + evidence_note(evidence)+ ),+ details=details,+ method=_METHOD,+ basis="inferred",+ data={"seams": [s.to_dict() for s in seams]},+ )+ ]+++report_sections.register(+ "estate-seams",+ Section(+ title="Riskiest seams",+ summary="Service pairs ranked by link confidence, reach and co-change no contract explains.",+ collect=collect,+ order=50,+ report="estate",+ scope="workspace",+ ),+)diff --git a/packages/core/src/repowise/core/report/sections/estate_start.py b/packages/core/src/repowise/core/report/sections/estate_start.pynew file mode 100644index 000000000..eeef59bec--- /dev/null+++ b/packages/core/src/repowise/core/report/sections/estate_start.py@@ -0,0 +1,190 @@+"""Where a team new to the estate starts: the services most others depend on, and in+each repo the central files with the least documentation."""++from __future__ import annotations++from typing import Any++from repowise.core.report.model import (+ Section,+ WorkspaceReportContext,+ capped,+ capped_names,+ check,+ report_sections,+)+from repowise.core.report.sections._estate import evidence_note, missing_graph, unread++_SERVICES = (+ "the stored system graph: for each service, the services a change to it reaches over "+ "structural edges (at most 3 hops), as the blast radius walks them"+)+_FILES = (+ "each index's file graph: production code files the health index scored (as the health "+ "and git indexes class them), ranked by PageRank centrality within their own repo, the "+ "least documented first (words on the file's written page; a page rendered from the code "+ "alone counts as none), as the knowledge map's onboarding targets; centrality is not "+ "compared across repos"+)+#: Files listed per repo in the text; the JSON keeps the full shortlist.+_PER_REPO = 3+++async def _targets(session: Any, repository_id: str) -> list[dict[str, Any]]:+ """The knowledge map's onboarding targets for one repo, words counted exactly."""+ from sqlalchemy import func, select++ from repowise.core.analysis.knowledge_map import onboarding_targets+ from repowise.core.persistence.crud import code_file_rows+ from repowise.core.persistence.models import GitMetadata, GraphNode, HealthFileMetric, Page++ # Production code only, as the health index classed it, and a code file to+ # the git index: a Dockerfile, a README or a vendored library is central in+ # the graph and undocumented by nature, and would lead the list.+ nodes = (+ await session.execute(+ select(GraphNode.node_id, GraphNode.pagerank)+ .join(+ HealthFileMetric,+ (HealthFileMetric.repository_id == GraphNode.repository_id)+ & (HealthFileMetric.file_path == GraphNode.node_id),+ )+ .join(GitMetadata, GitMetadata.file_path == GraphNode.node_id)+ .where(+ code_file_rows(repository_id),+ GraphNode.repository_id == repository_id,+ GraphNode.node_type == "file",+ GraphNode.is_test.is_(False),+ GraphNode.pagerank > 0.0,+ HealthFileMetric.code_origin == "production",+ )+ )+ ).all()+ # Written pages only: a page rendered from the code alone documents nothing+ # the file does not say. Character length ranks like words; exact words are+ # read for the shortlist only.+ written = (+ Page.repository_id == repository_id,+ Page.page_type == "file_page",+ Page.provider_name != "template",+ )+ sizes = {+ path: int(n or 0)+ for path, n in await session.execute(+ select(Page.target_path, func.length(Page.content)).where(*written)+ )+ }+ shortlist = onboarding_targets(nodes, sizes)+ documented = [c["path"] for c in shortlist if c["doc_words"] > 0]+ words: dict[str, int] = {}+ if documented:+ words = {+ path: len((content or "").split())+ for path, content in await session.execute(+ select(Page.target_path, Page.content).where(+ *written, Page.target_path.in_(documented)+ )+ )+ }+ ranked = [{**c, "doc_words": words.get(c["path"], 0)} for c in shortlist]+ # Re-ranked on exact words, the fold's own key: characters only made the cut.+ return sorted(ranked, key=lambda c: (c["doc_words"], -c["pagerank"]))+++def _services(ctx: WorkspaceReportContext, graph: Any, reach: dict[str, int]) -> dict[str, Any]:+ evidence = ctx.evidence()+ if evidence.state == "insufficient":+ return check(+ "start-services",+ reason=f"not determined: {evidence.summary}",+ method=_SERVICES,+ basis="unresolved",+ )+ names = {n.id: n for n in graph.nodes}+ ranked = sorted((n for n in reach if reach[n]), key=lambda n: (-reach[n], n))+ leaves = sorted(n for n in reach if not reach[n])+ details = capped(+ [f"{n} ({names[n].kind}): a change reaches {reach[n]} service(s)" for n in ranked], limit=10+ )+ if leaves:+ details.append(f"no other service depends on: {capped_names(leaves)}")+ return check(+ "start-services",+ reason=(+ f"{len(ranked)} of {len(reach)} service(s) have other services depending on them; "+ "read the widest first" + evidence_note(evidence)+ if ranked+ else "no service has another depending on it" + evidence_note(evidence)+ ),+ details=details,+ method=_SERVICES,+ basis="inferred",+ data={"reach": dict(sorted(reach.items()))},+ )+++def _files(+ ctx: WorkspaceReportContext, targets: dict[str, Any], repo_reach: dict[str, int]+) -> dict[str, Any]:+ read = {a: t for a, t in targets.items() if not isinstance(t, Exception)}+ order = sorted(read, key=lambda a: (-repo_reach.get(a, 0), a))+ lines = []+ for alias in order:+ files = read[alias][:_PER_REPO]+ if files:+ lines.append(+ f"{alias}: "+ + ", ".join(+ f"{f['path']} ({f['doc_words']} doc words)" if f["doc_words"] else f"{f['path']} (undocumented)"+ for f in files+ )+ )+ empty = [a for a in order if not read[a]]+ details = capped(lines)+ if empty:+ details.append(f"no ranked file in the index: {capped_names(empty)}")+ if failed := unread(targets):+ details.append(f"index could not be read: {capped_names(failed)}")+ not_indexed = [e.get("alias") or e.get("name") for e in ctx.repos if not e.get("indexed", True)]+ if not_indexed:+ details.append(f"not indexed: {capped_names(not_indexed)}")+ return check(+ "start-files",+ reason=(+ f"the most central, least documented files of {len(lines)} repo(s), "+ "repos ordered by how far a change to their services reaches"+ if lines+ else "no repo index holds a ranked file graph"+ ),+ details=details,+ method=_FILES,+ basis="inferred" if lines else "unresolved",+ data={"repositories": {a: read[a] for a in order}},+ )+++async def collect(ctx: WorkspaceReportContext) -> list[dict[str, Any]]:+ from repowise.core.workspace.seams import service_reach++ graph = ctx.system_graph()+ if graph is None:+ return missing_graph("start-services", _SERVICES)+ reach = service_reach(graph)+ repo_reach: dict[str, int] = {}+ for node in graph.nodes:+ repo_reach[node.repo] = max(repo_reach.get(node.repo, 0), reach[node.id])+ targets = await ctx.each_index("onboarding_targets", _targets)+ return [_services(ctx, graph, reach), _files(ctx, targets, repo_reach)]+++report_sections.register(+ "estate-start",+ Section(+ title="Where to start",+ summary="The services most others depend on, then each repo's central, least documented files.",+ collect=collect,+ order=60,+ report="estate",+ scope="workspace",+ ),+)diff --git a/packages/core/src/repowise/core/workspace/seams.py b/packages/core/src/repowise/core/workspace/seams.pynew file mode 100644index 000000000..a6f7c4c2a--- /dev/null+++ b/packages/core/src/repowise/core/workspace/seams.py@@ -0,0 +1,177 @@+"""Riskiest seams: service pairs ranked by a fixed heuristic over the system graph.++A seam is a pair of services joined by a cross-service edge: a structural+dependency (a contract link or a package dependency) or co-change in git+history. Its score is ``confidence x reach x (1 + undeclared co-change)``:++* confidence: the strongest structural edge's link confidence (0-1).+* reach: services a change to the depended-on side reaches over structural+ edges (the blast radius walk, :data:`.blast_radius.DEFAULT_MAX_DEPTH` hops),+ the other side of the pair included; at least 1.+* undeclared co-change: the pair's co-change strength (0-1) when no contract+ links them (a package dependency is not a contract); 0 when a contract does,+ or when history was read and no co-change was found; ``None`` when either+ repo holds too little indexed history to show co-change. The score then+ leaves the factor out and is a floor (:attr:`Seam.score_is_floor`), never+ a zero.++A pair joined by co-change alone scores ``co-change x reach``.++Uncalibrated: the score orders pairs to look at first; it is not a probability+and not comparable across workspaces. Pure; the caller hands in the graph and+how many commits each repo's index holds.+"""++from __future__ import annotations++from collections.abc import Mapping+from dataclasses import dataclass, field+from typing import Any++from repowise.core.workspace.blast_radius import cross_repo_blast_radius+from repowise.core.workspace.system_graph import SystemGraph++#: Commits a repo's index must hold before co-change can show in its history:+#: the miner needs two working sessions, so one commit can never show it.+MIN_HISTORY_COMMITS = 2+++@dataclass+class Seam:+ """One service pair and every input its score was computed from."""++ services: tuple[str, str] # node ids; the depended-on side second when there is one+ direction: str # "->" (first depends on second), "<->" (both ways) or "~" (co-change only)+ kinds: list[str] # structural edge kinds between the pair+ confidence: float | None # strongest structural link; None when co-change only+ reach: int+ co_change: float | None # co-change strength; None when it could not be measured+ declared: bool # a contract links the pair+ score: float | None # None when the pair has no input left to score+ #: Why an input is missing, e.g. "co-change not measured: cart has 1 commit indexed".+ missing: list[str] = field(default_factory=list)++ @property+ def undeclared(self) -> float | None:+ """Co-change no contract explains: the score's third factor."""+ if self.declared:+ return 0.0 # a contract explains whatever co-change there is+ return self.co_change++ @property+ def score_is_floor(self) -> bool:+ """The score left out a factor that could only raise it (co-change not measured)."""+ return self.score is not None and self.confidence is not None and self.undeclared is None++ def to_dict(self) -> dict[str, Any]:+ return {+ "services": list(self.services),+ "direction": self.direction,+ "kinds": self.kinds,+ "confidence": self.confidence,+ "reach": self.reach,+ "co_change": self.co_change,+ "declared": self.declared,+ "undeclared_co_change": self.undeclared,+ "score": self.score,+ "score_is_floor": self.score_is_floor,+ "missing": self.missing,+ }+++def service_reach(graph: SystemGraph) -> dict[str, int]:+ """``node id -> services a change to it reaches`` over structural edges only."""+ return {+ n.id: cross_repo_blast_radius(graph, [n.id], include_behavioral=False).total_impacted+ for n in graph.nodes+ }+++def rank_seams(+ graph: SystemGraph,+ commits: Mapping[str, int] | None = None,+ *,+ reach: Mapping[str, int] | None = None,+) -> list[Seam]:+ """Every cross-service pair in *graph*, highest score first.++ *commits* maps a repo alias to the commits its index holds; a repo absent+ from it (or *commits* None) has unknown history. *reach* is+ :func:`service_reach`, passed when the caller already computed it.+ """+ reach = reach if reach is not None else service_reach(graph)+ repo_of = {n.id: n.repo for n in graph.nodes}+ pairs: dict[frozenset[str], dict[str, Any]] = {}+ for e in graph.edges:+ if e.source == e.target:+ continue+ p = pairs.setdefault(+ frozenset((e.source, e.target)), {"deps": set(), "kinds": set(), "conf": None, "cc": None}+ )+ if e.structural:+ p["deps"].add((e.source, e.target))+ p["kinds"].add(e.kind)+ p["conf"] = max(p["conf"] or 0.0, e.confidence)+ else:+ p["cc"] = max(p["cc"] or 0.0, e.confidence)+ seams = [_seam(key, p, reach, repo_of, commits) for key, p in pairs.items()]+ return sorted(+ seams, key=lambda s: (s.score is None, -(s.score or 0.0), -s.reach, s.services)+ )+++def _seam(+ key: frozenset[str],+ p: dict[str, Any],+ reach: Mapping[str, int],+ repo_of: Mapping[str, str],+ commits: Mapping[str, int] | None,+) -> Seam:+ deps: set[tuple[str, str]] = p["deps"]+ if len(deps) == 1:+ (consumer, provider), direction = next(iter(deps)), "->"+ depended = [provider]+ else:+ consumer, provider = sorted(key)+ direction = "<->" if deps else "~"+ depended = [consumer, provider]+ seam_reach = max(1, *(reach.get(n, 0) for n in depended))+ missing: list[str] = []+ co_change = p["cc"]+ declared = any(k != "package" for k in p["kinds"])+ if co_change is None and not declared:+ short = dict.fromkeys(+ repo+ for repo in (repo_of.get(consumer, consumer), repo_of.get(provider, provider))+ if (commits or {}).get(repo, 0) < MIN_HISTORY_COMMITS+ )+ missing.extend(f"co-change not measured: {r} has {_commits(commits, r)}" for r in short)+ if not short:+ co_change = 0.0+ seam = Seam(+ services=(consumer, provider),+ direction=direction,+ kinds=sorted(p["kinds"]),+ confidence=p["conf"],+ reach=seam_reach,+ co_change=co_change,+ declared=declared,+ score=None,+ missing=missing,+ )+ undeclared = seam.undeclared+ if seam.confidence is not None:+ seam.score = round(seam.confidence * seam_reach * (1.0 + (undeclared or 0.0)), 2)+ elif undeclared is not None:+ seam.score = round(undeclared * seam_reach, 2)+ return seam+++def _commits(commits: Mapping[str, int] | None, repo: str) -> str:+ if commits is None or repo not in commits:+ return "no indexed history"+ n = commits[repo]+ return f"{n} commit{'' if n == 1 else 's'} indexed"+++__all__ = ["MIN_HISTORY_COMMITS", "Seam", "rank_seams", "service_reach"]diff --git a/packages/core/src/repowise/core/workspace/store.py b/packages/core/src/repowise/core/workspace/store.pyindex 91af11fed..157096e35 100644--- a/packages/core/src/repowise/core/workspace/store.py+++ b/packages/core/src/repowise/core/workspace/store.py@@ -518,3 +518,32 @@ def lookup_symbols(discard(path)return Nonereturn out, components+++def read_repo_health(path: Path) -> dict[str, dict[str, Any]] | None:+ """``alias -> {indexed, indexed_commit, health, error}`` from the store's ``repos`` rows.++ ``health`` is the stored headline of the repo's newest health snapshot, or+ None when it has none. None when the store is absent, unreadable or of+ another schema version; read only, so a reader never rebuilds it.+ """+ try:+ uri = f"{Path(path).resolve().as_uri()}?mode=ro"+ with closing(sqlite3.connect(uri, uri=True)) as conn:+ conn.execute(f"PRAGMA busy_timeout={_BUSY_TIMEOUT_MS}")+ if conn.execute("PRAGMA user_version").fetchone()[0] != SCHEMA_VERSION:+ return None+ rows = conn.execute(+ "SELECT alias, indexed, indexed_commit, health_json, error FROM repos"+ ).fetchall()+ except sqlite3.Error:+ return None+ return {+ alias: {+ "indexed": bool(indexed),+ "indexed_commit": commit,+ "health": json.loads(health) if health else None,+ "error": error,+ }+ for alias, indexed, commit, health, error in rows+ }diff --git a/tests/unit/analysis/test_knowledge_map_folds.py b/tests/unit/analysis/test_knowledge_map_folds.pyindex 2c35e8c94..ce9b4fe79 100644--- a/tests/unit/analysis/test_knowledge_map_folds.py+++ b/tests/unit/analysis/test_knowledge_map_folds.py@@ -58,3 +58,13 @@ def test_onboarding_targets_skip_unranked_nodes_and_cap() -> None:assert len(everything) == 12tail = everything[-2:]assert [t["path"] for t in tail] == ["f10.py", "f11.py"]+++def test_onboarding_targets_skip_nodes_that_are_not_files() -> None:+ nodes = [+ {"node_id": "external:os", "pagerank": 0.9},+ {"node_id": "framework:spring", "pagerank": 0.8},+ {"node_id": "app.py::App", "pagerank": 0.7},+ {"node_id": "app.py", "pagerank": 0.1},+ ]+ assert [t["path"] for t in onboarding_targets(nodes, {})] == ["app.py"]diff --git a/tests/unit/core/test_report_estate.py b/tests/unit/core/test_report_estate.pyindex 60423afd4..8b864152f 100644--- a/tests/unit/core/test_report_estate.py+++ b/tests/unit/core/test_report_estate.py@@ -182,7 +182,7 @@ def test_assemble_appends_workspace_sections_after_the_repos():async def test_without_a_system_graph_every_estate_section_is_unresolved(tmp_path):found = await _estate(WorkspaceReportContext(tmp_path))items = [c for checks in found.values() for c in checks.values()]- assert len(found) == 3 and all(c["basis"] == "unresolved" for c in items)+ assert len(found) == 6 and all(c["basis"] == "unresolved" for c in items)assert "repowise update --workspace" in items[0]["reason"]@@ -283,7 +283,14 @@ def test_cli_estate_reads_the_stored_artifacts(tmp_path: Path, monkeypatch) -> Nassert result.exit_code == 0, result.outputdoc = json.loads(out.read_text(encoding="utf-8"))assert doc["kind"] == "estate" and doc["scope"] == {"kind": "workspace", "name": "ws"}- assert [s["id"] for s in doc["sections"]] == ["estate-summary", "estate-map", "estate-contracts"]+ assert [s["id"] for s in doc["sections"]] == [+ "estate-summary",+ "estate-map",+ "estate-contracts",+ "estate-health",+ "estate-seams",+ "estate-start",+ ]assert all(s["repo"] is None for s in doc["sections"])assert [r.get("indexed", True) for r in doc["repos"]] == [False] * 4 # no member is indexedmd = CliRunner().invoke(cli, ["report", "estate", str(ws), "--sections", "estate-map"])diff --git a/tests/unit/core/test_report_estate_rollups.py b/tests/unit/core/test_report_estate_rollups.pynew file mode 100644index 000000000..180fdacfc--- /dev/null+++ b/tests/unit/core/test_report_estate_rollups.py@@ -0,0 +1,235 @@+"""`report estate` roll-ups: health, churn hotspots and bug magnets per repo, the+riskiest seams and where to start, read from each member's index and the workspace store."""++from __future__ import annotations++from datetime import UTC, datetime+from pathlib import Path++from repowise.core.persistence.models import (+ GitCommit,+ GitMetadata,+ GraphNode,+ HealthFileMetric,+ HealthSnapshot,+ Page,+ Repository,+)+from repowise.core.report.build import available_sections, collect_workspace+from repowise.core.report.model import WorkspaceReportContext+from repowise.core.workspace.config import WorkspaceConfig+from repowise.core.workspace.registry import open_repo_db+from repowise.core.workspace.store import refresh_workspace_store+from repowise.core.workspace.system_graph import (+ SystemEdge,+ SystemGraph,+ SystemNode,+ save_system_graph,+)++_DAY = datetime(2026, 10, 1, tzinfo=UTC)+++async def _index(repo: Path, alias: str, *, commits: int, health: float | None, files: dict) -> None:+ """A real ``wiki.db``: *commits* commits, and per file ``(pagerank, hotspot, magnet,+ fixes, origin, written_words)``."""+ (repo / ".repowise").mkdir(parents=True, exist_ok=True)+ engine, factory = await open_repo_db(repo)+ rid = f"repo-{alias}"+ async with factory() as session:+ session.add(Repository(id=rid, name=alias, url="", local_path=str(repo)))+ await session.flush()+ for i in range(commits):+ session.add(GitCommit(repository_id=rid, sha=f"{i:040d}", committed_at=_DAY))+ for path, (rank, hot, magnet, fixes, origin, words) in files.items():+ session.add(GraphNode(repository_id=rid, node_id=path, node_type="file", pagerank=rank))+ session.add(+ GitMetadata(+ repository_id=rid,+ file_path=path,+ is_hotspot=hot,+ temporal_hotspot_score=rank,+ bug_magnet=magnet,+ prior_defect_count=fixes,+ fix_mass=float(fixes),+ last_fix_at=_DAY if fixes else None,+ history_only=origin == "config",+ )+ )+ session.add(+ HealthFileMetric(repository_id=rid, file_path=path, code_origin=origin, score=8.0)+ )+ if words is not None:+ session.add(+ Page(+ id=f"file_page:{path}",+ repository_id=rid,+ page_type="file_page",+ title=path,+ content=" ".join(["word"] * words),+ target_path=path,+ source_hash="h",+ model_name="m" if words else "",+ provider_name="anthropic" if words else "template",+ generation_level=2,+ created_at=_DAY,+ updated_at=_DAY,+ )+ )+ # a node that is not a file a reader opens+ session.add(GraphNode(repository_id=rid, node_id="external:os", node_type="file", pagerank=0.9))+ if health is not None:+ session.add(HealthSnapshot(repository_id=rid, average_health=health))+ await session.commit()+ await engine.dispose()+++def _node(repo: str) -> SystemNode:+ return SystemNode(id=repo, repo=repo, service_path=None, name=repo)+++def _edge(src: str, dst: str, kind: str = "http", confidence: float = 0.9) -> SystemEdge:+ return SystemEdge(+ id=f"{src}->{dst}:{kind}",+ source=src,+ target=dst,+ kind=kind,+ match_type="exact",+ confidence=confidence,+ weight=1,+ structural=kind != "co_change",+ strategy="exact_id",+ )+++async def _estate(tmp_path: Path) -> dict[str, dict]:+ """web -> api -> lib (package, co-changing); old has one commit; docs is not indexed."""+ ws = tmp_path / "ws"+ await _index(+ ws / "web",+ "web",+ commits=30,+ health=6.5,+ files={+ "app.py": (0.5, True, True, 4, "production", None),+ "util.py": (0.2, True, False, 1, "production", 120),+ "vendor.js": (0.9, False, False, 0, "vendored", None),+ "Dockerfile": (0.8, False, False, 0, "config", None),+ },+ )+ await _index(+ ws / "api", "api", commits=12, health=9.1, files={"main.go": (0.4, False, False, 0, "production", 0)}+ )+ await _index(+ ws / "lib", "lib", commits=8, health=None, files={"lib.cs": (0.3, False, False, 0, "production", None)}+ )+ await _index(+ ws / "old", "old", commits=1, health=8.0, files={"old.py": (0.3, False, False, 0, "production", None)}+ )+ (ws / "docs").mkdir()+ (ws / ".repowise-workspace.yaml").write_text(+ "version: 1\nrepos:\n"+ + "".join(f" - path: {r}\n alias: {r}\n" for r in ("web", "api", "lib", "old", "docs")),+ encoding="utf-8",+ )+ save_system_graph(+ SystemGraph(+ generated_at="2026-10-01T00:00:00+00:00",+ nodes=[_node(r) for r in ("web", "api", "lib", "old")],+ edges=[+ _edge("web", "api"),+ _edge("api", "lib", "package", 1.0),+ _edge("api", "lib", "co_change", 0.5),+ _edge("old", "api", "grpc", 0.75),+ ],+ ),+ ws,+ )+ await refresh_workspace_store(WorkspaceConfig.load(ws), ws)+ ctx = WorkspaceReportContext(+ ws,+ repos=[+ {"alias": r, "head_commit": "a" * 40} for r in ("web", "api", "lib", "old")+ ]+ + [{"alias": "docs", "name": "docs", "indexed": False}],+ )+ wanted = [s for s in available_sections("estate") if s[0] in ("estate-health", "estate-seams", "estate-start")]+ sections = await collect_workspace(ctx, wanted)+ return {s["id"]: {c["name"]: c for c in s["checks"]} for s in sections}+++async def test_estate_rollups_read_each_index_and_the_store(tmp_path):+ found = await _estate(tmp_path)++ health = found["estate-health"]["health"]+ assert health["reason"].startswith("3 of 5 repo(s) carry a health snapshot")+ assert health["details"][0].startswith("web: 6.5 average file health")+ assert "indexed with no health snapshot: lib" in health["details"]+ assert "not indexed: docs" in health["details"]++ churn = found["estate-health"]["churn-hotspots"]+ assert churn["reason"].startswith("2 churn hotspot file(s) across 1 of 3 repo(s)")+ assert "not a defect" in churn["reason"]+ assert churn["details"][0] == "web: 2 of 3 code file(s), 30 commits indexed: app.py, util.py"+ assert "too little history to measure (commits indexed): old (1)" in churn["details"]+ assert any(d.startswith("history read, no churn hotspot: api (newest commit") for d in churn["details"])++ magnets = found["estate-health"]["bug-magnets"]+ assert magnets["reason"].startswith("1 bug magnet file(s) across 1 of 3 repo(s)")+ assert magnets["details"][0] == "web app.py: 4 bug-fix commit(s) in the window, last 2026-10-01"++ seams = found["estate-seams"]["seams"]+ assert seams["basis"] == "inferred" and "heuristic" in seams["method"]+ assert seams["reason"].startswith(+ "3 service pair(s) joined by an edge, 1 with no contract between them, of which 1 "+ "change together (co-change measured for 1)"+ )+ assert seams["details"][0].startswith(+ "api -> lib: seam score 4.5, package, confidence 1.00, reach 3 service(s), "+ "co-change 0.50 with no contract"+ )+ # old -> api is a grpc contract: its short history does not touch its score+ assert not any("not measured" in d for d in seams["details"])++ services = found["estate-start"]["start-services"]+ assert services["details"][0] == "lib (service): a change reaches 3 service(s)"+ files = found["estate-start"]["start-files"]+ # production code only, undocumented first; a template page counts as none+ assert files["details"][0] == "lib: lib.cs (undocumented)"+ assert "web: app.py (undocumented), util.py (120 doc words)" in files["details"]+ assert "api: main.go (undocumented)" in files["details"]+ assert all("external:" not in d and "vendor.js" not in d and "Dockerfile" not in d for d in files["details"])+++async def test_without_history_or_store_each_input_says_so(tmp_path):+ ws = tmp_path / "ws"+ await _index(ws / "one", "one", commits=1, health=None, files={"a.py": (0.1, False, False, 0, "production", None)})+ (ws / ".repowise-workspace.yaml").write_text(+ "version: 1\nrepos:\n - path: one\n alias: one\n", encoding="utf-8"+ )+ ctx = WorkspaceReportContext(ws, repos=[{"alias": "one", "head_commit": "a" * 40}])+ (section,) = await collect_workspace(+ ctx, [s for s in available_sections("estate") if s[0] == "estate-health"]+ )+ checks = {c["name"]: c for c in section["checks"]}+ assert checks["health"]["basis"] == "unresolved"+ assert "workspace store is missing" in checks["health"]["reason"]+ assert checks["churn-hotspots"]["score"] == -1+ assert checks["churn-hotspots"]["reason"] == "no repo holds enough indexed history to measure churn"+++async def test_start_files_rank_on_exact_words_not_page_length(tmp_path):+ from repowise.core.report.sections.estate_start import _targets++ repo = tmp_path / "web"+ files = {"long.py": (0.5, False, False, 0, "production", 1), "short.py": (0.4, False, False, 0, "production", 1)}+ await _index(repo, "web", commits=2, health=None, files=files)+ engine, factory = await open_repo_db(repo)+ async with factory() as session:+ # long.py: more characters, fewer words; short.py: fewer characters, more words+ (await session.get(Page, "file_page:long.py")).content = "x" * 40+ (await session.get(Page, "file_page:short.py")).content = "a b c d e"+ await session.commit()+ rows = await _targets(session, "repo-web")+ await engine.dispose()+ assert [(r["path"], r["doc_words"]) for r in rows] == [("long.py", 1), ("short.py", 5)]diff --git a/tests/unit/workspace/test_seams.py b/tests/unit/workspace/test_seams.pynew file mode 100644index 000000000..a629c05d9--- /dev/null+++ b/tests/unit/workspace/test_seams.py@@ -0,0 +1,78 @@+"""Riskiest seams: the fixed heuristic over the system graph, its inputs kept per pair."""++from __future__ import annotations++from repowise.core.workspace.seams import rank_seams, service_reach+from repowise.core.workspace.system_graph import SystemEdge, SystemGraph, SystemNode+++def _node(repo: str) -> SystemNode:+ return SystemNode(id=repo, repo=repo, service_path=None, name=repo)+++def _edge(src: str, dst: str, kind: str = "http", confidence: float = 0.8) -> SystemEdge:+ return SystemEdge(+ id=f"{src}->{dst}:{kind}",+ source=src,+ target=dst,+ kind=kind,+ match_type="inferred" if kind == "co_change" else "exact",+ confidence=confidence,+ weight=1,+ structural=kind != "co_change",+ )+++def _graph(*edges: SystemEdge) -> SystemGraph:+ repos = sorted({r for e in edges for r in (e.source, e.target)})+ return SystemGraph(nodes=[_node(r) for r in repos], edges=list(edges))+++HISTORY = {"web": 40, "api": 40, "db": 40, "lib": 40, "ops": 40}+++def test_reach_counts_every_service_a_change_reaches_structurally():+ graph = _graph(_edge("web", "api"), _edge("api", "db"), _edge("ops", "db", "co_change", 0.9))+ assert service_reach(graph) == {"api": 1, "db": 2, "ops": 0, "web": 0}+++def test_score_is_confidence_times_reach_times_undeclared_co_change():+ graph = _graph(+ _edge("web", "api"), # contract, co-changes: declared, so co-change adds nothing+ _edge("web", "api", "co_change", 0.5),+ _edge("api", "lib", "package", 1.0), # no contract, co-changes: undeclared+ _edge("api", "lib", "co_change", 0.4),+ _edge("ops", "db", "co_change", 0.6), # co-change alone+ )+ by_pair = {s.services: s for s in rank_seams(graph, HISTORY)}+ lib = by_pair[("api", "lib")]+ assert (lib.confidence, lib.reach, lib.undeclared, lib.score) == (1.0, 2, 0.4, 2.8)+ api = by_pair[("web", "api")]+ assert api.declared and api.co_change == 0.5 and api.undeclared == 0.0+ assert api.score == 0.8 # 0.8 x reach 1 x (1 + 0)+ ops = by_pair[("db", "ops")]+ assert (ops.direction, ops.confidence, ops.score) == ("~", None, 0.6)+ assert rank_seams(graph, HISTORY)[0].services == ("api", "lib")+++def test_short_history_is_shown_as_not_measured_not_scored_as_zero():+ graph = _graph(_edge("web", "api", "package", 1.0), _edge("api", "db"), _edge("ops", "db"))+ commits = {"web": 1, "api": 30, "db": 30, "ops": 1}+ seams = {s.services: s for s in rank_seams(graph, commits)}+ short = seams[("web", "api")] # no contract: co-change would count, and is unknown+ assert short.co_change is None and short.undeclared is None+ assert short.missing == ["co-change not measured: web has 1 commit indexed"]+ assert short.score == 1.0 and short.score_is_floor # the missing factor can only raise it+ declared = seams[("ops", "db")] # a contract: co-change cannot change its score+ assert declared.undeclared == 0.0 and not declared.missing and not declared.score_is_floor+ assert seams[("api", "db")].co_change is None and not seams[("api", "db")].missing+ unknown = rank_seams(graph, None)+ assert all("no indexed history" in m for s in unknown for m in s.missing)+++def test_both_ways_takes_the_wider_reach():+ graph = _graph(_edge("web", "api"), _edge("api", "web", "event"), _edge("ops", "api"))+ (pair,) = [s for s in rank_seams(graph, HISTORY) if set(s.services) == {"web", "api"}]+ assert pair.direction == "<->" and pair.kinds == ["event", "http"]+ assert pair.reach == 2 # a change to api reaches web and ops+ assert pair.to_dict()["undeclared_co_change"] == 0.0