Skip to content

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

fix(dead-code): every reader in a workspace withdraws what the cross-repo cut withdraws (#4383)

Raghav Chamadiya1379ae11f526
diff --git a/docs/architecture/dead-code.md b/docs/architecture/dead-code.md
index 68687dad5..f646ca2c5 100644
--- a/docs/architecture/dead-code.md
+++ b/docs/architecture/dead-code.md
@@ -179,8 +179,9 @@ built from the `risk_factors.py` constants. The TypeScript mirror is
`DEAD_CODE_CONFIDENCE` in `packages/types/src/dead-code.ts`, so CLI, web and
MCP tier identically.
-`serve_findings` is the one read the MCP tool, the REST routes and the CLI
-share: it applies `cross_repo_cut` to each stored row, then the filters, and
+`serve_findings` is the one read every surface shares (MCP, REST, CLI, and
+the file, attention, actions, related-work, graph, chat, export and report
+readers): it applies `cross_repo_cut` to each stored row, then the filters, and
tiering reads the result. A file another repo's contract link points at gets
confidence `* 0.3`. Cross-repo co-change partners, or an `unused_export` in a
repo other repos depend on as a package, keep the confidence. Each adds a
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.md
index 1c3d57558..9dc92d0da 100644
--- a/docs/layers/DEAD_CODE.md
+++ b/docs/layers/DEAD_CODE.md
@@ -189,7 +189,11 @@ tier its new confidence names, so one cut below `0.4` is hidden by the default
floor. The dashboard adds the note to the finding's evidence. `repo="all"` merges every
workspace repo and tags each finding with its alias. The CLI analyzes one repo
per run (the primary repo unless `--repo <alias>`), and `--no-workspace` skips
-the cut. See [WORKSPACES.md](../scale/WORKSPACES.md) for how cross-repo data is built.
+the cut. The file page, Overview's attention list, Do next (web, `repowise next`,
+`get_overview`), related work, the code graph, the chat dataset, `repowise export
+--full` and the assessment report read the same cut. Fix first and plan annotations
+are built per repo before the workspace pass, so they read stored values. See
+[WORKSPACES.md](../scale/WORKSPACES.md) for how cross-repo data is built.
## Accuracy and limits
diff --git a/packages/cli/src/repowise/cli/_helpers/target.py b/packages/cli/src/repowise/cli/_helpers/target.py
index 8d331fda1..68b8f3f32 100644
--- a/packages/cli/src/repowise/cli/_helpers/target.py
+++ b/packages/cli/src/repowise/cli/_helpers/target.py
@@ -327,3 +327,25 @@ def resolve_command_target(
reason="no workspace nearby",
auto_detected=False,
)
+
+
+def cross_repo_cut_inputs(repo_path: Path, ws_root: Path | None) -> dict[str, Any]:
+ """``lookup`` and ``alias`` for the dead-code cross-repo cut (``serve_findings``)
+ on *repo_path*, a member of the workspace at *ws_root*; both ``None`` when
+ there is no workspace or the repo is not one of its members."""
+ none: dict[str, Any] = {"lookup": None, "alias": None}
+ if ws_root is None:
+ return none
+ import yaml
+
+ from repowise.core.workspace.config import WorkspaceConfig
+
+ try:
+ alias = WorkspaceConfig.load(ws_root).alias_for_path(ws_root, repo_path)
+ except (OSError, ValueError, yaml.YAMLError): # an unreadable config cuts nothing
+ return none
+ if alias is None:
+ return none
+ from repowise.server.mcp_server._enrichment import CrossRepoEnricher
+
+ return {"lookup": CrossRepoEnricher.for_workspace(ws_root), "alias": alias}
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index defa41a22..7dd56a12c 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -12,6 +12,7 @@ from rich.table import Table
from repowise.cli.helpers import (
console,
+ cross_repo_cut_inputs,
get_head_commit,
load_config,
load_state,
@@ -156,27 +157,6 @@ def _analyze_live(repo_path: Path, config: dict, notices: Any) -> DeadCodeReport
return analyzer.analyze(config)
-def _cross_repo_inputs(
- target: Any, repo_path: Path, no_workspace: bool
-) -> tuple[CrossRepoLookup | None, str | None]:
- """The workspace data and alias the cross-repo cut reads for *repo_path*."""
- if no_workspace or target.ws_root is None:
- return None, None
- from repowise.core.workspace.config import WorkspaceConfig
-
- ws_config = target.ws_config or WorkspaceConfig.load(target.ws_root)
- resolved = repo_path.resolve()
- alias = next(
- (e.alias for e in ws_config.repos if (target.ws_root / e.path).resolve() == resolved),
- None,
- )
- if alias is None:
- return None, None
- from repowise.server.mcp_server._enrichment import CrossRepoEnricher
-
- return CrossRepoEnricher.for_workspace(target.ws_root), alias
-
-
def _with_cut(served: ServedFinding) -> DeadCodeFindingData:
if served.cross_repo_note is None:
return served.row
@@ -352,9 +332,8 @@ def dead_code_command(
report = _analyze_live(repo_path, config, notices)
else:
_notice_stored(repo_path, notices)
- report, touched = _cut_cross_repo(
- report, *_cross_repo_inputs(target, repo_path, no_workspace), min_confidence
- )
+ cut = cross_repo_cut_inputs(repo_path, None if no_workspace else target.ws_root)
+ report, touched = _cut_cross_repo(report, cut["lookup"], cut["alias"], min_confidence)
if touched:
notices.print(
f"[dim]{touched} finding(s) not cleanup-ready: another workspace repo may use "
diff --git a/packages/cli/src/repowise/cli/commands/export_cmd.py b/packages/cli/src/repowise/cli/commands/export_cmd.py
index 6e4f17fc2..8c70d3c95 100644
--- a/packages/cli/src/repowise/cli/commands/export_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/export_cmd.py
@@ -10,6 +10,7 @@ from rich.progress import Progress
from repowise.cli.helpers import (
console,
+ cross_repo_cut_inputs,
ensure_repowise_dir,
get_db_url_for_repo,
resolve_repo_path,
@@ -186,15 +187,19 @@ def export_command(
DeadCodeFinding.repository_id == repo.id
)
)
+ from repowise.cli._helpers.paths import find_workspace_root
+ from repowise.core.analysis.dead_code.serving import is_safe, serve_findings
+
+ cut = cross_repo_cut_inputs(repo_path, find_workspace_root(repo_path))
extra_data["dead_code"] = [
{
"file_path": f.file_path,
"symbol_name": f.symbol_name,
"kind": f.kind,
"confidence": f.confidence,
- "safe_to_delete": f.safe_to_delete,
+ "safe_to_delete": is_safe(f),
}
- for f in dc.scalars().all()
+ for f in serve_findings(list(dc.scalars().all()), **cut)
]
# Git metadata (hotspots)
diff --git a/packages/cli/src/repowise/cli/commands/next_cmd.py b/packages/cli/src/repowise/cli/commands/next_cmd.py
index 860b5b13d..4a6b82ea7 100644
--- a/packages/cli/src/repowise/cli/commands/next_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/next_cmd.py
@@ -11,7 +11,13 @@ from typing import Any
import click
-from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async
+from repowise.cli.helpers import (
+ console,
+ cross_repo_cut_inputs,
+ repo_index_session,
+ resolve_command_target,
+ run_async,
+)
from repowise.cli.output import (
emit_json,
format_option,
@@ -29,13 +35,15 @@ _TIER_COLOUR = {"act_now": "red", "plan": "yellow", "improve_signal": "cyan"}
async def _read_view(root: Path) -> dict[str, Any] | None:
"""The actions view for *root*, or ``None`` when there is no index to read."""
+ from repowise.cli._helpers.paths import find_workspace_root
from repowise.core.persistence.crud.analysis.actions import load_actions_view
async with repo_index_session(root) as opened:
if opened is None:
return None
session, repo_id = opened
- return await load_actions_view(session, repo_id)
+ cut = cross_repo_cut_inputs(root, find_workspace_root(root))
+ return await load_actions_view(session, repo_id, **cut)
def load_view(root: Path) -> dict[str, Any] | None:
diff --git a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
index 20a68420c..ae08fbed1 100644
--- a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
@@ -13,6 +13,7 @@ from typing import Any
import click
from repowise.cli.helpers import (
+ cross_repo_cut_inputs,
err_console,
repo_index_session,
resolve_command_target,
@@ -31,9 +32,17 @@ def _targets(target: Any) -> list[tuple[str | None, Path]]:
async def _build(
- repos: list[tuple[str | None, Path]], sections: list, scope: dict, **options: Any
+ repos: list[tuple[str | None, Path]],
+ sections: list,
+ scope: dict,
+ *,
+ ws_root: Path | None = None,
+ **options: Any,
) -> dict:
- """The document over *repos*; *options* go to each :class:`ReportContext`."""
+ """The document over *repos*; *options* go to each :class:`ReportContext`.
+
+ Members of the workspace at *ws_root* read dead code with its cross-repo cut.
+ """
from repowise.core.persistence.models import Repository
from repowise.core.report.build import assemble, collect_repo
from repowise.core.report.model import ReportContext
@@ -57,6 +66,7 @@ async def _build(
root,
alias=alias,
head_commit=repo.head_commit if repo else None,
+ cross_repo=cross_repo_cut_inputs(root, ws_root),
**options,
)
parts.append(await collect_repo(ctx, sections))
@@ -159,5 +169,5 @@ def assessment_command(
)
target.notice(err_console, command="report assessment")
repos, scope = _scope(target)
- document = run_async(_build(repos, sections, scope))
+ document = run_async(_build(repos, sections, scope, ws_root=target.ws_root))
_emit(render(document), fmt, out_path, document)
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 1a98d570a..c0180c21b 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -225,6 +225,9 @@ from repowise.cli._helpers.target import (
from repowise.cli._helpers.target import (
WorkspaceNotFound as WorkspaceNotFound,
)
+from repowise.cli._helpers.target import (
+ cross_repo_cut_inputs as cross_repo_cut_inputs,
+)
from repowise.cli._helpers.target import (
resolve_command_target as resolve_command_target,
)
diff --git a/packages/core/src/repowise/core/analysis/actions/build.py b/packages/core/src/repowise/core/analysis/actions/build.py
index e8af25b71..63767a20f 100644
--- a/packages/core/src/repowise/core/analysis/actions/build.py
+++ b/packages/core/src/repowise/core/analysis/actions/build.py
@@ -43,8 +43,10 @@ Row shapes (the field names are the SQL columns):
``file_path``, ``kind``, ``target``, ``raw``, ``line_number``, ``reason``,
``confidence``; ``known_paths`` is every path the repository's history held.
``dead_code``
- ``id``, ``file_path``, ``symbol_name``, ``lines``, ``kind``,
- ``safe_to_delete`` (the stored verdict), ``status`` (absent = open).
+ ``id``, ``file_path``, ``symbol_name``, ``lines``, ``kind``, ``confidence``,
+ ``safe_to_delete``, ``status`` (absent = open); in a workspace, rows from
+ ``serve_findings`` so the cross-repo cut applies. Readiness is re-derived
+ (``dead_code.serving.is_safe``), never the stored flag alone.
``decisions``
One mapping: ``stale_decisions`` (rows with ``id``, ``title``) and
``summary`` (``proposed``, ``active`` counts).
@@ -68,6 +70,7 @@ from datetime import datetime, timedelta
from typing import Any
from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
+from repowise.core.analysis.dead_code.serving import is_safe
from repowise.core.analysis.finding_registry import excluded_types, is_served
from repowise.core.analysis.health.fix_first import build_fix_first
from repowise.core.analysis.health.models import lead_and_worth, split_by_origin
@@ -489,7 +492,7 @@ def build_dead(rows: Rows, files: Mapping[str, FileFacts]) -> dict[str, Any]:
)
for r in rows
if _open(r)
- and field(r, "safe_to_delete")
+ and is_safe(r)
and is_served("dead_code", field(r, "kind"), field(r, "file_path"), skipped)
and not _is_test(field(r, "file_path"), files)
)
diff --git a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py b/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
index 98455c357..23c2db5a1 100644
--- a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
+++ b/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
@@ -249,7 +249,13 @@ DEAD_CONFIDENCE = 0.8
def dead_spans(rows: Iterable[Any]) -> dict[str, list[DeadSpan]]:
"""Sure, open dead-code findings by file: ``(symbol, start, end)``, the
- symbol ``None`` for an unreachable file."""
+ symbol ``None`` for an unreachable file.
+
+ Ceiling: stored values, without the workspace's cross-repo cut. Fix first
+ and plan annotations are built per repository, before the workspace pass
+ that writes the cut's data. Upgrade path: pass ``serve_findings`` rows once
+ those builds run with the workspace's lookup.
+ """
out: dict[str, list[DeadSpan]] = {}
for row in rows:
sure = float(field(row, "confidence") or 0.0) >= DEAD_CONFIDENCE or field(
diff --git a/packages/core/src/repowise/core/analysis/related_work.py b/packages/core/src/repowise/core/analysis/related_work.py
index 4a66d9e2d..63bf12a41 100644
--- a/packages/core/src/repowise/core/analysis/related_work.py
+++ b/packages/core/src/repowise/core/analysis/related_work.py
@@ -24,6 +24,7 @@ from dataclasses import field as dc_field
from typing import Any
from repowise.core.analysis.change_health.identity import severity_rank
+from repowise.core.analysis.dead_code.serving import is_safe
from repowise.core.analysis.health.rows import detail_map, field
#: Items kept per file per lens. The total still counts every row, so a hot
@@ -206,7 +207,7 @@ def _dead_code_item(row: Any) -> RelatedItem:
id=str(field(row, "id")),
kind=field(row, "kind"),
symbol=field(row, "symbol_name"),
- tier="safe_to_delete" if field(row, "safe_to_delete", False) else "review",
+ tier="safe_to_delete" if is_safe(row) else "review",
line=_int(field(row, "start_line")),
**_flags(row, {}),
)
diff --git a/packages/core/src/repowise/core/generation/page_generator/helpers.py b/packages/core/src/repowise/core/generation/page_generator/helpers.py
index 851e9a0be..cc013d594 100644
--- a/packages/core/src/repowise/core/generation/page_generator/helpers.py
+++ b/packages/core/src/repowise/core/generation/page_generator/helpers.py
@@ -234,6 +234,9 @@ def build_dead_code_map(dead_code_report: Any | None) -> dict[str, list[dict]]:
Kinds the finding-type registry withholds, and findings on a language it
gates for dead code, never reach a page prompt.
+
+ Ceiling: the analyzer's own values, without the workspace's cross-repo cut;
+ pages are generated per repository, before the workspace pass writes it.
"""
dead_code_by_file: dict[str, list[dict]] = {}
withheld = excluded_types()
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
index c2199b966..0b722b7c5 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
@@ -55,6 +55,7 @@ from repowise.core.analysis.actions.facts import MOCKED_ONLY_VIA, FileFacts
from repowise.core.analysis.actions.rules.code import FIX_FIRST_ACTIONS
from repowise.core.analysis.actions.rules.hygiene import PUBLIC_ENV_KIND, SECRET_KINDS
from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
+from repowise.core.analysis.dead_code.serving import CrossRepoLookup, is_safe, serve_findings
from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.test_reachability import any_tests_reaching
@@ -382,26 +383,53 @@ async def _drift(session: AsyncSession, repo_id: str) -> dict[str, Any]:
return build_drift(rows, known)
-async def _dead(session: AsyncSession, repo_id: str, files: dict[str, FileFacts]) -> dict:
- rows = (
- await session.execute(
- select(
- DeadCodeFinding.id,
- DeadCodeFinding.file_path,
- DeadCodeFinding.symbol_name,
- DeadCodeFinding.lines,
- DeadCodeFinding.kind,
- DeadCodeFinding.safe_to_delete,
- DeadCodeFinding.status,
- ).where(
- DeadCodeFinding.repository_id == repo_id,
- DeadCodeFinding.status == "open",
- DeadCodeFinding.safe_to_delete.is_(True),
- DeadCodeFinding.kind.not_in(excluded_types() | REVIEW_ONLY_KINDS),
+async def _stored_safe_dead(session: AsyncSession, repo_id: str) -> list[Any]:
+ """Open findings stored deletion-ready: a superset, since the cut only withdraws."""
+ return list(
+ (
+ await session.execute(
+ select(
+ DeadCodeFinding.id,
+ DeadCodeFinding.file_path,
+ DeadCodeFinding.symbol_name,
+ DeadCodeFinding.lines,
+ DeadCodeFinding.kind,
+ DeadCodeFinding.confidence,
+ DeadCodeFinding.safe_to_delete,
+ DeadCodeFinding.status,
+ ).where(
+ DeadCodeFinding.repository_id == repo_id,
+ DeadCodeFinding.status == "open",
+ DeadCodeFinding.safe_to_delete.is_(True),
+ DeadCodeFinding.kind.not_in(excluded_types() | REVIEW_ONLY_KINDS),
+ )
)
- )
- ).all()
- return build_dead(rows, files)
+ ).all()
+ )
+
+
+async def _dead(
+ session: AsyncSession,
+ repo_id: str,
+ files: dict[str, FileFacts],
+ lookup: CrossRepoLookup | None,
+ alias: str | None,
+) -> dict:
+ served = serve_findings(await _stored_safe_dead(session, repo_id), lookup, alias)
+ return build_dead(served, files)
+
+
+async def _stored_dead_overstated(
+ session: AsyncSession, repo_id: str, lookup: CrossRepoLookup | None, alias: str | None
+) -> bool:
+ """Whether a finding stored deletion-ready reads not safe as served.
+
+ A snapshot may count it: the snapshot is written without the workspace's
+ cut, and one built before ``build_dead`` re-derived readiness took the
+ stored flag.
+ """
+ rows = await _stored_safe_dead(session, repo_id)
+ return not all(is_safe(f) for f in serve_findings(rows, lookup, alias))
async def _decisions(session: AsyncSession, repo_id: str) -> dict[str, Any]:
@@ -461,7 +489,15 @@ async def _coverage(session: AsyncSession, repo_id: str, head_sha: str | None) -
_Reader = Callable[[], Awaitable[dict[str, Any]]]
-async def load_repo_facts(session: AsyncSession, repo_id: str) -> RepoFacts:
+async def load_repo_facts(
+ session: AsyncSession,
+ repo_id: str,
+ *,
+ lookup: CrossRepoLookup | None = None,
+ alias: str | None = None,
+) -> RepoFacts:
+ """Every store's facts; in a workspace, *lookup* and *alias* apply the
+ dead-code cross-repo cut (:func:`serve_findings`)."""
anchor, head_sha = await _anchor(session, repo_id)
since = (anchor - QUARTER) if anchor else None
week = (anchor - WEEK) if anchor else None
@@ -486,7 +522,7 @@ async def load_repo_facts(session: AsyncSession, repo_id: str) -> RepoFacts:
await read("fix_first", lambda: _fix_first(session, repo_id))
await read("security", lambda: _secrets(session, repo_id, files))
await read("doc_drift", lambda: _drift(session, repo_id))
- await read("dead_code", lambda: _dead(session, repo_id, files))
+ await read("dead_code", lambda: _dead(session, repo_id, files, lookup, alias))
await read("decisions", lambda: _decisions(session, repo_id))
await read("coverage", lambda: _coverage(session, repo_id, head_sha))
values["unavailable"] = unavailable
@@ -546,9 +582,14 @@ SNAPSHOT_KIND = "actions"
_KEY = snapshot_key(SNAPSHOT_KIND, ACTIONS_MODEL_VERSION)
-async def _ruled(session: AsyncSession, repo_id: str) -> dict[str, Any]:
+async def _ruled(
+ session: AsyncSession,
+ repo_id: str,
+ lookup: CrossRepoLookup | None = None,
+ alias: str | None = None,
+) -> dict[str, Any]:
"""The rules' output from the facts as stored now, and what could not be read."""
- facts = await load_repo_facts(session, repo_id)
+ facts = await load_repo_facts(session, repo_id, lookup=lookup, alias=alias)
return {**rule_actions(facts), "unavailable": dict(facts.unavailable)}
@@ -630,12 +671,19 @@ def _stored_view(
async def load_actions_view(
- session: AsyncSession, repo_id: str, *, now: datetime | None = None
+ session: AsyncSession,
+ repo_id: str,
+ *,
+ now: datetime | None = None,
+ lookup: CrossRepoLookup | None = None,
+ alias: str | None = None,
) -> dict[str, Any]:
"""The one entry point: the rules' output, the person's answers, and the ranked view.
The rules' output is the stored snapshot while it is current, else built
- from the facts here. Never writes.
+ from the facts here. While a finding stored deletion-ready reads not safe
+ as served (in a workspace, *lookup* and *alias* apply the cross-repo cut),
+ the view is built live instead. Never writes.
"""
try:
async with session.begin_nested():
@@ -644,12 +692,22 @@ async def load_actions_view(
states = {}
when = now or datetime.now(UTC)
stored = await read_snapshot(session, repo_id, SNAPSHOT_KIND, _KEY)
+ if stored is not None and await _stored_dead_overstated(session, repo_id, lookup, alias):
+ stored = None
view = _stored_view(stored, states, when)
if view is None:
- view = _view(await _ruled(session, repo_id), states, when)
+ view = _view(await _ruled(session, repo_id, lookup, alias), states, when)
return view
-async def load_action(session: AsyncSession, repo_id: str, action_id: str) -> Action | None:
+async def load_action(
+ session: AsyncSession,
+ repo_id: str,
+ action_id: str,
+ *,
+ lookup: CrossRepoLookup | None = None,
+ alias: str | None = None,
+) -> Action | None:
"""One action by id: the same facts the list reads, without ranking the view."""
- return find_action(await load_repo_facts(session, repo_id), action_id)
+ facts = await load_repo_facts(session, repo_id, lookup=lookup, alias=alias)
+ return find_action(facts, action_id)
diff --git a/packages/core/src/repowise/core/report/model.py b/packages/core/src/repowise/core/report/model.py
index 5c7cf515a..028e2ac62 100644
--- a/packages/core/src/repowise/core/report/model.py
+++ b/packages/core/src/repowise/core/report/model.py
@@ -134,6 +134,10 @@ class ReportContext:
#: ``None`` is the default request: the 90 days before the newest
#: indexed commit, building what is missing.
period: PeriodRequest | None = None
+ #: ``lookup`` and ``alias`` for the dead-code cross-repo cut
+ #: (``dead_code.serving.serve_findings``) when the repository is a workspace
+ #: member; ``None`` reads stored values.
+ cross_repo: dict[str, Any] | None = None
_cache: dict[str, Any] = field(default_factory=dict)
async def components(self) -> Any:
diff --git a/packages/core/src/repowise/core/report/sections/dead_code.py b/packages/core/src/repowise/core/report/sections/dead_code.py
index 7dca2b326..3529b6475 100644
--- a/packages/core/src/repowise/core/report/sections/dead_code.py
+++ b/packages/core/src/repowise/core/report/sections/dead_code.py
@@ -1,7 +1,8 @@
"""Dead code by confidence tier, with the findings gated languages hold back.
-Counts come from the stored summary every dead-code surface serves; the
-stored ``safe_to_delete`` flag is never read.
+Counts come from the stored summary every dead-code surface serves, with the
+workspace's cross-repo cut when the context carries one; the stored
+``safe_to_delete`` flag is never read.
"""
from __future__ import annotations
@@ -27,7 +28,9 @@ async def collect(ctx: ReportContext) -> list[dict[str, Any]]:
basis="unresolved",
)
]
- summary = await get_dead_code_summary(ctx.session, ctx.repository_id)
+ summary = await get_dead_code_summary(
+ ctx.session, ctx.repository_id, **(ctx.cross_repo or {})
+ )
tiers = summary["confidence_summary"]
out = [
check(
diff --git a/packages/core/src/repowise/core/workspace/config.py b/packages/core/src/repowise/core/workspace/config.py
index 1afe539dc..a486a7569 100644
--- a/packages/core/src/repowise/core/workspace/config.py
+++ b/packages/core/src/repowise/core/workspace/config.py
@@ -412,6 +412,12 @@ class WorkspaceConfig:
"""Return all repo aliases in order."""
return [r.alias for r in self.repos]
+ def alias_for_path(self, workspace_root: Path, repo_path: Path | str) -> str | None:
+ """The alias of the member checked out at *repo_path*, or ``None``."""
+ target = Path(repo_path).resolve()
+ root = Path(workspace_root)
+ return next((e.alias for e in self.repos if (root / e.path).resolve() == target), None)
+
# ------------------------------------------------------------------
# Mutation helpers
# ------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/chat_datasets/__init__.py b/packages/server/src/repowise/server/chat_datasets/__init__.py
index 7c04504ac..68f56d6ef 100644
--- a/packages/server/src/repowise/server/chat_datasets/__init__.py
+++ b/packages/server/src/repowise/server/chat_datasets/__init__.py
@@ -61,6 +61,8 @@ class LoadContext:
repo_path: str
#: Rows of another dataset, from the same cache (``files`` maps paths to packages).
rows: Callable[[str], Awaitable[list[dict[str, Any]]]]
+ #: The repository's workspace alias; ``None`` (or ``default``) outside a workspace.
+ alias: str | None = None
@dataclass(frozen=True)
@@ -210,7 +212,8 @@ async def load_rows(name: str, repo: str | None) -> DatasetRows:
ds = get_dataset(dataset)
if ds is None:
raise KeyError(dataset)
- _store(key, await ds.load(LoadContext(session, repository, repo_path, rows)))
+ context = LoadContext(session, repository, repo_path, rows, ctx.alias)
+ _store(key, await ds.load(context))
finally:
# A failed load leaves no lock behind, so the next call reads again.
_locks.pop(key, None)
diff --git a/packages/server/src/repowise/server/chat_datasets/findings.py b/packages/server/src/repowise/server/chat_datasets/findings.py
index 038cfef6b..788dadb51 100644
--- a/packages/server/src/repowise/server/chat_datasets/findings.py
+++ b/packages/server/src/repowise/server/chat_datasets/findings.py
@@ -13,6 +13,7 @@ from typing import Any
from sqlalchemy import select
+from repowise.core.analysis.dead_code.serving import is_safe, serve_findings
from repowise.core.analysis.health.rows import field
from repowise.server.chat_datasets import SUMS, DatasetField, LoadContext, register_dataset
from repowise.server.chat_datasets.files import by_path, place, unique_suffixes
@@ -111,16 +112,19 @@ def _tier(confidence: float) -> str:
)
async def load_dead_code(ctx: LoadContext) -> list[dict[str, Any]]:
from repowise.core.persistence.crud.analysis.dead_code import get_dead_code_findings
+ from repowise.server.mcp_server._helpers import _cross_repo_cut
found = await get_dead_code_findings(ctx.session, ctx.repository.id)
- return dead_code_rows(found, await ctx.rows("files"))
+ served = serve_findings(found, **_cross_repo_cut(ctx.alias))
+ return dead_code_rows(served, await ctx.rows("files"))
def dead_code_rows(found: Iterable[Any], files: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
"""The ``dead_code`` dataset's rows over open dead-code findings.
*found* holds ``file_path``, ``kind``, ``confidence``, ``symbol_name``,
- ``lines`` and ``safe_to_delete``; *files* is the ``files`` dataset's rows.
+ ``lines`` and ``safe_to_delete`` (``serve_findings`` rows, so the
+ cross-repo cut applies); *files* is the ``files`` dataset's rows.
"""
found = list(found)
index = by_path(files)
@@ -137,7 +141,7 @@ def dead_code_rows(found: Iterable[Any], files: Iterable[Mapping[str, Any]]) ->
"confidence": confidence,
"symbol": field(f, "symbol_name"),
"lines": field(f, "lines"),
- "safe_to_delete": bool(field(f, "safe_to_delete")),
+ "safe_to_delete": is_safe(f),
"path": path,
"file": index[path]["file"] if path in index else labels[path],
"package": placed[path][0],
diff --git a/packages/server/src/repowise/server/deps.py b/packages/server/src/repowise/server/deps.py
index 1039abd51..fd1fe114b 100644
--- a/packages/server/src/repowise/server/deps.py
+++ b/packages/server/src/repowise/server/deps.py
@@ -118,6 +118,16 @@ def workspace_alias_for(app_state, repo_id: str) -> str | None:
return None
+def cross_repo_cut_inputs(request: Request, repo_id: str) -> dict:
+ """``lookup`` and ``alias`` for the dead-code cross-repo cut (``serve_findings``)
+ on *repo_id*; both ``None`` outside a workspace, which cuts nothing."""
+ state = request.app.state
+ return {
+ "lookup": getattr(state, "cross_repo_enricher", None),
+ "alias": workspace_alias_for(state, repo_id),
+ }
+
+
def client_is_local(request: Request) -> bool:
"""True when the request's peer address is a loopback address.
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index f49c215f1..b4310f618 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -167,6 +167,15 @@ def _is_workspace_mode() -> bool:
return _state._registry is not None
+def _cross_repo_cut(alias: str | None) -> dict:
+ """``lookup`` and ``alias`` for the dead-code cross-repo cut
+ (``serve_findings``) on the repo *alias* names; both ``None`` outside
+ workspace mode, and an empty artifact simply cuts nothing."""
+ if not _is_workspace_mode():
+ return {"lookup": None, "alias": None}
+ return {"lookup": _state._cross_repo_enricher, "alias": alias}
+
+
async def _resolve_repo_context(repo: str | None = None) -> Any:
"""Resolve the per-repo resource context for the given ``repo`` parameter.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index 244e75295..d31c26c4e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -12,7 +12,6 @@ from repowise.core.analysis.dead_code.models import DeadCodeKind
from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE
from repowise.core.analysis.dead_code.serving import (
TIER_FLOORS,
- CrossRepoLookup,
FindingFilters,
apply_filters,
build_summary,
@@ -32,11 +31,11 @@ from repowise.core.persistence.crud import get_dead_code_findings
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GitMetadata
from repowise.core.registry import mcp_tool_registry as mcp
-from repowise.server.mcp_server import _state
from repowise.server.mcp_server._basis import call_resolution_bases
from repowise.server.mcp_server._budget import OmissionCollector
from repowise.server.mcp_server._federation import Federation, merge_findings
from repowise.server.mcp_server._helpers import (
+ _cross_repo_cut,
_get_exclude_spec,
_get_repo,
_is_workspace_mode,
@@ -49,11 +48,6 @@ from repowise.server.mcp_server._index_state import index_state_key
from repowise.server.mcp_server._meta import build_meta as _build_meta
-def _cross_repo_lookup() -> CrossRepoLookup | None:
- """The workspace's cross-repo data; an empty artifact simply cuts nothing."""
- return _state._cross_repo_enricher if _is_workspace_mode() else None
-
-
async def _get_dead_code_all_repos(
filters: FindingFilters,
limit: int,
@@ -73,7 +67,7 @@ async def _get_dead_code_all_repos(
repo_findings, withheld = filters.split_withheld(repo_findings)
repo_findings, gated = filters.split_gated(repo_findings)
git_meta_map = await _load_git_meta_map(session, repository.id, repo_findings)
- served = serve_findings(repo_findings, _cross_repo_lookup(), ctx.alias)
+ served = serve_findings(repo_findings, **_cross_repo_cut(ctx.alias))
serialized = [
serialize_finding(f, git_meta_map, repository=ctx.alias)
for f in apply_filters(served, filters)
@@ -294,12 +288,12 @@ async def get_dead_code(
git_meta_map = await _load_git_meta_map(session, repository.id, every_shown_kind)
reference_repository = ctx.alias or repository.name
- lookup = _cross_repo_lookup()
+ cut = _cross_repo_cut(ctx.alias)
if finding_id:
match = next(
(
row
- for row in serve_findings(every_shown_kind, lookup, ctx.alias)
+ for row in serve_findings(every_shown_kind, **cut)
if finding_id in {row.id, dead_code_finding_id(row, reference_repository)}
),
None,
@@ -323,7 +317,7 @@ async def get_dead_code(
),
}
- served = serve_findings(all_findings, lookup, ctx.alias)
+ served = serve_findings(all_findings, **cut)
filtered = apply_filters(served, filters)
serialized = [
serialize_finding(f, git_meta_map, repository=reference_repository) for f in filtered
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/details.py b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
index 82677332d..34c9b4a3c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/details.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
@@ -15,6 +15,7 @@ from repowise.core.persistence.crud import get_health_finding_by_public_id, get_
from repowise.core.persistence.crud.analysis.actions import load_action
from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
from repowise.core.persistence.models import HealthFinding
+from repowise.server.mcp_server._helpers import _cross_repo_cut
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server.tool_health.analysis_meta import _attach_repository_analysis_meta
from repowise.server.mcp_server.tool_health.pillars import (
@@ -56,7 +57,7 @@ async def _detail_response(
refuses two before any read.
"""
if fix_id:
- return await _fix_detail_response(session, repository, fix_id)
+ return await _fix_detail_response(session, repository, fix_id, reference_repository)
if finding_id:
return await _finding_detail_response(
session, repository, reference_repository, finding_id
@@ -167,14 +168,16 @@ _FIX_NOT_FOUND = (
)
-async def _fix_detail_response(session: Any, repository: Any, fix_id: str) -> dict[str, Any]:
+async def _fix_detail_response(
+ session: Any, repository: Any, fix_id: str, alias: str | None = None
+) -> dict[str, Any]:
"""One Fix-first item in full: action steps, verify, risk, context.
An ``act_`` id is a Do next action, the same one the REST actions route
reads: its evidence rows and commands.
"""
if fix_id.startswith(_ACTION_ID_PREFIX):
- return await _action_detail_response(session, repository, fix_id)
+ return await _action_detail_response(session, repository, fix_id, alias)
item = (await load_fix_first(session, repository.id, item_id=fix_id)).find(fix_id)
result = {
"mode": "fix_item",
@@ -192,10 +195,10 @@ async def _fix_detail_response(session: Any, repository: Any, fix_id: str) -> di
async def _action_detail_response(
- session: Any, repository: Any, action_id: str
+ session: Any, repository: Any, action_id: str, alias: str | None = None
) -> dict[str, Any]:
"""One Do next action in full, serialized as the REST actions route does."""
- action = await load_action(session, repository.id, action_id)
+ action = await load_action(session, repository.id, action_id, **_cross_repo_cut(alias))
result = {
"mode": "action",
"fix_id": action_id,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py
index 58a554f20..b1857995d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py
@@ -7,6 +7,7 @@ from typing import Any
from repowise.core.analysis.actions.engine import NEXT_ACTIONS_HEAD
from repowise.core.persistence.crud.analysis.actions import load_actions_view
+from repowise.server.mcp_server._helpers import _cross_repo_cut
logger = logging.getLogger(__name__)
@@ -68,7 +69,7 @@ def compact_actions_view(view: dict[str, Any], *, full: bool = True) -> dict[str
async def _build_next_actions(
- session: Any, repository: Any, *, full: bool = False
+ session: Any, repository: Any, *, full: bool = False, alias: str | None = None
) -> tuple[dict[str, Any], str | None]:
"""``(block, None)``, or ``({}, reason)`` when the actions could not be read.
@@ -79,7 +80,7 @@ async def _build_next_actions(
"""
try:
async with session.begin_nested():
- view = await load_actions_view(session, repository.id)
+ view = await load_actions_view(session, repository.id, **_cross_repo_cut(alias))
return compact_actions_view(view, full=full), None
except Exception as exc:
logger.warning("get_overview: next actions unavailable: %s", exc)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
index ebf51b53b..99c9b804b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
@@ -137,7 +137,14 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
result = await _repo_overview(
- session, ctx.session_factory, repository, exclude_spec, want, collector, ctx.path
+ session,
+ ctx.session_factory,
+ repository,
+ exclude_spec,
+ want,
+ collector,
+ ctx.path,
+ alias=ctx.alias,
)
if "components" in want:
result["components"] = await component_list(
@@ -173,13 +180,16 @@ async def _repo_overview(
want: set[str],
collector: OmissionCollector,
repo_root: Any = None,
+ alias: str | None = None,
) -> dict[str, Any]:
"""Every single-repo block, in payload order; empty optional blocks are left out.
Code health and the next actions are the slow reads and need nothing else
here, so each runs on its own read session while the rest is read.
"""
- slow = _slow_reads(session, session_factory, repository, full_actions="actions" in want)
+ slow = _slow_reads(
+ session, session_factory, repository, full_actions="actions" in want, alias=alias
+ )
try:
overview_page = await _load_overview_page(session, repository)
package_roots = await _package_roots(session, repository, exclude_spec)
@@ -250,11 +260,16 @@ async def _repo_overview(
def _slow_reads(
- session: Any, session_factory: Any, repository: Any, *, full_actions: bool = False
+ session: Any,
+ session_factory: Any,
+ repository: Any,
+ *,
+ full_actions: bool = False,
+ alias: str | None = None,
) -> Awaitable[Any]:
"""``(code health, next actions)``: started now on their own sessions, or,
on a store whose sessions share one connection, read later on *session*."""
- actions = functools.partial(_build_next_actions, full=full_actions)
+ actions = functools.partial(_build_next_actions, full=full_actions, alias=alias)
if not _own_connections(session_factory):
return _in_turn(session, repository, actions)
diff --git a/packages/server/src/repowise/server/routers/actions.py b/packages/server/src/repowise/server/routers/actions.py
index 1081dda23..8447d1aaa 100644
--- a/packages/server/src/repowise/server/routers/actions.py
+++ b/packages/server/src/repowise/server/routers/actions.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
-from fastapi import APIRouter, Depends, HTTPException, Path, Query
+from fastapi import APIRouter, Depends, HTTPException, Path, Query, Request
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.agent_prompts import Flavor, render_action
@@ -15,7 +15,7 @@ from repowise.core.persistence.crud.analysis.actions import (
set_action_state,
)
from repowise.core.persistence.models import Repository
-from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session, verify_api_key
from repowise.server.schemas.actions import (
ActionsResponse,
ActionStateRequest,
@@ -29,11 +29,12 @@ router = APIRouter(tags=["actions"], dependencies=[Depends(verify_api_key)])
@router.get("/api/repos/{repo_id}/actions", response_model=ActionsResponse)
async def get_actions(
repo_id: str,
+ request: Request,
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Both horizons in one response, so switching between them costs nothing."""
await _require_repo(session, repo_id)
- return await load_actions_view(session, repo_id)
+ return await load_actions_view(session, repo_id, **cross_repo_cut_inputs(request, repo_id))
async def _require_repo(session: AsyncSession, repo_id: str) -> Repository:
@@ -49,13 +50,14 @@ async def _require_repo(session: AsyncSession, repo_id: str) -> Repository:
)
async def get_action_prompt(
repo_id: str,
+ request: Request,
action_id: str = Path(..., max_length=32),
flavor: Flavor = Query("generic"),
session: AsyncSession = Depends(get_db_session),
) -> AgentPromptResponse:
"""One action as the prompt an agent starts from, worded for its harness."""
repo = await _require_repo(session, repo_id)
- action = await load_action(session, repo_id, action_id)
+ action = await load_action(session, repo_id, action_id, **cross_repo_cut_inputs(request, repo_id))
if action is None:
raise HTTPException(status_code=404, detail="No action with that id")
return AgentPromptResponse(flavor=flavor, text=render_action(action.as_dict(), flavor, repo.name))
diff --git a/packages/server/src/repowise/server/routers/code_health/related_work_routes.py b/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
index 1af99ef87..793894fa1 100644
--- a/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/related_work_routes.py
@@ -9,9 +9,10 @@ from __future__ import annotations
from typing import Any
-from fastapi import Depends, HTTPException
+from fastapi import Depends, HTTPException, Request
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.dead_code.serving import serve_findings
from repowise.core.analysis.finding_registry import GateLayer, preview_label
from repowise.core.analysis.related_work import related_work
from repowise.core.persistence import crud
@@ -19,7 +20,7 @@ from repowise.core.persistence.crud.analysis.fix_first import load_fix_first
from repowise.core.persistence.crud.analysis.performance import (
list_performance_opportunities,
)
-from repowise.server.deps import get_db_session
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session
from repowise.server.repo_paths import normalize_target_path
from repowise.server.schemas import RelatedWorkRequest, RelatedWorkResponse
@@ -73,6 +74,7 @@ def _validated(raw: list[str]) -> list[str]:
async def get_related_work(
repo_id: str,
payload: RelatedWorkRequest,
+ request: Request,
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
"""Per file, what findings, Fix first, refactoring, performance and dead
@@ -107,7 +109,7 @@ async def get_related_work(
fix_first=queue.items,
refactoring=refactoring,
performance=performance,
- dead_code=dead_code,
+ dead_code=serve_findings(dead_code, **cross_repo_cut_inputs(request, repo_id)),
).as_dict()
# One file's rows share its language, so a lens carries one label. Fix
# first mixes layers, so it carries none.
diff --git a/packages/server/src/repowise/server/routers/dead_code.py b/packages/server/src/repowise/server/routers/dead_code.py
index 9218cd239..d562b56ee 100644
--- a/packages/server/src/repowise/server/routers/dead_code.py
+++ b/packages/server/src/repowise/server/routers/dead_code.py
@@ -10,7 +10,7 @@ from repowise.core.analysis.dead_code.risk_factors import (
)
from repowise.core.analysis.dead_code.serving import FindingFilters, ServedFinding, serve_findings
from repowise.core.persistence import crud
-from repowise.server.deps import get_db_session, verify_api_key, workspace_alias_for
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session, verify_api_key
from repowise.server.routers._unverified import UnverifiedQuery
from repowise.server.schemas import (
DeadCodeAnalyzeResponse,
@@ -26,15 +26,6 @@ router = APIRouter(
)
-def _cross_repo(request: Request, repo_id: str) -> dict:
- """The cross-repo cut's inputs for *repo_id*; empty outside a workspace."""
- state = request.app.state
- return {
- "lookup": getattr(state, "cross_repo_enricher", None),
- "alias": workspace_alias_for(state, repo_id),
- }
-
-
def _response(f: ServedFinding) -> DeadCodeFindingResponse:
response = DeadCodeFindingResponse.from_orm(f)
if f.cross_repo_note:
@@ -71,7 +62,7 @@ async def list_dead_code(
filters = FindingFilters(
kind=None, safe_only=safe_only, min_confidence=min_confidence, directory=None, owner=None
)
- findings = serve_findings(rows, **_cross_repo(request, repo_id), filters=filters)
+ findings = serve_findings(rows, **cross_repo_cut_inputs(request, repo_id), filters=filters)
findings.sort(key=lambda f: -f.confidence)
return [_response(f) for f in findings[:limit]]
@@ -136,7 +127,7 @@ async def dead_code_summary(
) -> DeadCodeSummaryResponse:
"""Get aggregate dead code statistics for a repository."""
summary = await crud.get_dead_code_summary(
- session, repo_id, include_unverified=include_unverified, **_cross_repo(request, repo_id)
+ session, repo_id, include_unverified=include_unverified, **cross_repo_cut_inputs(request, repo_id)
)
analyzed_at = await dead_code_analyzed_at(session, repo_id)
return DeadCodeSummaryResponse(**summary, analyzed_at=analyzed_at)
@@ -161,4 +152,4 @@ async def resolve_finding(
if finding is None:
raise HTTPException(status_code=404, detail="Finding not found")
repo_id = finding.repository_id
- return _response(serve_findings([finding], **_cross_repo(request, repo_id))[0])
+ return _response(serve_findings([finding], **cross_repo_cut_inputs(request, repo_id))[0])
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index 8140355eb..2bef632e9 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -14,11 +14,11 @@ import bisect
import json
from typing import Any
-from fastapi import APIRouter, Depends, HTTPException, Query
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.analysis.dead_code.deletion_gate import effective_safe_to_delete
+from repowise.core.analysis.dead_code.serving import is_safe, serve_findings
from repowise.core.analysis.finding_registry import excluded_types, split_gated
from repowise.core.analysis.health.aggregation import NLOC_NULL_REASON
from repowise.core.analysis.health.signals import file_signals
@@ -36,7 +36,7 @@ from repowise.core.persistence.models import (
Page,
WikiSymbol,
)
-from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session, verify_api_key
from repowise.server.mcp_server._graph_utils import parse_community_meta
from repowise.server.routers.code_health import (
_file_signals_to_dict,
@@ -236,6 +236,7 @@ async def files_index(
async def file_detail(
repo_id: str,
file_path: str,
+ request: Request,
fields: str = Query(
"full",
description="How much of each block to return. 'full' (the default) is "
@@ -498,11 +499,9 @@ async def file_detail(
"confidence": f.confidence,
"reason": f.reason,
"lines": f.lines,
- "safe_to_delete": effective_safe_to_delete(
- f.confidence, f.file_path, f.safe_to_delete, f.kind
- ),
+ "safe_to_delete": is_safe(f),
}
- for f in dead_rows
+ for f in serve_findings(dead_rows, **cross_repo_cut_inputs(request, repo_id))
]
return {
diff --git a/packages/server/src/repowise/server/routers/graph/community.py b/packages/server/src/repowise/server/routers/graph/community.py
index bac90eb31..a7e4dc7fc 100644
--- a/packages/server/src/repowise/server/routers/graph/community.py
+++ b/packages/server/src/repowise/server/routers/graph/community.py
@@ -10,11 +10,11 @@ the list, the panel and the drill-down count the same files.
from __future__ import annotations
-from fastapi import APIRouter, Depends, HTTPException, Query
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence import crud
-from repowise.server.deps import get_db_session
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session
from repowise.server.mcp_server._graph_utils import (
community_cohesion,
community_conductance,
@@ -86,6 +86,7 @@ async def architecture_graph(
async def community_slice(
repo_id: str,
community_id: int,
+ request: Request,
member_limit: int = Query(SLICE_MEMBER_CAP, ge=1, le=600),
population: Population = Depends(population_params),
session: AsyncSession = Depends(get_db_session),
@@ -93,7 +94,12 @@ async def community_slice(
) -> CommunitySliceResponse:
"""Return a single community's sub-graph for the drill-down."""
return await build_community_slice(
- session, repo_id, community_id, member_limit=member_limit, population=population
+ session,
+ repo_id,
+ community_id,
+ member_limit=member_limit,
+ population=population,
+ cut=cross_repo_cut_inputs(request, repo_id),
)
diff --git a/packages/server/src/repowise/server/routers/graph/full_graph.py b/packages/server/src/repowise/server/routers/graph/full_graph.py
index 91eeb5680..a8eaa2bfa 100644
--- a/packages/server/src/repowise/server/routers/graph/full_graph.py
+++ b/packages/server/src/repowise/server/routers/graph/full_graph.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import load_only
@@ -11,7 +11,7 @@ from repowise.core.analysis.execution_graph import is_walkable_execution_edge
from repowise.core.persistence import crud
from repowise.core.persistence.models import GraphEdge, GraphNode
from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like
-from repowise.server.deps import get_db_session
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session
from repowise.server.mcp_server._graph_utils import _node_id_is_excluded
from repowise.server.routers.graph._common import with_repo
from repowise.server.schemas import GraphExportResponse, NodeSearchResult
@@ -116,6 +116,7 @@ async def search_nodes(
@router.get("/{repo_id}", response_model=GraphExportResponse)
async def export_graph(
repo_id: str,
+ request: Request,
limit: int = Query(
_FULL_GRAPH_NODE_CAP,
ge=1,
@@ -184,7 +185,9 @@ async def export_graph(
# Repo-wide signals: needed for the *_total counts and, when truncating,
# for reserved-slot selection (flagged nodes are known before the cut).
- signals = await collect_node_signals(session, repo_id, None)
+ signals = await collect_node_signals(
+ session, repo_id, None, **cross_repo_cut_inputs(request, repo_id)
+ )
def _sig(n: GraphNode):
return signals.get(n.node_id, EMPTY_SIGNALS)
diff --git a/packages/server/src/repowise/server/routers/graph/neighborhoods.py b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
index 638631cd4..b5e7ca8cc 100644
--- a/packages/server/src/repowise/server/routers/graph/neighborhoods.py
+++ b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
@@ -2,10 +2,11 @@
from __future__ import annotations
-from fastapi import APIRouter, Depends, HTTPException, Query
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.dead_code.serving import ServedFinding, serve_findings
from repowise.core.attribution import attribution_enabled
from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
from repowise.core.persistence.crud.analysis.shown import ungated
@@ -16,7 +17,7 @@ from repowise.core.persistence.models import (
GraphNode,
Repository,
)
-from repowise.server.deps import get_db_session
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session
from repowise.server.routers.graph._common import with_repo
from repowise.server.schemas import (
DeadCodeGraphNodeResponse,
@@ -42,6 +43,7 @@ router = APIRouter()
@router.get("/{repo_id}/ego", response_model=EgoGraphResponse)
async def ego_graph(
repo_id: str,
+ request: Request,
node_id: str = Query(..., description="Center node ID"),
hops: int = Query(2, ge=1, le=3),
session: AsyncSession = Depends(get_db_session),
@@ -119,7 +121,9 @@ async def ego_graph(
else None
)
- signals = await collect_node_signals(session, repo_id, list(ego_node_ids))
+ signals = await collect_node_signals(
+ session, repo_id, list(ego_node_ids), **cross_repo_cut_inputs(request, repo_id)
+ )
node_responses = [to_graph_node(n, signals.get(n.node_id, EMPTY_SIGNALS)) for n in node_rows]
@@ -136,6 +140,7 @@ async def ego_graph(
@router.get("/{repo_id}/entry-points", response_model=GraphExportResponse)
async def entry_points_graph(
repo_id: str,
+ request: Request,
session: AsyncSession = Depends(get_db_session),
_repo: object = Depends(with_repo),
) -> GraphExportResponse:
@@ -186,7 +191,9 @@ async def entry_points_graph(
)
nodes = node_result.scalars().all()
- signals = await collect_node_signals(session, repo_id, list(reachable))
+ signals = await collect_node_signals(
+ session, repo_id, list(reachable), **cross_repo_cut_inputs(request, repo_id)
+ )
node_responses = [to_graph_node(n, signals.get(n.node_id, EMPTY_SIGNALS)) for n in nodes]
@@ -206,6 +213,7 @@ async def entry_points_graph(
@router.get("/{repo_id}/dead-nodes", response_model=DeadCodeGraphResponse)
async def dead_code_graph(
repo_id: str,
+ request: Request,
session: AsyncSession = Depends(get_db_session),
_repo: object = Depends(with_repo),
) -> DeadCodeGraphResponse:
@@ -218,7 +226,8 @@ async def dead_code_graph(
DeadCodeFinding.kind == "unreachable_file",
)
)
- findings = finding_result.scalars().all()
+ cut = cross_repo_cut_inputs(request, repo_id)
+ findings = serve_findings(list(finding_result.scalars().all()), **cut)
if not findings:
return DeadCodeGraphResponse(nodes=[], links=[])
@@ -229,7 +238,7 @@ async def dead_code_graph(
return DeadCodeGraphResponse(nodes=[], links=[])
dead_paths = {f.file_path for f in findings}
- finding_map: dict[str, DeadCodeFinding] = {f.file_path: f for f in findings}
+ finding_map: dict[str, ServedFinding] = {f.file_path: f for f in findings}
node_result = await session.execute(
select(GraphNode).where(
@@ -298,7 +307,7 @@ async def dead_code_graph(
neighbor_nodes = []
all_node_ids = dead_node_ids | neighbor_ids
- signals = await collect_node_signals(session, repo_id, list(all_node_ids))
+ signals = await collect_node_signals(session, repo_id, list(all_node_ids), **cut)
def _to_dead_node(n: GraphNode, confidence_group: str) -> DeadCodeGraphNodeResponse:
return node_to_response(
@@ -334,6 +343,7 @@ async def dead_code_graph(
@router.get("/{repo_id}/hot-files", response_model=HotFilesGraphResponse)
async def hot_files_graph(
repo_id: str,
+ request: Request,
days: int = Query(30, description="Time window in days: 7, 30, or 90"),
limit: int = Query(25, ge=1, le=100),
session: AsyncSession = Depends(get_db_session),
@@ -389,7 +399,9 @@ async def hot_files_graph(
neighbor_nodes = []
all_node_ids = hot_node_ids | neighbor_ids
- signals = await collect_node_signals(session, repo_id, list(all_node_ids))
+ signals = await collect_node_signals(
+ session, repo_id, list(all_node_ids), **cross_repo_cut_inputs(request, repo_id)
+ )
def _to_hot_node(n: GraphNode, commit_count: int) -> HotFilesNodeResponse:
return node_to_response(
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index 5e27e65dd..9b9d5e8db 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -11,14 +11,14 @@ from __future__ import annotations
from typing import Any
-from fastapi import APIRouter, Depends, HTTPException
+from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.forges import read_remote_url, strip_credentials
from repowise.core.persistence import crud
from repowise.core.persistence.models import GitMetadata
-from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.deps import cross_repo_cut_inputs, get_db_session, verify_api_key
from repowise.server.routers.git import _hotspot_from_row
from repowise.server.services import overview_payload as sections
from repowise.server.services.overview_counts import explore_counts
@@ -74,6 +74,7 @@ async def _top_hotspots(session: AsyncSession, repo_id: str) -> list[dict[str, A
@router.get("/{repo_id}/overview-summary")
async def overview_summary(
repo_id: str,
+ request: Request,
session: AsyncSession = Depends(get_db_session),
) -> dict:
"""Everything the Overview page needs above the fold, in one call."""
@@ -126,7 +127,9 @@ async def overview_summary(
"health": await sections.health_block(session, repo_id, health_metrics, snapshot, repo),
"languages": mix["languages"],
"docs_config_languages": mix["docs_config_languages"],
- **await sections.attention_block(session, repo_id),
+ **await sections.attention_block(
+ session, repo_id, cross_repo_cut_inputs(request, repo_id)
+ ),
"top_hotspots": await _top_hotspots(session, repo_id),
"recent_decisions": await sections.recent_decisions(session, repo_id),
"savings": await sections.savings_block(repo.local_path),
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index fdc477d97..bbbb2cdbe 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -686,7 +686,12 @@ async def get_workspace_actions(
continue
try:
async with get_session(resolve_session_factory(request.app.state, repo_id)) as session:
- view = await load_actions_view(session, repo_id)
+ view = await load_actions_view(
+ session,
+ repo_id,
+ lookup=getattr(request.app.state, "cross_repo_enricher", None),
+ alias=r.alias,
+ )
except Exception as exc: # one repository must not cost the page
_log.warning("workspace actions: %s unavailable: %s", r.alias, exc)
repos.append(
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index 6b628e862..07339c455 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -6,6 +6,7 @@ each store into a :class:`SourceResult` and hands them to the fold.
from __future__ import annotations
+import functools
from collections.abc import Awaitable, Callable
from sqlalchemy import case, func, select
@@ -24,6 +25,7 @@ from repowise.core.analysis.attention import (
silo_source,
)
from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
+from repowise.core.analysis.dead_code.serving import CrossRepoLookup, is_safe, serve_findings
from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category
from repowise.core.persistence.crud.analysis.refactoring import shown_plan_predicate
@@ -326,44 +328,44 @@ async def _refactoring_items(session: AsyncSession, repo_id: str) -> tuple[list[
return items, int(total), ""
-async def _dead_code_items(session: AsyncSession, repo_id: str) -> tuple[list[dict], int, str]:
+async def _dead_code_items(
+ session: AsyncSession,
+ repo_id: str,
+ *,
+ lookup: CrossRepoLookup | None = None,
+ alias: str | None = None,
+) -> tuple[list[dict], int, str]:
"""Safe-to-delete dead code, most confident first.
Stays in the bottom band whatever its confidence. Confidence here measures
how sure the graph is that nothing reaches the symbol, not how much it
costs to leave it there, and a high-confidence unused export is still the
least urgent thing this list can show.
+
+ Every stored-safe row is read, then served (:func:`serve_findings`): in a
+ workspace the cross-repo cut withdraws some, so the cap and the count
+ come after it.
"""
+ d = DeadCodeFinding
+ # Only the columns an item and the gate read: this runs on every Overview load.
rows = (
- (
- await session.execute(
- select(DeadCodeFinding)
- .where(
- DeadCodeFinding.repository_id == repo_id,
- DeadCodeFinding.status == "open",
- DeadCodeFinding.safe_to_delete.is_(True),
- DeadCodeFinding.kind.not_in(REVIEW_ONLY_KINDS),
- DeadCodeFinding.file_path.not_in(_test_paths(repo_id)),
- )
- .order_by(DeadCodeFinding.confidence.desc())
- .limit(PER_SOURCE_CAP)
+ await session.execute(
+ select(
+ d.id, d.kind, d.file_path, d.symbol_name, d.symbol_kind, d.lines,
+ d.confidence, d.safe_to_delete,
)
- )
- .scalars()
- .all()
- )
- total = (
- await session.scalar(
- select(func.count(DeadCodeFinding.id)).where(
- DeadCodeFinding.repository_id == repo_id,
- DeadCodeFinding.status == "open",
- DeadCodeFinding.safe_to_delete.is_(True),
- DeadCodeFinding.kind.not_in(REVIEW_ONLY_KINDS),
- DeadCodeFinding.file_path.not_in(_test_paths(repo_id)),
+ .where(
+ d.repository_id == repo_id,
+ d.status == "open",
+ d.safe_to_delete.is_(True),
+ d.kind.not_in(REVIEW_ONLY_KINDS),
+ d.file_path.not_in(_test_paths(repo_id)),
)
+ .order_by(d.confidence.desc())
)
- or 0
- )
+ ).all()
+ safe = [f for f in serve_findings(list(rows), lookup, alias) if is_safe(f)]
+ safe.sort(key=lambda f: -f.confidence)
items = [
{
"id": f"dead-{row.id}",
@@ -376,9 +378,9 @@ async def _dead_code_items(session: AsyncSession, repo_id: str) -> tuple[list[di
"subtype": row.kind,
"weight": float(row.confidence or 0.0),
}
- for row in rows
+ for row in safe[:PER_SOURCE_CAP]
]
- return items, int(total), ""
+ return items, len(safe), ""
def _decision_source(decision_health: dict) -> SourceResult:
@@ -403,7 +405,6 @@ _FETCHERS: tuple[tuple[AttentionSource, _Fetcher], ...] = (
("security_finding", _security_items),
("refactoring", _refactoring_items),
("doc_drift", _drift_items),
- ("dead_code", _dead_code_items),
)
@@ -413,6 +414,8 @@ async def build_attention(
*,
decision_health: dict,
knowledge_silos: list[dict],
+ lookup: CrossRepoLookup | None = None,
+ alias: str | None = None,
) -> AttentionView:
"""Every attention source, merged and ranked worst-first.
@@ -422,7 +425,8 @@ async def build_attention(
``decision_health`` and ``knowledge_silos`` are passed in rather than
fetched: the Overview route already has both in hand for other parts of its
payload, and re-deriving them here would be two more scans of the widest
- table in the schema.
+ table in the schema. *lookup* and *alias* apply the dead-code cross-repo
+ cut in a workspace.
A source that raises is dropped with its count, not allowed to fail the
page. Overview is an aggregate over a dozen stores and one absent table (an
@@ -430,7 +434,8 @@ async def build_attention(
whole page.
"""
sources: dict[AttentionSource, SourceResult] = {}
- for key, fetch in _FETCHERS:
+ dead_code = functools.partial(_dead_code_items, lookup=lookup, alias=alias)
+ for key, fetch in (*_FETCHERS, ("dead_code", dead_code)):
try:
items, total, detail = await fetch(session, repo_id)
except Exception:
diff --git a/packages/server/src/repowise/server/services/graph_views.py b/packages/server/src/repowise/server/services/graph_views.py
index 0809de654..f80d24a8b 100644
--- a/packages/server/src/repowise/server/services/graph_views.py
+++ b/packages/server/src/repowise/server/services/graph_views.py
@@ -325,6 +325,7 @@ async def build_community_slice(
community_id: int,
member_limit: int = SLICE_MEMBER_CAP,
population: Population = PRODUCTION_ONLY,
+ cut: dict | None = None,
) -> CommunitySliceResponse:
"""Return a single community's sub-graph for the constellation blossom.
@@ -334,7 +335,8 @@ async def build_community_slice(
``is_boundary=true`` so cross-cluster edges can render without dragging the
whole neighbor cluster in. Sized to ~50-300 nodes.
- Members and boundary stubs are both filtered to the *population*.
+ Members and boundary stubs are both filtered to the *population*. *cut*
+ is the dead-code cross-repo cut's inputs (``deps.cross_repo_cut_inputs``).
"""
all_members = await crud.get_community_members(
session, repo_id, community_id, node_type="file", limit=MEMBER_READ_CAP
@@ -419,7 +421,7 @@ async def build_community_slice(
]
# Member signals only (boundary stubs stay minimal / all-false signals).
- signals = await collect_node_signals(session, repo_id, list(member_ids))
+ signals = await collect_node_signals(session, repo_id, list(member_ids), **(cut or {}))
nodes = [
node_to_response(m, signals.get(m.node_id, EMPTY_SIGNALS), CommunitySliceNodeResponse)
for m in members
diff --git a/packages/server/src/repowise/server/services/node_signals.py b/packages/server/src/repowise/server/services/node_signals.py
index f9f6177e2..4080d7d7a 100644
--- a/packages/server/src/repowise/server/services/node_signals.py
+++ b/packages/server/src/repowise/server/services/node_signals.py
@@ -16,6 +16,7 @@ from typing import Any, TypeVar
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.dead_code.serving import CrossRepoLookup, serve_findings
from repowise.core.analysis.decisions.scope import SCOPE_BASIS_FOOTPRINT
from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
@@ -58,9 +59,17 @@ async def collect_node_signals(
session: AsyncSession,
repo_id: str,
node_ids: list[str] | None = None,
+ *,
+ lookup: CrossRepoLookup | None = None,
+ alias: str | None = None,
) -> dict[str, NodeSignals]:
"""Join git metadata, dead-code findings, decisions, and docs into one map.
+ Dead-code confidence is served (:func:`serve_findings`): in a workspace,
+ *lookup* and *alias* apply the cross-repo cut. It never drops a finding,
+ so ``is_dead`` is the same without it: a caller that only counts dead
+ files needs no cut.
+
When *node_ids* is provided, queries are scoped to that subset; otherwise
we fetch repo-wide. Returns ``{node_id: NodeSignals}``. Missing keys imply
default (all-false) signals.
@@ -93,7 +102,7 @@ async def collect_node_signals(
)
if node_ids is not None:
dead_q = dead_q.where(DeadCodeFinding.file_path.in_(node_ids))
- for f in (await session.execute(dead_q)).scalars():
+ for f in serve_findings(list((await session.execute(dead_q)).scalars()), lookup, alias):
s = _entry(f.file_path)
s.is_dead = True
s.dead_confidence = f.confidence
diff --git a/packages/server/src/repowise/server/services/overview_payload.py b/packages/server/src/repowise/server/services/overview_payload.py
index 77d486ee6..c6c24c0ef 100644
--- a/packages/server/src/repowise/server/services/overview_payload.py
+++ b/packages/server/src/repowise/server/services/overview_payload.py
@@ -310,8 +310,9 @@ async def health_block(
}
-async def attention_block(session: AsyncSession, repo_id: str) -> dict:
- """``attention``, ``attention_summary`` and ``onboarding_targets``."""
+async def attention_block(session: AsyncSession, repo_id: str, cut: dict | None = None) -> dict:
+ """``attention``, ``attention_summary`` and ``onboarding_targets``; *cut* is
+ the dead-code cross-repo cut's inputs (``deps.cross_repo_cut_inputs``)."""
decision_health = await crud.get_decision_health_summary(session, repo_id)
# Silos only. The full knowledge map also computes top owners and
# onboarding targets, and paying for those here meant loading the content
@@ -328,6 +329,7 @@ async def attention_block(session: AsyncSession, repo_id: str) -> dict:
repo_id,
decision_health=decision_health,
knowledge_silos=knowledge_silos,
+ **(cut or {}),
)
return {
"attention": result["items"],
diff --git a/tests/unit/analysis/test_actions_rules.py b/tests/unit/analysis/test_actions_rules.py
index 134651bdf..7fd51f4c6 100644
--- a/tests/unit/analysis/test_actions_rules.py
+++ b/tests/unit/analysis/test_actions_rules.py
@@ -984,7 +984,7 @@ def test_history_at_the_busy_floor_or_uncounted_is_not_flagged() -> None:
def _dead_row(path: str) -> dict:
return {"id": path, "kind": "unused_export", "file_path": path, "symbol_name": "old",
- "lines": 5, "safe_to_delete": True, "status": "open"}
+ "lines": 5, "confidence": 0.9, "safe_to_delete": True, "status": "open"}
def test_dead_code_actions_skip_tests_by_the_shared_classifier() -> None:
diff --git a/tests/unit/cli/test_dead_code_stored.py b/tests/unit/cli/test_dead_code_stored.py
index dec33c2fd..b6de17e98 100644
--- a/tests/unit/cli/test_dead_code_stored.py
+++ b/tests/unit/cli/test_dead_code_stored.py
@@ -226,7 +226,9 @@ def test_a_workspace_consumer_lowers_the_stored_finding(indexed_repo, monkeypatc
analyze_live = dead_code_cmd._analyze_live
monkeypatch.setattr(dead_code_cmd, "_analyze_live", None)
monkeypatch.setattr(
- dead_code_cmd, "_cross_repo_inputs", lambda *_a: (_HttpConsumed(), "api")
+ dead_code_cmd,
+ "cross_repo_cut_inputs",
+ lambda *_a: {"lookup": _HttpConsumed(), "alias": "api"},
)
# 0.9 * 0.3 = 0.27, under the default floor the other surfaces apply too.
assert _json(indexed_repo) == []
@@ -237,16 +239,14 @@ def test_a_workspace_consumer_lowers_the_stored_finding(indexed_repo, monkeypatc
assert live and all(f["confidence"] <= 0.3 and not f["safe_to_delete"] for f in live)
-def test_cross_repo_inputs_resolve_the_alias_and_honour_no_workspace(tmp_path, monkeypatch):
- from types import SimpleNamespace
-
+def test_cross_repo_inputs_resolve_the_alias_of_a_member(tmp_path, monkeypatch):
+ from repowise.cli.helpers import cross_repo_cut_inputs
+ from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
from repowise.server.mcp_server._enrichment import CrossRepoEnricher
monkeypatch.setattr(CrossRepoEnricher, "for_workspace", classmethod(lambda cls, root: root))
+ WorkspaceConfig(repos=[RepoEntry(path="api", alias="api")]).save(tmp_path)
member = tmp_path / "api"
- target = SimpleNamespace(
- ws_root=tmp_path, ws_config=SimpleNamespace(repos=[SimpleNamespace(alias="api", path="api")])
- )
- assert dead_code_cmd._cross_repo_inputs(target, member, False) == (tmp_path, "api")
- assert dead_code_cmd._cross_repo_inputs(target, member, True) == (None, None)
- assert dead_code_cmd._cross_repo_inputs(target, tmp_path / "other", False) == (None, None)
+ assert cross_repo_cut_inputs(member, tmp_path) == {"lookup": tmp_path, "alias": "api"}
+ assert cross_repo_cut_inputs(member, None) == {"lookup": None, "alias": None}
+ assert cross_repo_cut_inputs(tmp_path / "other", tmp_path) == {"lookup": None, "alias": None}
diff --git a/tests/unit/cli/test_next_cmd.py b/tests/unit/cli/test_next_cmd.py
index 952e91902..6d26ebea0 100644
--- a/tests/unit/cli/test_next_cmd.py
+++ b/tests/unit/cli/test_next_cmd.py
@@ -231,7 +231,7 @@ async def _build_index(repo_path: Path) -> None:
) # fmt: skip
session.add_all(
DeadCodeFinding(repository_id=repo.id, kind="unused_export",
- file_path="src/dead.py", symbol_name=f"f{i}", lines=10,
+ file_path="src/dead.py", symbol_name=f"f{i}", lines=10, confidence=0.9,
safe_to_delete=True)
for i in range(3)
) # fmt: skip
diff --git a/tests/unit/health/test_language_gates_core.py b/tests/unit/health/test_language_gates_core.py
index 29580cb91..9545aa3d6 100644
--- a/tests/unit/health/test_language_gates_core.py
+++ b/tests/unit/health/test_language_gates_core.py
@@ -25,7 +25,7 @@ def _audit_gated(monkeypatch):
def _dead(path: str) -> dict:
return {"id": path, "kind": "unused_export", "file_path": path, "symbol_name": "old",
- "lines": 5, "safe_to_delete": True, "status": "open"}
+ "lines": 5, "confidence": 0.9, "safe_to_delete": True, "status": "open"}
def test_actions_never_offer_a_gated_deletion():
diff --git a/tests/unit/persistence/test_actions_build.py b/tests/unit/persistence/test_actions_build.py
index a95690562..b57e740f8 100644
--- a/tests/unit/persistence/test_actions_build.py
+++ b/tests/unit/persistence/test_actions_build.py
@@ -128,7 +128,8 @@ def _rows(dead_ids: list[str], **overrides):
"known_paths": ["src/old.py"],
"dead_code": [
{"id": i, "kind": "unused_export", "file_path": "src/dead.py",
- "symbol_name": f"f{n}", "lines": 10, "safe_to_delete": True}
+ "symbol_name": f"f{n}", "lines": 10, "confidence": 0.9,
+ "safe_to_delete": True}
for n, i in enumerate(dead_ids)
],
"decisions": {"stale_decisions": [], "summary": {}},
diff --git a/tests/unit/persistence/test_actions_loader.py b/tests/unit/persistence/test_actions_loader.py
index be7d78b1a..d86e8a799 100644
--- a/tests/unit/persistence/test_actions_loader.py
+++ b/tests/unit/persistence/test_actions_loader.py
@@ -173,7 +173,7 @@ async def _seed(session) -> str:
add(
[
DeadCodeFinding(repository_id=rid, kind="unused_export", file_path="src/dead.py",
- symbol_name=f"f{i}", lines=10, safe_to_delete=True)
+ symbol_name=f"f{i}", lines=10, confidence=0.9, safe_to_delete=True)
for i in range(3)
]
)
diff --git a/tests/unit/server/mcp/test_dead_code.py b/tests/unit/server/mcp/test_dead_code.py
index 45663c979..fce2a5309 100644
--- a/tests/unit/server/mcp/test_dead_code.py
+++ b/tests/unit/server/mcp/test_dead_code.py
@@ -139,7 +139,9 @@ class _EveryFileConsumed:
async def test_cross_repo_cut_reaches_summary_and_rollups(setup_mcp, monkeypatch):
from repowise.server.mcp_server import get_dead_code, tool_dead_code
- monkeypatch.setattr(tool_dead_code, "_cross_repo_lookup", lambda: _EveryFileConsumed())
+ monkeypatch.setattr(
+ tool_dead_code, "_cross_repo_cut", lambda alias: {"lookup": _EveryFileConsumed(), "alias": alias}
+ )
result = await get_dead_code(group_by="directory", min_confidence=0.0)
summary = result["summary"]
@@ -165,7 +167,9 @@ class _EveryFileCalled(_EveryFileConsumed):
async def test_the_default_floor_reads_the_cut_confidence(setup_mcp, monkeypatch):
from repowise.server.mcp_server import get_dead_code, tool_dead_code
- monkeypatch.setattr(tool_dead_code, "_cross_repo_lookup", lambda: _EveryFileCalled())
+ monkeypatch.setattr(
+ tool_dead_code, "_cross_repo_cut", lambda alias: {"lookup": _EveryFileCalled(), "alias": alias}
+ )
# 0.9 / 0.7 / 0.5 cut to 0.27 / 0.21 / 0.15: none clears 0.4.
result = await get_dead_code()
diff --git a/tests/unit/server/mcp/test_overview_next_actions.py b/tests/unit/server/mcp/test_overview_next_actions.py
index b48a2c907..b339c6e68 100644
--- a/tests/unit/server/mcp/test_overview_next_actions.py
+++ b/tests/unit/server/mcp/test_overview_next_actions.py
@@ -18,7 +18,7 @@ async def _seed(session, rid: str) -> None:
) # fmt: skip
session.add_all(
DeadCodeFinding(repository_id=rid, kind="unused_export", file_path="src/dead.py",
- symbol_name=f"f{i}", lines=10, safe_to_delete=True)
+ symbol_name=f"f{i}", lines=10, confidence=0.9, safe_to_delete=True)
for i in range(3)
) # fmt: skip
session.add(
@@ -88,7 +88,7 @@ async def test_a_failed_read_is_omitted_with_a_reason(setup_mcp, monkeypatch):
from repowise.server.mcp_server import get_overview
from repowise.server.mcp_server.tool_overview import actions as mod
- async def boom(session, repo_id):
+ async def boom(session, repo_id, **_cut):
raise RuntimeError("no such table: action_states")
monkeypatch.setattr(mod, "load_actions_view", boom)
@@ -181,7 +181,7 @@ def _record(monkeypatch, gate=None):
await gate.wait() # finishes only if next_actions runs meanwhile
return {"average_health": 7.0}
- async def next_actions(session, _repo, full=False):
+ async def next_actions(session, _repo, full=False, alias=None):
seen["next_actions"] = session
if gate is not None:
gate.set()
@@ -231,7 +231,7 @@ async def test_a_failed_overview_leaves_no_slow_read_running(tmp_path, monkeypat
_record(monkeypatch, gate=asyncio.Event())
from repowise.server.mcp_server.tool_overview import tool
- async def stuck(session, _repo, full=False):
+ async def stuck(session, _repo, full=False, alias=None):
await asyncio.Event().wait()
monkeypatch.setattr(tool, "_build_next_actions", stuck)
diff --git a/tests/unit/server/test_dead_code_readers_workspace.py b/tests/unit/server/test_dead_code_readers_workspace.py
new file mode 100644
index 000000000..d1cb83a2d
--- /dev/null
+++ b/tests/unit/server/test_dead_code_readers_workspace.py
@@ -0,0 +1,254 @@
+"""In a workspace, every dead-code reader withdraws what the cross-repo cut withdraws.
+
+One finding is stored deletion-ready and reads safe on every surface outside a
+workspace; another repo changes together with its file, so inside one it
+reads not safe everywhere, at the confidence ``get_dead_code`` shows. A second
+finding serves an HTTP contract, so its confidence drops wherever it is shown.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+SAFE_PATH = "src/helpers.py"
+CONTRACT_PATH = "src/served.py"
+
+
+class _Consumed:
+ """Another repo co-changes with SAFE_PATH and calls an HTTP route in CONTRACT_PATH."""
+
+ def has_cross_repo_consumers(self, repo_alias, file_path):
+ return [{"repo": "web"}] if file_path == SAFE_PATH else []
+
+ def get_repos_depending_on(self, repo_alias):
+ return []
+
+ def get_package_consumers(self, repo_alias):
+ return []
+
+ def get_contract_links_as_provider(self, repo_alias, file_path):
+ return [{"consumer_repo": "web"}] if file_path == CONTRACT_PATH else []
+
+
+CUT = {"lookup": _Consumed(), "alias": "api"}
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ from repowise.core.persistence.models import GitMetadata
+
+ async with get_session(session_factory) as session:
+ # File detail answers for an indexed file only.
+ session.add(GitMetadata(repository_id=repo_id, file_path=SAFE_PATH))
+ await crud.save_dead_code_findings(
+ session,
+ repo_id,
+ [
+ {
+ "kind": "unused_export",
+ "file_path": SAFE_PATH,
+ "symbol_name": "old_helper",
+ "symbol_kind": "function",
+ "confidence": 0.9,
+ "reason": "No callers",
+ "lines": 40,
+ "start_line": 1,
+ "end_line": 40,
+ "safe_to_delete": True,
+ },
+ {
+ "kind": "unreachable_file",
+ "file_path": CONTRACT_PATH,
+ "symbol_name": None,
+ "symbol_kind": None,
+ "confidence": 0.9,
+ "reason": "No imports found",
+ "lines": 30,
+ "safe_to_delete": False,
+ },
+ ],
+ )
+
+
+def _enter_workspace(app, tmp_path, monkeypatch, repo_id: str) -> None:
+ state = app.state
+ monkeypatch.setattr(state, "cross_repo_enricher", CUT["lookup"], raising=False)
+ config = SimpleNamespace(repos=[SimpleNamespace(alias="api", path=".")])
+ monkeypatch.setattr(state, "workspace_config", config, raising=False)
+ monkeypatch.setattr(state, "workspace_root", str(tmp_path), raising=False)
+ path_to_id = {str(tmp_path.resolve()): repo_id}
+ monkeypatch.setattr(state, "workspace_path_to_repo_id", path_to_id, raising=False)
+
+
+def _dead_actions(view: dict) -> list[dict]:
+ return [
+ a for h in view["horizons"].values() for a in h["actions"] if a["rule"] == "dead_code_batch"
+ ]
+
+
+async def _rest_reads(client: AsyncClient, rid: str) -> dict:
+ """What each REST reader says about SAFE_PATH's finding."""
+ detail = (await client.get(f"/api/repos/{rid}/files/{SAFE_PATH}")).json()
+ [row] = detail["dead_code"]
+ overview = (await client.get(f"/api/repos/{rid}/overview-summary")).json()
+ attention = [i for i in overview["attention"] if i["type"] == "dead_code"]
+ related = (
+ await client.post(f"/api/repos/{rid}/health/related-work", json={"file_paths": [SAFE_PATH]})
+ ).json()
+ [item] = related["files"][0]["lenses"]["dead_code"]["items"]
+ actions = (await client.get(f"/api/repos/{rid}/actions")).json()
+ listed = (await client.get(f"/api/repos/{rid}/dead-code")).json()
+ [served] = [f for f in listed if f["file_path"] == SAFE_PATH]
+ return {
+ "file detail": (row["confidence"], row["safe_to_delete"]),
+ "dead-code list": (served["confidence"], served["safe_to_delete"]),
+ "attention": [i["target_id"] for i in attention],
+ "related work": item["tier"],
+ "actions": [a["evidence_total"] for a in _dead_actions(actions)],
+ }
+
+
+async def test_every_rest_reader_withdraws_a_stored_safe_row_the_cut_reaches(
+ client: AsyncClient, app, tmp_path, monkeypatch
+) -> None:
+ from repowise.server.routers import actions
+
+ app.include_router(actions.router)
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ # Outside a workspace the row is deletion-ready everywhere, so the cut is
+ # what the second read measures.
+ assert await _rest_reads(client, repo["id"]) == {
+ "file detail": (0.9, True),
+ "dead-code list": (0.9, True),
+ "attention": [SAFE_PATH],
+ "related work": "safe_to_delete",
+ "actions": [1],
+ }
+ _enter_workspace(app, tmp_path, monkeypatch, repo["id"])
+ assert await _rest_reads(client, repo["id"]) == {
+ "file detail": (0.9, False),
+ "dead-code list": (0.9, False),
+ "attention": [],
+ "related work": "review",
+ "actions": [],
+ }
+
+
+async def test_core_readers_take_the_cut(session_factory) -> None:
+ from repowise.core.persistence.crud.analysis.actions import (
+ load_action,
+ load_actions_view,
+ write_actions_snapshot,
+ )
+ from repowise.core.report.model import ReportContext
+ from repowise.core.report.sections.dead_code import collect
+ from repowise.server.services.node_signals import collect_node_signals
+ from tests.unit.persistence.helpers import insert_repo
+
+ async with get_session(session_factory) as session:
+ rid = (await insert_repo(session)).id
+ await _seed(session_factory, rid)
+
+ async with get_session(session_factory) as session:
+ # The snapshot is written per repository, without the cut.
+ await write_actions_snapshot(session, rid)
+ [stored] = _dead_actions(await load_actions_view(session, rid))
+ assert _dead_actions(await load_actions_view(session, rid, **CUT)) == []
+ assert await load_action(session, rid, stored["id"], **CUT) is None
+
+ report = ReportContext(session, rid, ".", alias="api", cross_repo=CUT)
+ tiers = {c["name"]: c["data"] for c in await collect(report)}
+ # The contract cut takes CONTRACT_PATH's 0.9 to 0.27, out of high.
+ assert tiers["dead-code:high"]["count"] == 1
+ assert tiers["dead-code:low"]["count"] == 1
+
+ signals = await collect_node_signals(session, rid, [CONTRACT_PATH], **CUT)
+ assert signals[CONTRACT_PATH].dead_confidence == 0.27
+ # Dead-file counts (module, architecture, community) read is_dead only.
+ uncut = await collect_node_signals(session, rid, [CONTRACT_PATH])
+ assert uncut[CONTRACT_PATH].is_dead is signals[CONTRACT_PATH].is_dead is True
+
+
[email protected]("cut", [{}, CUT], ids=["single repo", "workspace"])
+async def test_a_snapshot_that_took_the_stored_flag_is_not_served(
+ session_factory, monkeypatch, cut
+) -> None:
+ """A row stored safe below the confidence bar, counted by a snapshot built
+ from the stored flag, never reaches Do next."""
+ from repowise.core.analysis.actions import build
+ from repowise.core.persistence.crud.analysis.actions import (
+ _KEY,
+ SNAPSHOT_KIND,
+ load_actions_view,
+ write_actions_snapshot,
+ )
+ from repowise.core.persistence.read_snapshots import read_snapshot
+ from tests.unit.persistence.helpers import insert_repo
+
+ async with get_session(session_factory) as session:
+ rid = (await insert_repo(session)).id
+ await crud.save_dead_code_findings(
+ session,
+ rid,
+ [
+ {
+ "kind": "unused_export",
+ "file_path": "src/legacy.py",
+ "symbol_name": "legacy",
+ "symbol_kind": "function",
+ "confidence": 0.5,
+ "reason": "No callers",
+ "lines": 40,
+ "start_line": 1,
+ "end_line": 40,
+ "safe_to_delete": True,
+ }
+ ],
+ )
+ with monkeypatch.context() as m:
+ m.setattr(build, "is_safe", lambda r: bool(build.field(r, "safe_to_delete")))
+ async with get_session(session_factory) as session:
+ await write_actions_snapshot(session, rid)
+ stored = await read_snapshot(session, rid, SNAPSHOT_KIND, _KEY)
+ assert "dead_code_batch" in str(stored)
+
+ async with get_session(session_factory) as session:
+ assert _dead_actions(await load_actions_view(session, rid, **cut)) == []
+
+
+async def test_chat_dataset_and_mcp_actions_take_the_cut(session_factory, monkeypatch) -> None:
+ from repowise.server.chat_datasets import LoadContext
+ from repowise.server.chat_datasets.findings import load_dead_code
+ from repowise.server.mcp_server import _helpers, _state
+ from repowise.server.mcp_server.tool_overview.actions import _build_next_actions
+ from tests.unit.persistence.helpers import insert_repo
+
+ async with get_session(session_factory) as session:
+ repository = await insert_repo(session)
+ await _seed(session_factory, repository.id)
+ monkeypatch.setattr(_helpers, "_is_workspace_mode", lambda: True)
+ monkeypatch.setattr(_state, "_cross_repo_enricher", CUT["lookup"])
+
+ async def no_files(_name):
+ return []
+
+ async with get_session(session_factory) as session:
+ context = LoadContext(session, repository, ".", no_files, "api")
+ rows = {r["path"]: r for r in await load_dead_code(context)}
+ assert (rows[SAFE_PATH]["confidence"], rows[SAFE_PATH]["safe_to_delete"]) == (0.9, False)
+ assert rows[CONTRACT_PATH]["confidence"] == 0.27
+
+ block, _ = await _build_next_actions(session, repository, full=True, alias="api")
+ assert "dead_code_batch" not in str(block)