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(decisions): keep a record's scope and its graph links in step (#2464)

Raghav Chamadiya9358d45ce284
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index 5ea483ac4..cb784c94b 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -360,7 +360,8 @@ def decision_add(
alternatives=alternatives_list,
consequences=consequences_list,
affected_files=affected_files,
- affected_modules=[],
+ # None derives them from the files; [] would clear them.
+ affected_modules=None,
tags=tags_list,
kind=kind,
source="cli",
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 10dd0a9f1..ddb58ca93 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1037,6 +1037,7 @@ async def _persist_full_update_async(
# classified.
from repowise.core.persistence.decision_migration import (
apply_migration,
+ backfill_decision_node_links,
backfill_scope_basis,
backfill_session_scope_basis,
prune_unindexed_scope_files,
@@ -1052,6 +1053,7 @@ async def _persist_full_update_async(
await prune_unindexed_scope_files(session, repo_id)
await backfill_scope_basis(session, repo_id)
await backfill_session_scope_basis(session, repo_id)
+ await backfill_decision_node_links(session, repo_id)
if require_decision_persist_success:
from repowise.core.persistence.crud import (
diff --git a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
index 35f612abf..46bd8fb3e 100644
--- a/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
+++ b/packages/core/src/repowise/core/analysis/decisions/lifecycle.py
@@ -222,6 +222,33 @@ NEEDS_REVIEW_STALENESS: float = 0.5
#: a decision whose code moved is a decision to re-read, not one to ignore.
_GOVERNING: frozenset[str] = frozenset({"active", "needs_review"})
+#: Statuses that record a retirement somebody performed. The migration keeps
+#: them: reclassifying one as an open candidate would undo the retirement.
+RETIRED_STATUSES: frozenset[str] = frozenset({"dismissed", "deprecated", "superseded"})
+
+#: Retirements that leave nothing in the decision's place, and so govern no
+#: path. A record at one of these keeps its files and its place in a lookup by
+#: id and links no code, because the graph is what "what governs this path" is
+#: answered from.
+#:
+#: ``superseded`` is deliberately *not* here even though it is retired: it has
+#: a successor, it still governs the path, and ``get_risk``'s
+#: ``superseded_decision`` directive finds it through those very links to tell
+#: a reviewer their change is governed by a decision that has been replaced.
+#: ``proposed`` is absent because a candidate is not retired at all, and the
+#: candidate lane delivers on its links.
+WITHDRAWN_STATUSES: frozenset[str] = frozenset({"dismissed", "deprecated"})
+
+
+def is_retired(status: str) -> bool:
+ """Whether *status* records a retirement somebody performed."""
+ return status in RETIRED_STATUSES
+
+
+def is_withdrawn(status: str) -> bool:
+ """Whether *status* leaves nothing in the decision's place, so governs no path."""
+ return status in WITHDRAWN_STATUSES
+
def is_governing(currency: str) -> bool:
"""Whether a decision at *currency* still constrains new work."""
diff --git a/packages/core/src/repowise/core/persistence/crud/authority.py b/packages/core/src/repowise/core/persistence/crud/authority.py
index 351a6e5ee..2fae07756 100644
--- a/packages/core/src/repowise/core/persistence/crud/authority.py
+++ b/packages/core/src/repowise/core/persistence/crud/authority.py
@@ -44,7 +44,11 @@ from repowise.core.analysis.decisions.lifecycle import (
)
from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATED
-from ..decision_graph import upsert_decision_edge
+from ..decision_graph import (
+ set_record_scope,
+ sync_links_from_record,
+ upsert_decision_edge,
+)
from ..models import (
DecisionAcceptance,
DecisionAlias,
@@ -609,6 +613,10 @@ async def record_acceptance(
record.status = legacy_status_for_currency(currency)
record.updated_at = _now_utc()
await session.flush()
+ # Retirement decides what the graph holds, so a status write moves the
+ # links with it. Leaving them to the next index is what made the
+ # withdrawal visible in one surface and not another.
+ await sync_links_from_record(session, record)
return acceptance
@@ -699,10 +707,9 @@ async def accept_decision(
if reason:
record.rationale = reason
if scope is not None:
- record.affected_files_json = json.dumps(scope)
- # The accepter chose these files, so the record binds to them
- # rather than keeping the basis it was mined with.
- record.scope_basis = SCOPE_BASIS_STATED
+ # The accepter chose these files, so the record binds to them rather
+ # than keeping the basis it was mined with.
+ await set_record_scope(session, record, scope, basis=SCOPE_BASIS_STATED)
acceptance = await record_acceptance(
session,
record,
@@ -955,6 +962,7 @@ async def dismiss_candidate(
record.status = "dismissed"
record.updated_at = _now_utc()
await session.flush()
+ await sync_links_from_record(session, record)
return meta
diff --git a/packages/core/src/repowise/core/persistence/crud/decisions.py b/packages/core/src/repowise/core/persistence/crud/decisions.py
index 607882106..988f231cf 100644
--- a/packages/core/src/repowise/core/persistence/crud/decisions.py
+++ b/packages/core/src/repowise/core/persistence/crud/decisions.py
@@ -21,6 +21,7 @@ from repowise.core.analysis.decisions.lifecycle import (
ARCHITECTURAL_KIND,
DECISION_KINDS,
DECISION_STATUS_ORDER,
+ RETIRED_STATUSES,
status_rank,
)
from repowise.core.analysis.decisions.provenance import (
@@ -32,7 +33,7 @@ from repowise.core.analysis.decisions.provenance import (
)
from repowise.core.analysis.decisions.scope import SCOPE_BASIS_STATED, binds_to_paths
-from ..decision_graph import sync_decision_node_links
+from ..decision_graph import scope_modules, sync_links_from_record
from ..models import (
DecisionCandidateMeta,
DecisionEdge,
@@ -329,7 +330,9 @@ async def upsert_decision(
# The caller supplied these files, so they are its claim and not
# any footprint the row carried.
rec.scope_basis = SCOPE_BASIS_STATED if affected_files else ""
- rec.affected_modules_json = json.dumps(affected_modules or [])
+ rec.affected_modules_json = json.dumps(
+ scope_modules(affected_files or [], affected_modules)
+ )
rec.tags_json = json.dumps(tags or [])
rec.evidence_commits_json = json.dumps(evidence_commits or [])
rec.evidence_line = evidence_line
@@ -340,6 +343,7 @@ async def upsert_decision(
rec.superseded_by = superseded_by
rec.updated_at = _now_utc()
await session.flush()
+ await sync_links_from_record(session, rec)
await _write_candidate_meta(session, repository_id, {}, only={rec.id})
return rec
@@ -393,7 +397,11 @@ async def upsert_decision(
alternatives_json=json.dumps(alternatives or []),
consequences_json=json.dumps(consequences or []),
affected_files_json=json.dumps(affected_files or []),
- affected_modules_json=json.dumps(affected_modules or []),
+ # Same claim as the restate arm: files the caller supplied are stated.
+ scope_basis=SCOPE_BASIS_STATED if affected_files else "",
+ affected_modules_json=json.dumps(
+ scope_modules(affected_files or [], affected_modules)
+ ),
tags_json=json.dumps(tags or []),
evidence_commits_json=json.dumps(evidence_commits or []),
source=source,
@@ -407,6 +415,7 @@ async def upsert_decision(
)
session.add(rec)
await session.flush()
+ await sync_links_from_record(session, rec)
await _write_candidate_meta(session, repository_id, {}, only={rec.id})
return rec
@@ -575,21 +584,28 @@ async def update_decision_metadata(
) -> DecisionRecord | None:
"""Patch the module/file linkage on a decision record.
- Each argument left as ``None`` is preserved. Pass an empty list to clear.
- Returns the updated record, or ``None`` if the id was not found.
+ Each argument left as ``None`` is preserved, except that supplying files
+ without modules re-derives the modules from those files: a scope whose two
+ halves describe different code links the record to a module its files are
+ not in. Pass an empty list to clear either. Returns the updated record, or
+ ``None`` if the id was not found.
"""
rec = await session.get(DecisionRecord, decision_id)
if rec is None:
return None
- if affected_modules is not None:
- rec.affected_modules_json = json.dumps(affected_modules)
if affected_files is not None:
rec.affected_files_json = json.dumps(affected_files)
# A scope set by hand is stated, whatever the row held before:
# otherwise the new files are stored and then ignored everywhere.
rec.scope_basis = SCOPE_BASIS_STATED
+ # Modules follow the files they describe. Replacing one and keeping
+ # the other links the record to a module its files are not in.
+ affected_modules = scope_modules(affected_files, affected_modules)
+ if affected_modules is not None:
+ rec.affected_modules_json = json.dumps(affected_modules)
rec.updated_at = _now_utc()
await session.flush()
+ await sync_links_from_record(session, rec)
return rec
@@ -635,7 +651,7 @@ async def update_decision_status(
await accept_decision(
session, rec, accepter=accepter or "unrecorded", kind=kind
)
- elif accepted and status in ("dismissed", "deprecated", "superseded"):
+ elif accepted and status in RETIRED_STATUSES:
await record_acceptance(
session,
rec,
@@ -651,6 +667,9 @@ async def update_decision_status(
if superseded_by is not None:
rec.superseded_by = superseded_by
rec.updated_at = _now_utc()
+ # Both directions: a retirement drops the links and a revival rebuilds
+ # them, rather than either waiting for the next index.
+ await sync_links_from_record(session, rec)
await session.flush()
return rec
@@ -685,8 +704,11 @@ async def update_decision_by_id(
}
if "affected_files" in fields:
# Same rule as every other path that takes a scope from its caller:
- # the basis has to move with the files it describes.
+ # the basis and the modules have to move with the files they describe.
rec.scope_basis = SCOPE_BASIS_STATED if fields["affected_files"] else ""
+ fields["affected_modules"] = scope_modules(
+ fields["affected_files"], fields.get("affected_modules")
+ )
_scalar_fields = {
"title",
"context",
@@ -705,6 +727,7 @@ async def update_decision_by_id(
rec.updated_at = _now_utc()
await session.flush()
+ await sync_links_from_record(session, rec)
return rec
@@ -1448,20 +1471,7 @@ async def bulk_upsert_decisions(
prior_split or any(bool(d.get("needs_split")) for d in members),
)
- # Mirror the JSON file/module arrays into first-class decision→code
- # links so the graph is traversable both directions (Phase 3A). The
- # JSON stays the cheap read cache; these rows are the queryable truth.
- # A footprint contributes no links. The graph is what session
- # injection and the ``get_risk`` directives ask "which decisions touch
- # this node", so gating this one write path covers both readers.
- binds = binds_to_paths(rec.scope_basis)
- await sync_decision_node_links(
- session,
- repository_id,
- rec.id,
- files=json.loads(rec.affected_files_json or "[]") if binds else [],
- modules=json.loads(rec.affected_modules_json or "[]") if binds else [],
- )
+ await sync_links_from_record(session, rec)
# (Re-)embed the record into the shared store so it's matchable by
# later groups in this batch + future runs, and discoverable via
@@ -1732,7 +1742,13 @@ async def recompute_decision_staleness(
if affected:
affected_by_id[dec.id] = affected
- modules_updated = _backfill_module_nodes(decisions, affected_by_id)
+ remodelled = _backfill_module_nodes(decisions, affected_by_id)
+ modules_updated = len(remodelled)
+ # This repair runs after ``backfill_decision_node_links`` on both index
+ # paths, so a module array it rewrites here would otherwise keep the link
+ # the backfill had already judged correct.
+ for dec in remodelled:
+ await sync_links_from_record(session, dec)
if not affected_by_id:
if modules_updated:
await session.flush()
@@ -1798,15 +1814,19 @@ async def recompute_decision_staleness(
def _backfill_module_nodes(
decisions: list[DecisionRecord],
affected_by_id: dict[str, list[str]],
-) -> int:
- """Re-derive each record's module linkage from its files. Returns rows moved.
+) -> list[DecisionRecord]:
+ """Re-derive each record's module linkage from its files.
+
+ Returns the records whose array moved, because the caller has to relink
+ each one: this rewrites half a record's scope and the graph holds the
+ other half.
Records naming no file are left alone: there is nothing to derive from, and
an invented scope is worse than an absent one.
"""
from repowise.core.analysis.decisions.scope import resolve_module_nodes
- moved = 0
+ moved = []
for dec in decisions:
affected = affected_by_id.get(dec.id)
if not affected:
@@ -1814,7 +1834,7 @@ def _backfill_module_nodes(
derived = resolve_module_nodes(affected)
if derived != json.loads(dec.affected_modules_json or "[]"):
dec.affected_modules_json = json.dumps(derived)
- moved += 1
+ moved.append(dec)
return moved
diff --git a/packages/core/src/repowise/core/persistence/decision_dedupe.py b/packages/core/src/repowise/core/persistence/decision_dedupe.py
index 27183dfa5..910314edc 100644
--- a/packages/core/src/repowise/core/persistence/decision_dedupe.py
+++ b/packages/core/src/repowise/core/persistence/decision_dedupe.py
@@ -85,7 +85,7 @@ from .crud.decisions import (
list_decision_evidence,
record_completeness,
)
-from .decision_graph import sync_decision_node_links
+from .decision_graph import sync_links_from_record
from .models import (
DecisionCandidateMeta,
DecisionEdge,
@@ -387,15 +387,10 @@ async def apply_dedupe(
canonical.scope_basis = SCOPE_BASIS_FOOTPRINT
else:
canonical.scope_basis = commit_scope_basis(sorted(union["files"]))
- # Sync replaces rather than accretes, so it must see the union.
- binds = binds_to_paths(canonical.scope_basis)
- await sync_decision_node_links(
- session,
- repository_id,
- canonical.id,
- files=sorted(union["files"]) if binds else [],
- modules=sorted(union["modules"]) if binds else [],
- )
+ # Through the shared writer, which reads the union just written to the
+ # record: the last path that judged links by its own rule, and so the
+ # last one that could re-create links a withdrawal had removed.
+ await sync_links_from_record(session, canonical)
_rederive_headline(canonical, await list_decision_evidence(session, canonical.id))
applied.clusters.append(done)
diff --git a/packages/core/src/repowise/core/persistence/decision_graph.py b/packages/core/src/repowise/core/persistence/decision_graph.py
index c07662453..7fb7ba128 100644
--- a/packages/core/src/repowise/core/persistence/decision_graph.py
+++ b/packages/core/src/repowise/core/persistence/decision_graph.py
@@ -18,21 +18,30 @@ Two graphs live here:
from __future__ import annotations
+import json
+
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.decisions.lifecycle import is_withdrawn
+from repowise.core.analysis.decisions.scope import binds_to_paths, resolve_module_nodes
+
from .models import DecisionEdge, DecisionNodeLink, DecisionRecord
__all__ = [
"VALID_EDGE_KINDS",
"build_lineage_chain",
+ "expected_node_links",
"get_decision_edges",
"get_governed_nodes",
"get_governing_decisions",
"list_all_decision_edges",
"list_conflict_edges",
"list_decision_node_links",
+ "scope_modules",
+ "set_record_scope",
"sync_decision_node_links",
+ "sync_links_from_record",
"upsert_decision_edge",
]
@@ -198,6 +207,85 @@ async def sync_decision_node_links(
await session.flush()
+def expected_node_links(record: DecisionRecord) -> tuple[list[str], list[str]]:
+ """The (files, modules) *record*'s links should hold, given its state.
+
+ One answer for both the writer and the backfill that checks it, so a
+ record can never be judged against a rule other than the one that wrote
+ it. A basis that does not bind to paths links nothing, and neither does a
+ withdrawn record: the graph is what "what governs this path" is answered
+ from, and a decision with nothing in its place answers nothing. Keyed on
+ the vocabulary rather than the one literal ``dismiss`` writes — a
+ withdrawal through the acceptance log lands on ``deprecated``, and a
+ ``superseded`` record keeps its links because its successor's directive
+ is found through them.
+ """
+ if is_withdrawn(record.status) or not binds_to_paths(record.scope_basis):
+ return [], []
+ return (
+ _json_list(record.affected_files_json),
+ _json_list(record.affected_modules_json),
+ )
+
+
+def scope_modules(files: list[str], modules: list[str] | None) -> list[str]:
+ """The module array for a scope: what the caller gave, or derived from it.
+
+ ``None`` means the caller supplied files and said nothing about modules,
+ which is not the same as saying there are none. Deriving is what keeps the
+ two halves of a scope describing the same code; an empty list still
+ clears.
+ """
+ return resolve_module_nodes(files) if modules is None else list(modules)
+
+
+async def set_record_scope(
+ session: AsyncSession,
+ record: DecisionRecord,
+ files: list[str],
+ *,
+ basis: str | None = None,
+) -> None:
+ """Point *record* at *files*, deriving its modules, and relink the graph.
+
+ For every caller that takes a file list from outside — an accepter, a
+ manifest, a prune. The module array is derived here rather than left as
+ the caller found it, because a scope whose halves disagree links a record
+ to modules its files are no longer in, and mirroring is faithful to that
+ disagreement rather than a repair for it.
+ """
+ record.affected_files_json = json.dumps(files)
+ record.affected_modules_json = json.dumps(scope_modules(files, None))
+ if basis is not None:
+ record.scope_basis = basis
+ await sync_links_from_record(session, record)
+
+
+async def sync_links_from_record(session: AsyncSession, record: DecisionRecord) -> None:
+ """Mirror *record*'s current scope arrays into its traversable links.
+
+ Call this from every writer that moves ``affected_files_json`` or
+ ``affected_modules_json``. The arrays are a read cache; these rows are what
+ every path-scoped surface queries, so a scope written to one and not the
+ other is stored and then ignored.
+ """
+ files, modules = expected_node_links(record)
+ await sync_decision_node_links(
+ session, record.repository_id, record.id, files=files, modules=modules
+ )
+
+
+def _json_list(raw: str | None) -> list[str]:
+ """A stored JSON array as a list of non-empty strings; empty on anything else."""
+ try:
+ value = json.loads(raw or "[]")
+ except (TypeError, ValueError):
+ return []
+ if not isinstance(value, list):
+ return []
+ return [v for v in value if isinstance(v, str) and v]
+
+
async def get_governing_decisions(
session: AsyncSession,
repository_id: str,
diff --git a/packages/core/src/repowise/core/persistence/decision_manifest.py b/packages/core/src/repowise/core/persistence/decision_manifest.py
index 38d2d2fa9..06749f63e 100644
--- a/packages/core/src/repowise/core/persistence/decision_manifest.py
+++ b/packages/core/src/repowise/core/persistence/decision_manifest.py
@@ -37,6 +37,7 @@ from .crud.authority import (
resolve_decision_id,
)
from .crud.decisions import _rederive_headline, list_decision_evidence
+from .decision_graph import set_record_scope
from .models import DecisionAlias, DecisionRecord
__all__ = ["ImportOutcome", "export_manifest", "import_manifest"]
@@ -228,10 +229,11 @@ async def _apply_entry(
else:
record.confidence = _entry_confidence(entry)
record.kind = entry.kind or ARCHITECTURAL_KIND
- record.affected_files_json = json.dumps(sorted(_scope_files(entry.scope)))
# The file is hand-authored and version controlled, so its scope is
# stated: a record narrowed here binds to what the file says.
- record.scope_basis = SCOPE_BASIS_STATED
+ await set_record_scope(
+ session, record, sorted(_scope_files(entry.scope)), basis=SCOPE_BASIS_STATED
+ )
# The successor is an id the file wrote down, and the file can be older
# than the store it is being read into. Storing it unresolved would put a
# retired id back into the column.
@@ -310,8 +312,6 @@ async def import_manifest(
rationale=entry.reason,
source=entry.source or "cli",
kind=entry.kind or ARCHITECTURAL_KIND,
- affected_files_json=json.dumps(sorted(_scope_files(entry.scope))),
- scope_basis=SCOPE_BASIS_STATED,
evidence_commits_json=json.dumps(sorted(entry.evidence)),
superseded_by=entry.superseded_by or None,
confidence=_entry_confidence(entry),
@@ -319,6 +319,9 @@ async def import_manifest(
)
session.add(record)
await session.flush()
+ await set_record_scope(
+ session, record, sorted(_scope_files(entry.scope)), basis=SCOPE_BASIS_STATED
+ )
elif entry.id not in outcome.reaffirmed:
outcome.accepted.append(entry.id)
if dry_run:
diff --git a/packages/core/src/repowise/core/persistence/decision_migration.py b/packages/core/src/repowise/core/persistence/decision_migration.py
index ab3e46ddb..d0711274e 100644
--- a/packages/core/src/repowise/core/persistence/decision_migration.py
+++ b/packages/core/src/repowise/core/persistence/decision_migration.py
@@ -26,11 +26,11 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.decisions.kinds import classify_kind
from repowise.core.analysis.decisions.lifecycle import (
AGREEMENT_KIND,
+ RETIRED_STATUSES,
currency_for_legacy_status,
)
from repowise.core.analysis.decisions.scope import (
SCOPE_BASIS_FOOTPRINT,
- resolve_module_nodes,
session_scope_basis,
)
@@ -41,7 +41,12 @@ from .crud.authority import (
record_acceptance,
upsert_candidate_meta,
)
-from .decision_graph import DecisionNodeLink
+from .decision_graph import (
+ DecisionNodeLink,
+ expected_node_links,
+ set_record_scope,
+ sync_links_from_record,
+)
from .models import (
DecisionAcceptance,
DecisionCandidateMeta,
@@ -53,6 +58,7 @@ __all__ = [
"MigrationPlan",
"RowPlan",
"apply_migration",
+ "backfill_decision_node_links",
"backfill_scope_basis",
"backfill_session_scope_basis",
"plan_json",
@@ -68,9 +74,6 @@ __all__ = [
#: purpose.
_SELF_ACCEPTING_SOURCES: frozenset[str] = frozenset({"cli", "adr"})
-#: Statuses that record a retirement somebody performed. The migration keeps
-#: them: reclassifying one as an open candidate would undo the retirement.
-_RETIRED_STATUSES: frozenset[str] = frozenset({"dismissed", "deprecated", "superseded"})
@dataclass(slots=True)
@@ -221,7 +224,7 @@ async def plan_migration(
# it as an unreviewed candidate would put a decision the user retired
# back in front of them asking to be accepted, so all three retired
# statuses keep their status and carry a tombstone.
- if rec.status in _RETIRED_STATUSES:
+ if rec.status in RETIRED_STATUSES:
plan.rows.append(
RowPlan(
rec.id,
@@ -364,7 +367,7 @@ async def apply_migration(
continue
if row.kind:
rec.kind = row.kind
- if rec.status in _RETIRED_STATUSES and row.outcome != "decision":
+ if rec.status in RETIRED_STATUSES and row.outcome != "decision":
# Record the tombstone without touching the status that carries the
# retirement.
existed = await session.get(DecisionCandidateMeta, rec.id) is not None
@@ -544,6 +547,50 @@ async def backfill_session_scope_basis(
return changed
+async def backfill_decision_node_links(
+ session: AsyncSession, repository_id: str
+) -> int:
+ """Rebuild links for records whose scope never reached the graph.
+
+ Every hand-authored record predates :func:`sync_links_from_record`, and a
+ record with files but no links is invisible to every path-scoped surface.
+ Runs on each index, after the basis repairs so it mirrors the scope they
+ leave behind. Returns how many records were relinked.
+ """
+ rows = (
+ (
+ await session.execute(
+ select(DecisionRecord).where(DecisionRecord.repository_id == repository_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ linked: dict[str, set[tuple[str, str]]] = {}
+ for decision_id, node_id, link_type in (
+ await session.execute(
+ select(
+ DecisionNodeLink.decision_id,
+ DecisionNodeLink.node_id,
+ DecisionNodeLink.link_type,
+ ).where(DecisionNodeLink.repository_id == repository_id)
+ )
+ ).all():
+ linked.setdefault(decision_id, set()).add((node_id, link_type))
+
+ changed = 0
+ for rec in rows:
+ files, modules = expected_node_links(rec)
+ want = {(n, "file") for n in files} | {(n, "module") for n in modules}
+ if want == linked.get(rec.id, set()):
+ continue
+ await sync_links_from_record(session, rec)
+ changed += 1
+ if changed:
+ await session.flush()
+ return changed
+
+
#: Below this many indexed file nodes, the graph is treated as unbuilt rather
#: than as evidence that a scope is wrong. Pruning against a graph that failed
#: to build would empty every scope in the store, which is the one outcome
@@ -603,15 +650,7 @@ async def prune_unindexed_scope_files(
kept = [f for f in files if f in indexed]
if len(kept) == len(files):
continue
- rec.affected_files_json = json.dumps(kept)
- rec.affected_modules_json = json.dumps(resolve_module_nodes(kept))
- for dropped in set(files) - set(kept):
- await session.execute(
- delete(DecisionNodeLink).where(
- DecisionNodeLink.decision_id == rec.id,
- DecisionNodeLink.node_id == dropped,
- )
- )
+ await set_record_scope(session, rec, kept)
changed += 1
if changed:
await session.flush()
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 241f8bff5..1e0e74ee3 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -2081,6 +2081,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
try:
from repowise.core.persistence.decision_migration import (
apply_migration,
+ backfill_decision_node_links,
backfill_scope_basis,
backfill_session_scope_basis,
prune_unindexed_scope_files,
@@ -2093,6 +2094,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
await prune_unindexed_scope_files(session, repo_id)
await backfill_scope_basis(session, repo_id)
await backfill_session_scope_basis(session, repo_id)
+ await backfill_decision_node_links(session, repo_id)
except Exception as _migrate_err:
logger.debug("decision_entity_migration_skipped", error=str(_migrate_err))
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 4bbd06166..40a491710 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -659,7 +659,9 @@ async def patch_decision(
Accepts status transitions (confirm / deprecate / supersede) and / or
governance edits (``affected_modules``, ``affected_files``). Any field
- left as ``None`` in the body is preserved.
+ left as ``None`` in the body is preserved, except that sending
+ ``affected_files`` without ``affected_modules`` re-derives the modules
+ from those files so the two halves of the scope cannot disagree.
"""
decision_id = await _live_decision_id(session, decision_id)
rec = await crud.get_decision(session, decision_id)
diff --git a/tests/unit/persistence/test_decision_scope_links.py b/tests/unit/persistence/test_decision_scope_links.py
new file mode 100644
index 000000000..098c4faaf
--- /dev/null
+++ b/tests/unit/persistence/test_decision_scope_links.py
@@ -0,0 +1,347 @@
+"""Every writer that moves a decision's scope moves its graph links with it.
+
+The JSON arrays are a read cache; ``decision_node_links`` is what the
+edit-time injection hook and the ``get_risk`` directives query. A record whose
+scope reached one and not the other is stored and then ignored by every
+path-scoped surface.
+"""
+
+from __future__ import annotations
+
+import json
+
+from sqlalchemy import delete, select
+
+from repowise.core.analysis.decisions.scope import (
+ SCOPE_BASIS_REPOSITORY,
+ SCOPE_BASIS_STATED,
+)
+from repowise.core.persistence.crud import (
+ recompute_decision_staleness,
+ update_decision_by_id,
+ update_decision_metadata,
+ update_decision_status,
+ upsert_decision,
+)
+from repowise.core.persistence.crud.authority import (
+ accept_decision,
+ dismiss_candidate,
+ record_acceptance,
+)
+from repowise.core.persistence.decision_graph import (
+ expected_node_links,
+ get_governed_nodes,
+ get_governing_decisions,
+ sync_links_from_record,
+)
+from repowise.core.persistence.decision_migration import backfill_decision_node_links
+from repowise.core.persistence.models import DecisionNodeLink
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def _add(session, repo_id: str, **kwargs):
+ return await upsert_decision(
+ session,
+ repository_id=repo_id,
+ title=kwargs.pop("title", "Use one queue"),
+ decision="One queue, not three.",
+ source="cli",
+ **kwargs,
+ )
+
+
+async def _links(session, decision_id: str) -> set[tuple[str, str]]:
+ rows = await session.execute(
+ select(DecisionNodeLink.node_id, DecisionNodeLink.link_type).where(
+ DecisionNodeLink.decision_id == decision_id
+ )
+ )
+ return set(rows.all())
+
+
+async def test_decision_add_reaches_the_governing_lookup(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ governing = await get_governing_decisions(async_session, repo.id, "a/one.py")
+ assert [r.id for r in governing] == [rec.id]
+
+
+async def test_a_first_write_states_its_basis_like_a_restate_does(async_session):
+ """Both arms of ``upsert_decision``, or the same call gives two bases."""
+ repo = await insert_repo(async_session)
+ first = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ assert first.scope_basis == SCOPE_BASIS_STATED
+
+ again = await _add(async_session, repo.id, affected_files=["a/one.py", "b/two.py"])
+ assert again.scope_basis == SCOPE_BASIS_STATED
+
+
+async def test_restating_a_record_replaces_its_links(async_session):
+ repo = await insert_repo(async_session)
+ first = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ again = await _add(async_session, repo.id, affected_files=["b/two.py"])
+
+ assert again.id == first.id
+ assert await _links(async_session, first.id) == {("b/two.py", "file"), ("b", "module")}
+
+
+async def test_a_non_binding_basis_links_nothing_despite_its_files(async_session):
+ """The gate, not the empty case: files present, basis that does not bind."""
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ assert await _links(async_session, rec.id) == {("a/one.py", "file"), ("a", "module")}
+
+ rec.scope_basis = SCOPE_BASIS_REPOSITORY
+ await sync_links_from_record(async_session, rec)
+
+ assert await _links(async_session, rec.id) == set()
+
+
+async def test_confirm_with_a_scope_links_the_files_it_chose(async_session):
+ """``decision add`` points a candidate at ``confirm --scope``; that is this."""
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=[])
+ assert await _links(async_session, rec.id) == set()
+
+ await accept_decision(
+ async_session,
+ rec,
+ accepter="dev",
+ scope=["c/three.py"],
+ reason="one queue is enough",
+ )
+
+ # The module is derived from the accepter's files, not left as it was.
+ assert await _links(async_session, rec.id) == {("c/three.py", "file"), ("c", "module")}
+
+
+async def test_an_accepted_scope_leaves_no_module_from_the_old_one(async_session):
+ """Half a scope moving is worse than none: the stale module still governs."""
+ repo = await insert_repo(async_session)
+ rec = await _add(
+ async_session, repo.id, affected_files=["old/one.py"], affected_modules=["old"]
+ )
+ assert ("old", "module") in await _links(async_session, rec.id)
+
+ await accept_decision(
+ async_session, rec, accepter="dev", scope=["new/two.py"], reason="moved"
+ )
+
+ assert await _links(async_session, rec.id) == {("new/two.py", "file"), ("new", "module")}
+
+
+async def test_a_dismissed_record_governs_nothing(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ assert await _links(async_session, rec.id)
+
+ rec.status = "dismissed"
+ await sync_links_from_record(async_session, rec)
+
+ assert await _links(async_session, rec.id) == set()
+ assert await get_governing_decisions(async_session, repo.id, "a/one.py") == []
+
+
+async def test_the_backfill_unlinks_a_dismissed_record(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ rec.status = "dismissed"
+ await async_session.flush()
+
+ assert await backfill_decision_node_links(async_session, repo.id) == 1
+
+ assert await _links(async_session, rec.id) == set()
+
+
+async def test_the_module_repair_relinks_what_it_rewrites(async_session):
+ """The repair runs after the backfill, so its own rewrite must relink."""
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["packages/core/one.py"])
+ # The legacy derivation: module = first path segment.
+ rec.affected_modules_json = json.dumps(["packages"])
+ await sync_links_from_record(async_session, rec)
+ assert ("packages", "module") in await _links(async_session, rec.id)
+
+ await recompute_decision_staleness(async_session, repo.id, {})
+
+ links = await _links(async_session, rec.id)
+ assert ("packages", "module") not in links
+ assert ("packages/core", "module") in links
+
+
+async def test_metadata_and_by_id_patches_move_the_links(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ await update_decision_metadata(
+ async_session, rec.id, affected_files=["d/four.py"], affected_modules=["d"]
+ )
+ assert await _links(async_session, rec.id) == {("d/four.py", "file"), ("d", "module")}
+
+ await update_decision_by_id(async_session, rec.id, affected_files=["e/five.py"])
+ nodes = {(n.node_id, n.link_type) for n in await get_governed_nodes(async_session, rec.id)}
+ assert nodes == {("e/five.py", "file"), ("e", "module")}
+
+
+async def test_clearing_a_scope_clears_the_links(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ await update_decision_metadata(async_session, rec.id, affected_files=[])
+
+ assert await _links(async_session, rec.id) == set()
+
+
+async def test_expected_links_ignore_a_malformed_array(async_session):
+ """Each half is guarded on its own; a broken one contributes nothing."""
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ rec.affected_files_json = "{not json"
+ assert expected_node_links(rec) == ([], ["a"])
+
+ rec.affected_modules_json = "[1, null]"
+ assert expected_node_links(rec) == ([], [])
+
+
+async def test_backfill_relinks_a_record_written_before_the_writer(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ # The pre-fix vintage: arrays written, graph never touched.
+ await async_session.execute(
+ delete(DecisionNodeLink).where(DecisionNodeLink.decision_id == rec.id)
+ )
+ await async_session.flush()
+ assert await _links(async_session, rec.id) == set()
+
+ assert await backfill_decision_node_links(async_session, repo.id) == 1
+
+ assert await _links(async_session, rec.id) == {("a/one.py", "file"), ("a", "module")}
+
+
+async def test_backfill_is_idempotent(async_session):
+ repo = await insert_repo(async_session)
+ await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ assert await backfill_decision_node_links(async_session, repo.id) == 0
+
+
+async def test_a_patch_that_moves_files_moves_the_modules(async_session):
+ """The PATCH route sends files and no modules; the old module must not stay."""
+ repo = await insert_repo(async_session)
+ rec = await _add(
+ async_session, repo.id, affected_files=["packages/cli/q.py"], affected_modules=["packages/cli"]
+ )
+
+ await update_decision_metadata(async_session, rec.id, affected_files=["packages/core/q.py"])
+
+ assert await _links(async_session, rec.id) == {
+ ("packages/core/q.py", "file"),
+ ("packages/core", "module"),
+ }
+
+
+async def test_an_explicit_empty_module_list_still_clears(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ await update_decision_metadata(
+ async_session, rec.id, affected_files=["b/two.py"], affected_modules=[]
+ )
+
+ assert await _links(async_session, rec.id) == {("b/two.py", "file")}
+
+
+async def test_a_deprecated_record_governs_nothing(async_session):
+ """The literal ``dismiss`` writes is not the only withdrawal."""
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ await update_decision_status(async_session, rec.id, "deprecated")
+
+ assert await _links(async_session, rec.id) == set()
+
+
+async def test_a_dismissal_unlinks_without_waiting_for_an_index(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ await update_decision_status(async_session, rec.id, "dismissed")
+
+ assert await get_governing_decisions(async_session, repo.id, "a/one.py") == []
+
+
+async def test_a_revival_relinks_without_waiting_for_an_index(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ await update_decision_status(async_session, rec.id, "dismissed")
+ assert await _links(async_session, rec.id) == set()
+
+ await update_decision_status(async_session, rec.id, "proposed")
+
+ assert ("a/one.py", "file") in await _links(async_session, rec.id)
+
+
+async def test_a_withdrawal_through_the_acceptance_log_unlinks(async_session):
+ """``record_acceptance`` is the sole writer of the status projection."""
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ await accept_decision(async_session, rec, accepter="dev", reason="keep one queue")
+ assert await _links(async_session, rec.id)
+
+ await record_acceptance(
+ async_session,
+ rec,
+ action="dismissed",
+ currency="dismissed",
+ accepter="dev",
+ kind="person",
+ )
+
+ assert await _links(async_session, rec.id) == set()
+
+
+async def test_dismissing_a_candidate_unlinks_it(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+ assert await _links(async_session, rec.id)
+
+ await dismiss_candidate(async_session, rec, reason="wrong", accepter="dev")
+
+ assert await _links(async_session, rec.id) == set()
+
+
+async def test_a_superseded_record_keeps_its_links(async_session):
+ """`get_risk`'s superseded_decision directive finds the record through them.
+
+ A withdrawal leaves nothing in the decision's place; a supersession leaves
+ a successor, and telling a reviewer their change is governed by a decision
+ that has been replaced is the whole point of that directive.
+ """
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ await update_decision_status(async_session, rec.id, "superseded")
+
+ assert ("a/one.py", "file") in await _links(async_session, rec.id)
+ assert [r.id for r in await get_governing_decisions(async_session, repo.id, "a/one.py")] == [
+ rec.id
+ ]
+
+
+async def test_upsert_honours_an_explicit_empty_module_list(async_session):
+ """`[]` clears in every writer, or the same input means two things."""
+ repo = await insert_repo(async_session)
+ rec = await _add(
+ async_session, repo.id, affected_files=["a/one.py"], affected_modules=[]
+ )
+
+ assert await _links(async_session, rec.id) == {("a/one.py", "file")}
+
+
+async def test_upsert_derives_modules_when_none_are_given(async_session):
+ repo = await insert_repo(async_session)
+ rec = await _add(async_session, repo.id, affected_files=["a/one.py"])
+
+ assert await _links(async_session, rec.id) == {("a/one.py", "file"), ("a", "module")}
diff --git a/tests/unit/server/test_decisions_api.py b/tests/unit/server/test_decisions_api.py
index 9167313cb..598a44662 100644
--- a/tests/unit/server/test_decisions_api.py
+++ b/tests/unit/server/test_decisions_api.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import pytest
from httpx import AsyncClient
+from sqlalchemy import delete
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
@@ -88,8 +89,16 @@ async def _seed_lineage(session_factory, repo_id: str, old_id: str, new_id: str)
async def _seed_code_link(session_factory, repo_id: str, decision_id: str) -> None:
- """Insert a DecisionNodeLink row directly."""
+ """State this repository's whole code graph as one link.
+
+ Creating a decision now mirrors its scope into the graph, so every seeded
+ decision brings links of its own. Clearing first is what lets the caller
+ assert on an exact edge count.
+ """
async with get_session(session_factory) as session:
+ await session.execute(
+ delete(DecisionNodeLink).where(DecisionNodeLink.repository_id == repo_id)
+ )
session.add(
DecisionNodeLink(
repository_id=repo_id,
diff --git a/tests/unit/server/test_decisions_patch.py b/tests/unit/server/test_decisions_patch.py
index cd709765e..99360f864 100644
--- a/tests/unit/server/test_decisions_patch.py
+++ b/tests/unit/server/test_decisions_patch.py
@@ -81,8 +81,9 @@ async def test_patch_decision_clear_files(client: AsyncClient, app) -> None:
assert resp.status_code == 200
body = resp.json()
assert body["affected_files"] == []
- # Modules untouched (None means preserve).
- assert body["affected_modules"] == ["packages/core"]
+ # Modules follow the files they describe, so clearing one clears the
+ # other: a record naming no file must not keep governing a whole subtree.
+ assert body["affected_modules"] == []
@pytest.mark.asyncio
diff --git a/tests/unit/server/test_mcp_decision_graph.py b/tests/unit/server/test_mcp_decision_graph.py
index eb52254fa..ae036452a 100644
--- a/tests/unit/server/test_mcp_decision_graph.py
+++ b/tests/unit/server/test_mcp_decision_graph.py
@@ -12,6 +12,7 @@ import json
from datetime import UTC, datetime
import pytest
+from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import StaticPool
@@ -338,6 +339,14 @@ async def decision_db(session: AsyncSession, repo_id: str) -> str:
)
await session.flush()
+ # Accepting a record now mirrors its scope into the graph, so clear that
+ # before writing the links this fixture wants: it states the graph
+ # exactly, rather than layering on whatever the scope arrays imply.
+ await session.execute(
+ delete(DecisionNodeLink).where(DecisionNodeLink.repository_id == rid)
+ )
+ await session.flush()
+
# DecisionNodeLink rows — the graph truth used by get_governing_decisions
links = [
DecisionNodeLink(