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.

refactor(core): split pipeline persist into a package by writer area (#3989)

Raghav Chamadiya8b92d6f98fdd
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 3653035d2..ac2a7cbe2 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -137,7 +137,7 @@ repowise/
│ │ │ │ └── claude_md.py # ClaudeMdGenerator subclass
│ │ │ ├── pipeline/
│ │ │ │ ├── orchestrator.py # run_pipeline(), PipelineResult
-│ │ │ │ ├── persist.py # persist_pipeline_result(): shared by CLI + server
+│ │ │ │ ├── persist/ # persist_pipeline_result(): shared by CLI + server
│ │ │ │ └── progress.py # ProgressCallback protocol + LoggingProgressCallback
│ │ │ ├── persistence/
│ │ │ │ ├── models.py # SQLAlchemy ORM models
@@ -696,13 +696,14 @@ sweep does not mistake "deliberately kept" for "no longer produced".
`repowise init` is fully idempotent. Running it twice produces the same result.
Running it after a partial previous run completes only the remaining pages.
-### 5.7 Shared Persistence (`pipeline/persist.py`)
+### 5.7 Shared Persistence (`pipeline/persist/`)
The persistence logic for storing a `PipelineResult` into the database (graph nodes,
edges, symbols, pages, git metadata, dead code findings, decision records) was
-extracted from the CLI's `init_cmd.py` into `core/pipeline/persist.py`. Both the
+extracted from the CLI's `init_cmd.py` into the `core/pipeline/persist/` package. Both the
CLI and the server's background job executor call `persist_pipeline_result()`, zero
-duplication.
+duplication. The package splits the writers by area (graph, prune, tombstones,
+sweeps, security, git, health, analysis, generation) and re-exports them all.
FTS indexing is intentionally excluded from this function. Callers must run it
separately after the session closes to avoid SQLite write-lock conflicts.
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 37372f67d..bf2f6477b 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -143,7 +143,7 @@ core/alembic/versions/
```
core/pipeline/
├── orchestrator.py # _run_health_analysis(): builds community_label_map, runs analyzer
-└── persist.py # persist_pipeline_result(): writes findings/metrics/snapshot
+└── persist/ # persist_pipeline_result(): writes findings/metrics/snapshot
```
### CLI
@@ -245,7 +245,7 @@ things:
smaller repos run `analyze()` on a single thread.
The returned report rides on `PipelineResult.health_report`. Then
-`core/pipeline/persist.py` writes it in one session: `save_health_metrics`,
+`core/pipeline/persist/` writes it in one session: `save_health_metrics`,
`save_health_findings` (only when there are findings), and a
`save_health_snapshot` carrying the three KPIs plus a `{path: score}` map for
trend tracking (rolling 50-row window per repo), and a second
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
deleted file mode 100644
index 91a7ecef9..000000000
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ /dev/null
@@ -1,2738 +0,0 @@
-"""Shared persistence logic for pipeline results.
-
-Extracted from ``cli/commands/init_cmd.py`` so both the CLI and the server
-can persist a ``PipelineResult`` without duplicating the upsert recipe.
-"""
-
-from __future__ import annotations
-
-import dataclasses
-import json
-import logging
-from collections.abc import Callable, Iterable
-from pathlib import Path
-from typing import Any
-
-import structlog
-
-from repowise.core.entry_candidacy import is_reachability_root
-from repowise.core.generation.models import (
- STRUCTURALLY_KEYED_PAGE_TYPES,
- STUB_FALLBACK_ERROR,
-)
-
-logger = structlog.get_logger(__name__)
-
-#: Candidate paths per spotlight query: each path is one ``LIKE`` term, and
-#: SQLite caps how deep an expression tree may grow.
-_SPOTLIGHT_PATHS_PER_QUERY = 200
-
-# A second, stdlib logger for the one message here that has to survive
-# ``repowise init``. ``configure_cli_logging`` pins both ``repowise.core`` and
-# structlog to ERROR for the progress-bar commands, so anything below ERROR is
-# discarded in the exact command that writes the index. The refusal below is
-# logged through this at ERROR for that reason; the routine counts stay on
-# structlog with their siblings.
-_log = logging.getLogger(__name__)
-
-# Max page ids per UPDATE ... IN (...) so a large cascade cannot exceed
-# SQLite's bound-variable limit on the local CLI store.
-_STALE_ID_CHUNK = 500
-
-
-def tombstone_candidates(file_diffs: list[Any]) -> list[tuple[str, list[str]]]:
- """(dead_path, successor_paths) pairs from deleted/renamed file diffs.
-
- A renamed file's old path gets its new path as the successor; a deleted
- file has no successor. Diffs of other statuses contribute nothing.
- """
- out: list[tuple[str, list[str]]] = []
- for fd in file_diffs or []:
- status = getattr(fd, "status", None)
- if status == "deleted" and fd.path:
- out.append((fd.path, []))
- elif status == "renamed" and fd.old_path:
- out.append((fd.old_path, [fd.path] if fd.path else []))
- return out
-
-
-async def mark_tombstone_pages(
- session: Any, repo_id: str, candidates: list[tuple[str, list[str]]]
-) -> list[str]:
- """Mark the pages of deleted/renamed files as tombstones: each file's page
- and the symbol spotlight pages of the symbols it defined.
-
- A ``freshness_status="fresh"`` page for a file that no longer exists is
- an active trap: retrieval serves it, agents cite it, and the index-age
- metadata says nothing is wrong. Tombstoned pages keep their content
- (the prose may still orient a reader) but carry status=tombstone and
- ``successor_paths`` in metadata so serving layers can skip or redirect.
-
- Returns the page ids marked, so the caller can drop them from the
- full-text index once its session has closed. Every serving layer already
- discards a tombstone, but retrieval fetches a fixed number of rows before
- any of that runs, so a tombstone still takes one of those slots and pushes
- a real candidate out of the fetch. The row has to go, and only the caller
- knows when it is safe to write to the index — on SQLite it shares a file
- with this session.
- """
- if not candidates:
- return []
- from sqlalchemy import or_, select
-
- from repowise.core.persistence.models import Page
-
- page_ids = {f"file_page:{path}": (path, successors) for path, successors in candidates}
- pages = list(
- (
- await session.execute(
- select(Page).where(Page.repository_id == repo_id, Page.id.in_(page_ids))
- )
- ).scalars()
- )
- # A symbol spotlight page targets ``<path>::<symbol>``, so its id is never
- # ``file_page:<path>``; it goes with its file all the same. Matched on the
- # ``<path>::`` prefix, so a file whose name merely starts with *path* stays.
- successors_by_path = dict(candidates)
- paths = list(successors_by_path)
- for start in range(0, len(paths), _SPOTLIGHT_PATHS_PER_QUERY):
- chunk = paths[start : start + _SPOTLIGHT_PATHS_PER_QUERY]
- res = await session.execute(
- select(Page).where(
- Page.repository_id == repo_id,
- Page.page_type == "symbol_spotlight",
- or_(*(Page.target_path.startswith(f"{p}::", autoescape=True) for p in chunk)),
- )
- )
- for page in res.scalars():
- path = (page.target_path or "").split("::", 1)[0]
- # SQLite LIKE ignores ASCII case, so ``pkg/Foo.py::`` also matches
- # a live ``pkg/foo.py``; keep only exact path matches.
- if path not in successors_by_path:
- continue
- page_ids[page.id] = (path, successors_by_path.get(path, []))
- pages.append(page)
- marked: list[str] = []
- for page in pages:
- _, successors = page_ids[page.id]
- page.freshness_status = "tombstone"
- try:
- meta = json.loads(page.metadata_json or "{}")
- except (json.JSONDecodeError, TypeError):
- meta = {}
- meta["successor_paths"] = successors
- page.metadata_json = json.dumps(meta)
- marked.append(page.id)
- if marked:
- logger.info("pages_tombstoned", repo_id=repo_id, count=len(marked))
- elif candidates:
- # Candidates existed but no page matched — the id scheme drifted from
- # ``file_page:{path}`` or the paths don't line up. Silent success here
- # would let stale pages keep serving, so surface it.
- logger.debug(
- "tombstone_no_match",
- repo_id=repo_id,
- candidate_count=len(candidates),
- sample=[p for p, _ in candidates[:3]],
- )
- return marked
-
-
-async def tombstone_file_pages_outside_scope(
- session: Any, repo_id: str, current_file_paths: set[str]
-) -> list[str]:
- """Tombstone active source-backed pages outside a full traversal's scope.
-
- Files removed by ``exclude_patterns`` still exist on disk, so the ordinary
- deleted-file tombstone path cannot identify them. A successful full
- traversal can: any active file page outside its parsed-file set is no longer
- part of this index.
- """
- from sqlalchemy import select
-
- from repowise.core.persistence.models import Page
-
- pages = (
- await session.execute(
- select(Page).where(
- Page.repository_id == repo_id,
- Page.page_type.in_(("file_page", "api_contract", "infra_page", "symbol_spotlight")),
- Page.freshness_status != "tombstone",
- )
- )
- ).scalars()
- marked: list[str] = []
- for page in pages:
- target = page.target_path or ""
- source_path = target.split("::", 1)[0] if page.page_type == "symbol_spotlight" else target
- if source_path in current_file_paths:
- continue
- page.freshness_status = "tombstone"
- try:
- metadata = json.loads(page.metadata_json or "{}")
- except (json.JSONDecodeError, TypeError):
- metadata = {}
- metadata["successor_paths"] = []
- page.metadata_json = json.dumps(metadata)
- marked.append(page.id)
- return marked
-
-
-async def reconcile_full_index_scope(
- session: Any,
- repo_id: str,
- current_graph_paths: set[str],
- current_git_paths: set[str],
-) -> list[str]:
- """Reconcile every source-backed store against one successful traversal."""
- tombstoned = await tombstone_file_pages_outside_scope(session, repo_id, current_graph_paths)
- await _prune_stale_file_rows(
- session,
- repo_id,
- current_graph_paths,
- current_git_paths,
- authoritative_empty=True,
- )
- from repowise.core.persistence.crud.decisions import (
- purge_proposed_decisions_outside_files,
- )
-
- await purge_proposed_decisions_outside_files(session, repo_id, current_graph_paths)
- return tombstoned
-
-
-async def tombstone_pages_outside_generation(
- session: Any, repo_id: str, current_page_ids: set[str]
-) -> list[str]:
- """Retire generated pages absent from an authoritative full generation.
-
- This is used only when generation configuration changed and the update ran
- the complete generation ladder. It covers selection changes such as page
- caps, spotlight ranking, and disabling onboarding, none of which imply that
- the backing source file disappeared.
- """
- from sqlalchemy import select
-
- from repowise.core.generation.models import GENERATION_LEVELS
- from repowise.core.persistence.models import Page
-
- pages = (
- await session.execute(
- select(Page).where(
- Page.repository_id == repo_id,
- Page.page_type.in_(tuple(GENERATION_LEVELS)),
- Page.freshness_status != "tombstone",
- )
- )
- ).scalars()
- marked: list[str] = []
- for page in pages:
- if page.id in current_page_ids:
- continue
- page.freshness_status = "tombstone"
- try:
- metadata = json.loads(page.metadata_json or "{}")
- except (json.JSONDecodeError, TypeError):
- metadata = {}
- metadata["successor_paths"] = []
- page.metadata_json = json.dumps(metadata)
- marked.append(page.id)
- return marked
-
-
-async def tombstone_absent_file_pages(
- session: Any, repo_id: str, repo_path: Path | str
-) -> list[str]:
- """Tombstone every file page whose file is no longer on disk.
-
- :func:`mark_tombstone_pages` works from a diff, so it only ever sees a
- file that was deleted or renamed *between two commits this run compared*.
- ``repowise init`` compares nothing — it indexes a checkout as it stands —
- so it has never tombstoned anything, and a page written before a file was
- deleted keeps ``freshness_status='fresh'`` through every later index.
-
- That page is the trap the tombstone exists to close: retrieval serves it,
- agents cite it, and the index-age metadata says nothing is wrong.
-
- The check is a plain existence test against the checkout rather than a
- comparison with what this run parsed. A file can be present but unparsed —
- an unsupported extension, a parse failure, a changed exclude list — and
- such a file is stale, not deleted. Calling it deleted would put a
- ``successor_paths: []`` on a page whose file a reader can still open.
-
- Returns the page ids marked, so the caller can drop them from the
- full-text index once its session has closed, on the same terms as
- :func:`mark_tombstone_pages`.
- """
- from sqlalchemy import select
-
- from repowise.core.persistence.models import Page
-
- root = Path(repo_path)
- res = await session.execute(
- select(Page).where(
- Page.repository_id == repo_id,
- Page.page_type == "file_page",
- Page.freshness_status != "tombstone",
- )
- )
- live = list(res.scalars().all())
- if not live:
- return []
-
- absent = [p for p in live if not (root / (p.target_path or "")).exists()]
- if not absent:
- return []
-
- # Every page absent means the paths are not being resolved against the
- # tree they were written from — a wrong root, a bare-repo checkout, a
- # working copy that has not been restored yet. Tombstoning the whole wiki
- # on that reading is worse than leaving it, and unlike a partial mistake
- # it is not recoverable by re-indexing a file. Refuse, loudly, and let the
- # rest of the run proceed.
- if len(absent) == len(live):
- _log.error(
- "tombstone_sweep_refused repo_id=%s file_pages=%d root=%s: every file "
- "page's path is missing from the checkout, which reads as a wrong "
- "root rather than a deleted repository. Nothing was tombstoned.",
- repo_id,
- len(live),
- root,
- )
- return []
-
- marked: list[str] = []
- for page in absent:
- page.freshness_status = "tombstone"
- try:
- meta = json.loads(page.metadata_json or "{}")
- except (json.JSONDecodeError, TypeError):
- meta = {}
- # Deleted, not renamed: rename detection is the diff-driven sweep's
- # job and it has evidence this one does not.
- meta["successor_paths"] = []
- page.metadata_json = json.dumps(meta)
- marked.append(page.id)
-
- logger.info(
- "file_pages_tombstoned_absent",
- repo_id=repo_id,
- count=len(marked),
- sample=[p.target_path for p in absent[:3]],
- )
- return marked
-
-
-async def mark_stale_pages(session: Any, repo_id: str, paths: Iterable[str]) -> int:
- """Decay weakly-affected file pages to ``freshness_status='stale'``.
-
- ``ChangeDetector.get_affected_pages`` returns ``decay_only`` — pages hit
- by the change cascade but beyond the regeneration budget (budget
- overflow, co-change partners, 2-hop rename fallout). They keep serving
- their existing content, but the stale bit makes the coverage view and
- ``get_stale_pages`` truthful so the next docs run (or a reader) knows
- they lag the code. Only ``fresh`` pages are downgraded — tombstoned or
- already-stale pages keep their stronger status, and pages regenerated in
- this run are never in ``decay_only`` by construction.
-
- Maps each path to its ``file_page:<path>`` id and hands off to
- :func:`mark_page_ids_stale`, so both entry points share one UPDATE.
-
- The two were separate copies of the same statement, and only the sibling
- was chunked against ``SQLITE_MAX_VARIABLE_NUMBER``. That is not a crash
- anyone is hitting today: SQLite has defaulted to 32766 bind variables since
- 3.32, and a ``decay_only`` set that large would take an enormous cascade.
- It is reachable on the 999-variable builds older interpreters still ship,
- but the reason to collapse the two is narrower than that. They answered the
- same question differently, in the file with the most bug fixes in this repo,
- and now there is one place to answer it.
-
- Returns the number of pages marked.
- """
- return await mark_page_ids_stale(session, repo_id, (f"file_page:{path}" for path in paths))
-
-
-async def mark_page_ids_stale(session: Any, repo_id: str, page_ids: Iterable[str]) -> int:
- """Decay arbitrary pages to ``freshness_status='stale'`` by full page id.
-
- The sibling of :func:`mark_stale_pages`, which only understands
- ``file_page:<path>`` ids. Scoped generation's cascade needs to mark
- dependents of every type — module, SCC, layer and the repo-wide overview /
- architecture / onboarding pages — stale when the run regenerated a file but
- not its summaries. Same ``fresh``-only downgrade so a tombstoned or
- already-stale page keeps its stronger status.
-
- Returns the number of pages marked.
- """
- ids = list(dict.fromkeys(page_ids)) # dedupe, preserve order
- if not ids:
- return 0
- from sqlalchemy import update
-
- from repowise.core.persistence.models import Page
-
- # Chunk the IN list: SQLite (the local CLI store) binds one variable per id
- # and caps at SQLITE_MAX_VARIABLE_NUMBER, so a large cascade could exceed it.
- marked = 0
- for i in range(0, len(ids), _STALE_ID_CHUNK):
- batch = ids[i : i + _STALE_ID_CHUNK]
- res = await session.execute(
- update(Page)
- .where(
- Page.repository_id == repo_id,
- Page.id.in_(batch),
- Page.freshness_status == "fresh",
- )
- .values(freshness_status="stale")
- )
- marked += int(res.rowcount or 0)
- if marked:
- logger.info("pages_decayed_stale", repo_id=repo_id, count=marked)
- return marked
-
-
-def _derive_entry_point_scores(graph_builder: Any) -> dict[str, float]:
- """Best-effort entry-point scores from the builder's execution-flow report.
-
- Returns ``{node_id: score}`` for every scored entry-point candidate (not
- just the ones that produced a traced flow). The call is cached on the
- builder, so this is cheap when flows were already computed.
- """
- try:
- report = graph_builder.execution_flows()
- except Exception as exc: # analysis is non-load-bearing for persistence
- logger.warning("entry_point_scores_derive_failed", error=str(exc))
- return {}
- if report is None:
- return {}
- scores = getattr(report, "entry_point_scores", None)
- if scores:
- return dict(scores)
- # Back-compat: older reports only expose per-flow scores.
- return {
- f.entry_point_id: f.entry_point_score
- for f in getattr(report, "flows", []) or []
- if hasattr(f, "entry_point_id") and hasattr(f, "entry_point_score")
- }
-
-
-def _betweenness_commits(graph_builder: Any) -> dict[str, str | None]:
- """Per kind, the commit its betweenness was last exactly computed at.
-
- ``None`` means the builder cannot say, which is not "never scored" and must
- not be written as one: a builder rehydrated from SQL serves real values it
- did not compute, and stamping those NULL would report an entire indexed
- repository as unscored.
- """
- scoring = getattr(graph_builder, "betweenness_scoring", None)
- if scoring is None:
- return {"file": None, "symbol": None}
- try:
- return {k: getattr(scoring(k), "scored_commit", None) for k in ("file", "symbol")}
- except Exception: # pragma: no cover - a builder without the accessor
- return {"file": None, "symbol": None}
-
-
-def _stamp_betweenness_commit(
- node_dict: dict[str, Any],
- node_type: str,
- bc: dict[str, float],
- sym_bc: dict[str, float],
- bt_commits: dict[str, str | None],
-) -> None:
- """Set ``betweenness_commit`` on a graph-node row when its scoring is known."""
- node_id = node_dict["node_id"]
- # Scored → its commit; in no scoring → NULL, the unscored marker;
- # provenance unknown → key omitted, so the stored stamp survives.
- if node_id in bc:
- kind, scored = "file", True
- elif node_id in sym_bc:
- kind, scored = "symbol", True
- else:
- kind, scored = ("file" if node_type == "file" else "symbol"), False
- if bt_commits[kind] is not None:
- node_dict["betweenness_commit"] = bt_commits[kind] if scored else None
-
-
-def _community_meta(
- node_id: str,
- node_type: str,
- cd: dict[str, Any],
- sc: dict[str, Any],
- ci: dict[Any, Any],
- ep_scores: dict[str, float],
-) -> dict[str, Any]:
- """The ``community_meta_json`` payload of one graph node."""
- community_meta: dict[str, Any] = {}
- if node_type == "file":
- cid = cd.get(node_id, 0)
- comm_info = ci.get(cid)
- if comm_info:
- community_meta = {
- "label": comm_info.label,
- "cohesion": comm_info.cohesion,
- "conductance": comm_info.conductance,
- }
- elif node_type == "symbol":
- sym_cid = sc.get(node_id)
- if sym_cid is not None:
- community_meta = {"symbol_community_id": sym_cid}
- if node_id in ep_scores:
- community_meta["entry_point_score"] = ep_scores[node_id]
- return community_meta
-
-
-async def persist_graph_nodes(
- session: Any,
- repo_id: str,
- graph_builder: Any,
- ep_scores: dict[str, float] | None = None,
- *,
- timings: Any | None = None,
-) -> None:
- """Persist file- and symbol-level graph nodes with full centrality metrics.
-
- Lifted out of :func:`persist_pipeline_result` so the incremental
- update path can refresh ``graph_nodes`` (including symbol-level
- PageRank / betweenness) without constructing a full ``PipelineResult``.
- """
- from repowise.core.analysis.communities import stored_community_id
- from repowise.core.persistence import (
- batch_upsert_graph_metrics,
- batch_upsert_graph_node_membership,
- batch_upsert_graph_nodes,
- )
- from repowise.core.pipeline.phase_timing import timed
-
- graph = graph_builder.graph()
- with timed(timings, "persist.graph_nodes.metrics"):
- pr = graph_builder.pagerank()
- bc = graph_builder.betweenness_centrality()
- sym_pr = graph_builder.symbol_pagerank()
- sym_bc = graph_builder.symbol_betweenness_centrality()
- cd = graph_builder.community_detection()
- sc = graph_builder.symbol_communities()
- ci = graph_builder.community_info()
- # ``None`` means "derive scores from the graph" (the incremental update
- # path passes nothing). An explicit ``{}`` means "no scores" and is left
- # untouched. Without this, every ``update`` re-upserted symbol nodes with
- # empty community_meta and wiped the entry_point_scores written at init,
- # leaving get_execution_flows / the dashboard panel permanently empty.
- if ep_scores is None:
- with timed(timings, "persist.graph_nodes.entry_points"):
- ep_scores = _derive_entry_point_scores(graph_builder)
-
- bt_commits = _betweenness_commits(graph_builder)
-
- timings_rows = timed(timings, "persist.graph_nodes.rows")
- timings_rows.__enter__()
- nodes = []
- for node_id in graph.nodes:
- data = graph.nodes[node_id]
- node_type = data.get("node_type", "file")
-
- node_dict: dict[str, Any] = {
- "node_id": node_id,
- "node_type": node_type,
- "language": data.get("language", "unknown"),
- "symbol_count": data.get("symbol_count", 0),
- "has_error": data.get("has_error", False),
- "is_test": data.get("is_test", False),
- "is_entry_point": data.get("is_entry_point", False),
- "is_reachability_root": is_reachability_root(data),
- "always_run_reason": data.get("always_run_reason"),
- # Files draw from the file-level metric tables; symbols fall
- # back to the symbol subgraph (calls + heritage) so that the
- # per-symbol UI panel shows real centrality instead of 0.
- "pagerank": pr.get(node_id, sym_pr.get(node_id, 0.0)),
- "betweenness": bc.get(node_id, sym_bc.get(node_id, 0.0)),
- "community_id": stored_community_id(cd, node_id),
- }
-
- _stamp_betweenness_commit(node_dict, node_type, bc, sym_bc, bt_commits)
-
- community_meta = _community_meta(node_id, node_type, cd, sc, ci, ep_scores)
- node_dict["community_meta_json"] = json.dumps(community_meta)
-
- if node_type == "symbol":
- node_dict.update(
- {
- "kind": data.get("kind"),
- "name": data.get("name"),
- "qualified_name": data.get("qualified_name"),
- "file_path": data.get("file_path"),
- "start_line": data.get("start_line"),
- "end_line": data.get("end_line"),
- "visibility": data.get("visibility"),
- "signature": data.get("signature"),
- "parent_symbol_id": data.get("parent_name"),
- "public_api": data.get("public_api"),
- }
- )
- nodes.append(node_dict)
- timings_rows.__exit__(None, None, None)
-
- if nodes:
- with timed(timings, "persist.graph_nodes.upsert"):
- await batch_upsert_graph_nodes(session, repo_id, nodes)
-
- # Materialize the file-level metrics snapshot (graph_metrics) so large
- # repos can serve metric reads from SQL without recomputing the NetworkX
- # centrality kernels. Additive to graph_nodes; never changes node rows.
- try:
- with timed(timings, "persist.graph_nodes.snapshots"):
- await batch_upsert_graph_metrics(
- session, repo_id, graph_builder.file_metrics_snapshot()
- )
- except Exception as exc: # materialization is non-load-bearing
- logger.warning("graph_metrics_materialize_skipped", error=str(exc))
-
- # Materialize file-level SCCs (import cycles) + symbol communities as
- # queryable rows (graph_node_membership). Feeds the break-cycle /
- # move-method refactoring surfaces; non-load-bearing like graph_metrics.
- try:
- with timed(timings, "persist.graph_nodes.snapshots"):
- await batch_upsert_graph_node_membership(
- session, repo_id, graph_builder.node_membership_snapshot()
- )
- except Exception as exc: # materialization is non-load-bearing
- logger.warning("graph_node_membership_materialize_skipped", error=str(exc))
-
-
-def _changed_file_symbols(
- parsed_files: list[Any] | None, changed_paths: list[str]
-) -> tuple[list[str], list[Any]]:
- """``(reconcile_paths, symbols)`` for files that both changed and parsed.
-
- Restricting to the intersection means a changed file that failed to parse
- this run keeps its existing symbol rows (mirrors the graph, which skips
- unparsed files) rather than having them wrongly pruned on a transient
- failure. Mutates ``sym.file_path`` where the parser left it unset, same as
- the full persist path.
- """
- changed = set(changed_paths or [])
- reconcile_paths: list[str] = []
- symbols: list[Any] = []
- for pf in parsed_files or []:
- path = pf.file_info.path
- if path not in changed:
- continue
- reconcile_paths.append(path)
- for sym in pf.symbols:
- if not getattr(sym, "file_path", None):
- sym.file_path = path
- symbols.append(sym)
- return reconcile_paths, symbols
-
-
-async def persist_incremental_symbols(
- session: Any,
- repo_id: str,
- parsed_files: list[Any] | None,
- changed_paths: list[str],
-) -> None:
- """Refresh ``wiki_symbols`` for changed+parsed files on an incremental update.
-
- The incremental update path re-parses changed files but never persisted
- their symbols, so wiki_symbols bounds fossilized at the last full index and
- the get_answer hydrator served drifted signatures/bodies. This upserts the
- changed files' fresh symbols and prunes symbols that vanished from a
- still-existing file. Scoped to the changed set for cost — the repo-wide
- ``batch_upsert_symbols`` reloads every symbol row.
- """
- if not parsed_files:
- return
- from repowise.core.ingestion.parse_cache import parser_fingerprint
- from repowise.core.persistence.crud import reconcile_symbols_for_files
-
- # An extraction change can re-key symbols in files git did not touch (an
- # overload gaining its own id), so it widens to the whole parsed set on the
- # same check that widens edges. The stamp is written once, by
- # :func:`persist_incremental_edges`, which runs after this.
- if await _stored_edges_parser_fingerprint(session, repo_id) != parser_fingerprint():
- changed_paths = [pf.file_info.path for pf in parsed_files]
- reconcile_paths, symbols = _changed_file_symbols(parsed_files, changed_paths)
- if not reconcile_paths:
- return
- await reconcile_symbols_for_files(session, repo_id, reconcile_paths, symbols)
-
-
-async def persist_symbol_analysis(
- session: Any,
- repo_id: str,
- parsed_files: list[Any] | None,
-) -> None:
- """Reconcile symbol rows after analysis mutates their derived fields.
-
- Health analysis computes ``complexity_estimate`` on the in-memory symbols
- after the resumable INDEX checkpoint has already persisted the parser
- defaults. Re-upsert just those symbol records before ANALYSIS is marked
- complete; graph construction, Git analysis, and the rest of ingestion stay
- untouched. The upsert preserves each persisted row's database identity.
- """
- if not parsed_files:
- return
- from repowise.core.persistence.crud import batch_upsert_symbols
-
- symbols: list[Any] = []
- for pf in parsed_files:
- for sym in pf.symbols:
- if not getattr(sym, "file_path", None):
- sym.file_path = pf.file_info.path
- symbols.append(sym)
- if symbols:
- await batch_upsert_symbols(session, repo_id, symbols)
-
-
-def _changed_file_edges(
- graph_builder: Any,
- parsed_files: list[Any] | None,
- changed_paths: list[str],
-) -> tuple[list[str], list[dict]]:
- """``(reconcile_paths, edges)`` for edges emanating from changed+parsed files.
-
- An edge is attributed to the file that owns its *source* node: a file node
- is the path itself; a symbol node carries ``file_path``. An edge whose fact
- sits at its target (``TARGET_OWNED_HINTS``) belongs to the target's file
- as well, so editing the decorated file rewrites it. Restricting to
- files that both changed and parsed this run mirrors ``_changed_file_symbols``
- — a changed file that failed to parse keeps its existing edges rather than
- having them wrongly wiped on a transient failure.
- """
- from repowise.core.ingestion.models import TARGET_OWNED_HINTS
-
- changed = set(changed_paths or [])
- parsed = {pf.file_info.path for pf in parsed_files or []}
- reconcile = changed & parsed
- if not reconcile:
- return [], []
-
- graph = graph_builder.graph()
- owner: dict[str, str | None] = {}
- for node_id in graph.nodes:
- data = graph.nodes[node_id]
- owner[node_id] = (
- node_id if data.get("node_type", "file") == "file" else data.get("file_path")
- )
-
- edges: list[dict] = []
- for u, v, data in graph.edges(data=True):
- if owner.get(u) in reconcile or (
- data.get("hint_source") in TARGET_OWNED_HINTS and owner.get(v) in reconcile
- ):
- edges.append(_edge_row(u, v, data))
- return sorted(reconcile), edges
-
-
-def _edge_row(source: str, target: str, data: dict) -> dict:
- """One ``graph_edges`` payload from an in-memory edge; both writers use it."""
- return {
- "source_node_id": source,
- "target_node_id": target,
- "imported_names_json": json.dumps(data.get("imported_names", [])),
- "edge_type": data.get("edge_type", "imports"),
- "confidence": data.get("confidence", 1.0),
- "hint_source": data.get("hint_source"),
- "resolution_origin": data.get("resolution_origin"),
- "call_lines_json": json.dumps(data.get("call_lines", [])),
- "type_only": bool(data.get("type_only", False)),
- "deferred": bool(data.get("deferred", False)),
- }
-
-
-async def _edges_predate_cohesion(session: Any, repo_id: str, graph_builder: Any) -> bool:
- """True when ``graph_edges`` was written before edge cohesion was recorded.
-
- An incremental update rewrites only the changed files' edges, so a store
- indexed by an older build keeps that build's edges — and its resolution
- mistakes — on every file that has not happened to change since. The health
- engine and the server both read a graph rehydrated from those rows, so they
- would go on reporting cycles the current engine no longer finds.
-
- The signal is the store's own content rather than a version marker: a
- routine update deliberately clamps ``store_format_version`` below the first
- reindex gate, so a version comparison would refire on every run. Here, a
- repo whose graph now has cohesion edges but whose table has no cohesion
- ``hint_source`` anywhere is exactly a pre-cohesion store. Rewriting it
- stamps those rows, so this answers False from then on and the full
- reconcile happens once.
- """
- from sqlalchemy import select
-
- from repowise.core.ingestion.cohesion import COHESION_HINTS, is_cohesion_edge
- from repowise.core.persistence.models import GraphEdge
-
- try:
- graph = graph_builder.graph()
- except Exception:
- return False
- if not any(is_cohesion_edge(d) for _u, _v, d in graph.edges(data=True)):
- return False # nothing to record, so nothing can be missing
-
- row = (
- await session.execute(
- select(GraphEdge.id)
- .where(
- GraphEdge.repository_id == repo_id,
- # Cohesion hints only: other passes (pytest conftest) stamp a
- # hint too, and one of theirs is not a cohesion stamp.
- GraphEdge.hint_source.in_(COHESION_HINTS),
- )
- .limit(1)
- )
- ).first()
- return row is None
-
-
-async def has_graph_edges(session: Any, repo_id: str) -> bool:
- """Whether this repo already has any ``graph_edges`` row."""
- from sqlalchemy import select
-
- from repowise.core.persistence.models import GraphEdge
-
- row = (
- await session.execute(
- select(GraphEdge.repository_id).where(GraphEdge.repository_id == repo_id).limit(1)
- )
- ).first()
- return row is not None
-
-
-async def _stored_edges_parser_fingerprint(session: Any, repo_id: str) -> str | None:
- """The ``parser_fingerprint()`` recorded when this repo's edges were written.
-
- ``None`` on a store written before the column existed, which is what makes
- every already-shipped store take the widen once.
- """
- from sqlalchemy import select
-
- from repowise.core.persistence.models import Repository
-
- return (
- await session.execute(
- select(Repository.graph_edges_parser_fingerprint).where(Repository.id == repo_id)
- )
- ).scalar_one_or_none()
-
-
-async def stamp_edges_parser_fingerprint(session: Any, repo_id: str, fingerprint: str) -> None:
- """Record the parser build that just wrote this repo's ``graph_edges``.
-
- Written by :func:`persist_incremental_edges` after a widen, and by the full
- :func:`persist_ingestion` path only when the store held no edges before it.
- That path upserts edges (:func:`batch_upsert_graph_edges`) and prunes only
- the nodes of files that vanished, so a re-index over an existing store adds
- the new build's edges without removing the old build's surplus ones.
- Stamping such a store would mark it parser-current and permanently suppress
- the delete-then-insert reconcile that is the only thing which clears them;
- it stays unstamped, and the first update widens. A fresh store has no
- surplus, so it is stamped: unstamped, the next parser change could not be
- told apart from "already up to date" on a quiet checkout.
- """
- from sqlalchemy import update
-
- from repowise.core.persistence.models import Repository
-
- await session.execute(
- update(Repository)
- .where(Repository.id == repo_id)
- .values(graph_edges_parser_fingerprint=fingerprint)
- )
-
-
-async def persist_incremental_edges(
- session: Any,
- repo_id: str,
- graph_builder: Any,
- parsed_files: list[Any] | None,
- changed_paths: list[str],
-) -> None:
- """Refresh ``graph_edges`` for changed files on an incremental update.
-
- Sibling of :func:`persist_incremental_symbols`. The full-init path was the
- only one that ever wrote ``graph_edges``; ``repowise update`` rebuilt the
- graph but never repersisted edges, so adjacency froze at the last full
- index. Phase E flow-path answers and any graph expansion read adjacency
- straight from this table, so they decayed on every incremental update. This
- delete-then-inserts the changed files' outgoing edges (dropping edges those
- files no longer have). Scoped to the changed set for cost.
-
- That scoping is also this function's one structural blind spot: an
- extraction change (a tree-sitter query edit, an extractor fix) alters the
- edges of *every* file, but only the git-changed ones get rewritten, so the
- rest keep the old build's edges until they happen to change. The parse cache
- self-invalidates on such a change (``parser_fingerprint`` hashes the ``.scm``
- sources) and the update rebuilds the whole graph in memory anyway, so the
- correct edges are already computed and only the write is too narrow. Widen
- it whenever the fingerprint that last wrote the table differs from the
- running one, then re-stamp. One comparison covers every future extraction
- change; :func:`_edges_predate_cohesion` is the bespoke predecessor, kept
- until shipped stores have all been stamped.
- """
- # An empty parse still counts: a repo with no source files has nothing to
- # widen, and it must be stamped, or a missing stamp re-parses it forever.
- if graph_builder is None or parsed_files is None:
- return
- from repowise.core.ingestion.parse_cache import parser_fingerprint
- from repowise.core.persistence.crud import reconcile_edges_for_files
-
- # Widen the reconcile to the whole parsed set, once. Same code path, so the
- # delete-then-insert still drops edges a file no longer has — which is what
- # clears the old build's resolution mistakes, an upsert alone would leave
- # them behind.
- fingerprint = parser_fingerprint()
- parser_changed = await _stored_edges_parser_fingerprint(session, repo_id) != fingerprint
- if parser_changed:
- changed_paths = [pf.file_info.path for pf in parsed_files]
- logger.info("graph_edges_parser_backfill", repo_id=repo_id, files=len(changed_paths))
- elif await _edges_predate_cohesion(session, repo_id, graph_builder):
- changed_paths = [pf.file_info.path for pf in parsed_files]
- logger.info("graph_edges_cohesion_backfill", repo_id=repo_id, files=len(changed_paths))
-
- reconcile_paths, edges = _changed_file_edges(graph_builder, parsed_files, changed_paths)
- if reconcile_paths:
- await reconcile_edges_for_files(session, repo_id, reconcile_paths, edges)
- # Every reconciled file, not only a widen's: a symbol renamed or removed
- # in a changed file otherwise keeps its node beside the new one.
- await _prune_vanished_symbol_nodes(session, repo_id, graph_builder, reconcile_paths)
- # Only after the widen actually ran to completion. Raising here (or in any
- # caller before the commit) leaves the old stamp, so the next update retries
- # rather than stranding the files it never reached.
- if parser_changed:
- await stamp_edges_parser_fingerprint(session, repo_id, fingerprint)
-
-
-async def _prune_vanished_symbol_nodes(
- session: Any, repo_id: str, graph_builder: Any, paths: list[str]
-) -> None:
- """Delete symbol ``graph_nodes`` of *paths* a re-extraction no longer produces.
-
- ``persist_graph_nodes`` upserts the current graph and never deletes, so a
- symbol whose id changed (a rename, or an overload gaining its own id under
- a new parser) would otherwise keep its old row beside the new ones. Scoped
- to files this run reconciled; a file that is gone is
- :func:`_prune_stale_file_rows`'s job.
- Membership rows prune themselves on their next write, and ``graph_metrics``
- holds files only.
- """
- from sqlalchemy import delete, or_, select
-
- from repowise.core.persistence.models import GraphEdge, GraphNode
-
- graph = graph_builder.graph()
- stale: list[str] = []
- for i in range(0, len(paths), _PRUNE_CHUNK):
- rows = await session.execute(
- select(GraphNode.node_id).where(
- GraphNode.repository_id == repo_id,
- GraphNode.node_type != "file",
- GraphNode.file_path.in_(paths[i : i + _PRUNE_CHUNK]),
- )
- )
- stale.extend(node_id for node_id in rows.scalars() if node_id not in graph)
- for i in range(0, len(stale), _PRUNE_CHUNK):
- batch = stale[i : i + _PRUNE_CHUNK]
- await session.execute(
- delete(GraphEdge).where(
- GraphEdge.repository_id == repo_id,
- or_(GraphEdge.source_node_id.in_(batch), GraphEdge.target_node_id.in_(batch)),
- )
- )
- await session.execute(
- delete(GraphNode).where(GraphNode.repository_id == repo_id, GraphNode.node_id.in_(batch))
- )
- if stale:
- logger.info("graph_nodes_parser_prune", repo_id=repo_id, nodes=len(stale))
-
-
-# Chunk size for IN (...) deletes — stays under SQLite's host-parameter limit.
-_PRUNE_CHUNK = 500
-
-
-async def _prune_stale_file_rows(
- session: Any,
- repo_id: str,
- current_graph_file_paths: set[str],
- current_git_file_paths: set[str],
- *,
- authoritative_empty: bool = False,
-) -> None:
- """Delete file-scoped rows for files absent from the latest full pipeline run.
-
- The parser and git indexer disagree on the file set — a file can be
- git-tracked yet absent from ``parsed_files`` (parse failure, unparsed
- extension, skipped) — so the tables use different sources of truth.
- *current_graph_file_paths* (from ``parsed_files``) governs graph/analysis
- tables; *current_git_file_paths* (from ``git_metadata_list``) governs
- ``git_metadata`` only. Each set independently no-ops when empty to avoid
- wiping rows on a broken run, unless ``authoritative_empty`` confirms that a
- successful full traversal really produced an empty scope.
-
- Full runs only. The authority here is "absent from this run's output",
- which is only safe because a full run rebuilds every table it prunes from
- in the same transaction. Incremental runs use
- :func:`prune_deleted_file_rows`, whose authority is the filesystem and git
- rather than the parse — see its docstring for why the two differ.
- """
- from sqlalchemy import delete, or_, select
-
- from repowise.core.persistence.models import (
- CoverageFile,
- DeadCodeFinding,
- GitFunctionBlame,
- GitMetadata,
- GraphEdge,
- GraphMetric,
- GraphNode,
- HealthFileMetric,
- HealthFinding,
- SecurityFinding,
- WikiSymbol,
- )
-
- async def _delete_stale_by_paths(
- model: Any,
- column: Any,
- current: set[str],
- *,
- allow_empty: bool | None = None,
- ) -> None:
- # Diff persisted paths against *current* in Python so the IN (...) is
- # bounded by the stale set, not the whole repo (SQLite param limit).
- empty_is_authoritative = authoritative_empty if allow_empty is None else allow_empty
- if not current and not empty_is_authoritative:
- return
- existing = set(
- (await session.execute(select(column).where(model.repository_id == repo_id).distinct()))
- .scalars()
- .all()
- )
- stale = [p for p in existing if p not in current]
- for i in range(0, len(stale), _PRUNE_CHUNK):
- await session.execute(
- delete(model).where(
- model.repository_id == repo_id,
- column.in_(stale[i : i + _PRUNE_CHUNK]),
- )
- )
-
- # ---- Graph nodes + edges -------------------------------------------------
- # File nodes key on node_id; symbol nodes on file_path. Delete edges before
- # nodes (no FK cascade between the tables).
- if current_graph_file_paths or authoritative_empty:
- node_rows = (
- await session.execute(
- select(GraphNode.node_id, GraphNode.node_type, GraphNode.file_path).where(
- GraphNode.repository_id == repo_id
- )
- )
- ).all()
- stale_node_ids = [
- node_id
- for node_id, node_type, file_path in node_rows
- if (node_type == "file" and node_id not in current_graph_file_paths)
- or (
- node_type != "file"
- and file_path is not None
- and file_path not in current_graph_file_paths
- )
- ]
- for i in range(0, len(stale_node_ids), _PRUNE_CHUNK):
- batch = stale_node_ids[i : i + _PRUNE_CHUNK]
- await session.execute(
- delete(GraphEdge).where(
- GraphEdge.repository_id == repo_id,
- or_(
- GraphEdge.source_node_id.in_(batch),
- GraphEdge.target_node_id.in_(batch),
- ),
- )
- )
- await session.execute(
- delete(GraphNode).where(
- GraphNode.repository_id == repo_id,
- GraphNode.node_id.in_(batch),
- )
- )
-
- # GraphMetric is file-level only (node_id == path).
- await _delete_stale_by_paths(GraphMetric, GraphMetric.node_id, current_graph_file_paths)
- await _delete_stale_by_paths(WikiSymbol, WikiSymbol.file_path, current_graph_file_paths)
- await _delete_stale_by_paths(
- SecurityFinding, SecurityFinding.file_path, current_graph_file_paths
- )
- await _delete_stale_by_paths(
- DeadCodeFinding, DeadCodeFinding.file_path, current_graph_file_paths
- )
- await _delete_stale_by_paths(
- HealthFileMetric, HealthFileMetric.file_path, current_graph_file_paths
- )
- await _delete_stale_by_paths(HealthFinding, HealthFinding.file_path, current_graph_file_paths)
- await _delete_stale_by_paths(CoverageFile, CoverageFile.file_path, current_graph_file_paths)
- await _delete_stale_by_paths(
- GitFunctionBlame, GitFunctionBlame.file_path, current_graph_file_paths
- )
- await _delete_stale_by_paths(
- GitMetadata,
- GitMetadata.file_path,
- current_git_file_paths,
- # An empty Git result is authoritative only when the successful source
- # traversal is empty too. Otherwise it may be a degraded Git walk.
- allow_empty=authoritative_empty and not current_graph_file_paths,
- )
-
-
-# A prune that would take more than this share of a table is read as a broken
-# run rather than a large commit, and refused. The asymmetry is the whole
-# argument: refusing leaves stale rows, which are visible in the UI and cleared
-# by a reindex, where proceeding deletes live ones, which are invisible until
-# someone notices the symbol is missing.
-_PRUNE_MAX_FRACTION = 0.5
-# ...but a small repo can legitimately lose half its files in one commit, so the
-# fraction only applies once the *deletion* is big enough for the ratio to mean
-# something. Measured on the deletion rather than the table so that a 25-row
-# store losing 20 rows still prunes: at that size "most of it went" is an
-# ordinary commit, not evidence of a broken run.
-_PRUNE_FLOOR_MIN_ROWS = 20
-
-
-def _git_tracked_paths(root: Path) -> frozenset[str]:
- """Every path git tracks at HEAD, POSIX-relative, or an empty set on failure.
-
- Empty is indistinguishable from "git failed" on purpose: both mean this
- witness has nothing to say, and the caller treats silence as "no opinion"
- rather than as "nothing is tracked".
- """
- from repowise.core.git_refs import tracked_paths
-
- return tracked_paths(str(root))
-
-
-class _FileLiveness:
- """Is this path still a real file, judged without consulting this run's parser.
-
- Two witnesses, neither of which is the parse: the file is present on disk,
- or git still tracks it. A path has to fail both to count as deleted.
-
- That split is the point. Deriving deletions from ``parsed_files`` alone
- makes every transient read or parse failure look like a deletion, and on
- Windows a file lock or an antivirus scan produces exactly that: the file is
- there, the run could not read it, and the naive prune deletes its rows.
- The disk check answers for that case; git covers the narrower one where the
- stat itself fails (``Path.exists()`` reports False on a permission error).
-
- The deliberate cost of taking the union: a file that a config change has
- newly *excluded* still exists and is still tracked, so its rows survive an
- incremental update. That matches the behaviour before this guard existed
- (which pruned nothing at all on this path), and a full reindex still clears
- it, so nothing regresses.
-
- ``git ls-files`` is spawned lazily, on the first path that is not on disk,
- so an update with no deletions never pays for it.
- """
-
- def __init__(self, repo_path: Any) -> None:
- self._root = Path(repo_path)
- self._tracked: frozenset[str] | None = None
- # The same path is asked about once per table it has rows in, and a
- # stat under an antivirus scanner is not free.
- self._memo: dict[str, bool] = {}
-
- def is_live(self, path: str) -> bool:
- answer = self._memo.get(path)
- if answer is None:
- answer = self._is_live(path)
- self._memo[path] = answer
- return answer
-
- def _is_live(self, path: str) -> bool:
- if (self._root / path).exists():
- return True
- if self._tracked is None:
- self._tracked = _git_tracked_paths(self._root)
- return path in self._tracked
-
-
-def path_liveness(repo_path: Any) -> Callable[[str], bool] | None:
- """Whether a repo-relative path is still on disk or tracked by git; ``None``
- without a checkout to ask, so no caller reads a path as deleted on no evidence."""
- return _FileLiveness(repo_path).is_live if repo_path else None
-
-
-async def _resolve_plans_of_deleted_files(
- session: Any, repo_id: str, dead: Callable[[set[str], str], list[str]], liveness: Any
-) -> None:
- from sqlalchemy import select
-
- from repowise.core.persistence.crud import PayoffContext, upsert_refactoring_suggestions
- from repowise.core.persistence.models import RefactoringSuggestion
-
- live_plan_paths = await session.execute(
- select(RefactoringSuggestion.file_path)
- .where(
- RefactoringSuggestion.repository_id == repo_id,
- RefactoringSuggestion.status.in_(("open", "acknowledged")),
- )
- .distinct()
- )
- gone = dead(set(live_plan_paths.scalars().all()), "refactoring_suggestions")
- if gone:
- payoff = PayoffContext(
- fact_rows=None,
- is_live=liveness.is_live,
- commit=await _analyzed_commit(session, repo_id),
- )
- await upsert_refactoring_suggestions(session, repo_id, [], file_paths=gone, payoff=payoff)
-
-
-async def prune_deleted_file_rows(
- session: Any,
- repo_id: str,
- repo_path: Any,
- *,
- live_hint: set[str] | None = None,
-) -> tuple[int, list[str]]:
- """Delete file-scoped rows for files that are gone, on an incremental update.
-
- The incremental path never pruned anything: deleting a file tombstoned its
- wiki page and left its graph nodes, edges, metrics, symbols, health rows and
- git metadata behind, so MCP, search and every health aggregate kept counting
- a file that no longer exists until someone ran a full reindex.
-
- The authority is deliberately *not* the one :func:`_prune_stale_file_rows`
- uses. A full run rebuilds every table it prunes from, so "absent from this
- run's output" is a safe question there. An incremental run rebuilds nothing:
- a row deleted here is not rewritten, so the question has to be "is the file
- gone", answered by :class:`_FileLiveness` from the filesystem and git rather
- than from the parse. They differ exactly in the transient-failure case, and
- that case is the one that loses data.
-
- *live_hint* is what this run already knows to be live: the paths that
- parsed, plus every file node the rebuilt graph holds. The first half is
- purely an optimisation, since anything in it would pass the liveness test
- anyway and the stat is skipped. The second half is load-bearing: a node
- like ``external:...`` or Spring's ``META-INF/services/<iface>`` names no
- file, so it fails every liveness test there is, and only the fact that the
- graph build just re-minted it says it is not a deletion.
-
- Returns ``(deleted_path_count, refusals)``, where a refusal is a one-line
- explanation of a floor guard that fired, for the caller's degraded report.
- """
- from sqlalchemy import delete, or_, select
-
- # Not every ``node_type == "file"`` row names a file. ``external:`` and
- # ``framework:`` nodes are minted for third-party imports and for
- # convention-based loading, they are stored as file nodes, and they answer
- # "no" to every liveness question there is because no such file was ever
- # meant to exist. Without this they read as a mass deletion: 223 of hugo's
- # 2,356 file nodes, 590 of react's 3,353, and 70% of spring-petclinic's,
- # which is past the floor guard and would have been reported as a refusal
- # rather than as the bug it is.
- #
- # Imported rather than re-listed: a prefix added to one copy and not the
- # other is exactly the bug above. Costs nothing on this path, where the
- # partial dead-code analysis has already loaded the module (13.7 ms when
- # it has not, measured cold after the CLI modules are up).
- from repowise.core.analysis.dead_code.analyzer import _is_synthetic_node
- from repowise.core.persistence.crud.analysis.function_facts import delete_file_rows
- from repowise.core.persistence.models import (
- DeadCodeFinding,
- DocDriftFinding,
- DocDriftReference,
- GitMetadata,
- GraphEdge,
- GraphMetric,
- GraphNode,
- HealthFileMetric,
- HealthFinding,
- SecurityFinding,
- WikiSymbol,
- )
-
- hint = live_hint or set()
- liveness = _FileLiveness(repo_path)
- refusals: list[str] = []
- deleted: set[str] = set()
-
- def _dead(persisted: set[str], label: str) -> list[str]:
- """Paths in *persisted* that no longer exist, or [] if the floor fired."""
- persisted = {p for p in persisted if not _is_synthetic_node(p)}
- dead = [p for p in persisted if p not in hint and not liveness.is_live(p)]
- if (
- len(dead) > _PRUNE_FLOOR_MIN_ROWS
- and persisted
- and len(dead) > _PRUNE_MAX_FRACTION * len(persisted)
- ):
- refusals.append(
- f"Deleted-file prune refused for {label}: {len(dead)} of "
- f"{len(persisted)} paths looked deleted, which reads as a broken "
- "run rather than a commit. Run a full reindex to clear them."
- )
- return []
- deleted.update(dead)
- return dead
-
- async def _prune_table(model: Any, column: Any, label: str) -> None:
- persisted = set(
- (await session.execute(select(column).where(model.repository_id == repo_id).distinct()))
- .scalars()
- .all()
- )
- persisted.discard(None)
- dead = _dead(persisted, label)
- for i in range(0, len(dead), _PRUNE_CHUNK):
- await session.execute(
- delete(model).where(
- model.repository_id == repo_id,
- column.in_(dead[i : i + _PRUNE_CHUNK]),
- )
- )
-
- # ---- Graph nodes + edges -------------------------------------------------
- # File nodes key on node_id, symbol nodes on file_path, and edges have no FK
- # cascade from either, so edges go first.
- node_rows = (
- await session.execute(
- select(GraphNode.node_id, GraphNode.node_type, GraphNode.file_path).where(
- GraphNode.repository_id == repo_id
- )
- )
- ).all()
- node_paths = {
- (node_id if node_type == "file" else file_path)
- for node_id, node_type, file_path in node_rows
- if node_type == "file" or file_path
- }
- dead_paths = set(_dead(node_paths, "graph_nodes"))
- if dead_paths:
- stale_node_ids = [
- node_id
- for node_id, node_type, file_path in node_rows
- if (node_id if node_type == "file" else file_path) in dead_paths
- ]
- for i in range(0, len(stale_node_ids), _PRUNE_CHUNK):
- batch = stale_node_ids[i : i + _PRUNE_CHUNK]
- await session.execute(
- delete(GraphEdge).where(
- GraphEdge.repository_id == repo_id,
- or_(
- GraphEdge.source_node_id.in_(batch),
- GraphEdge.target_node_id.in_(batch),
- ),
- )
- )
- await session.execute(
- delete(GraphNode).where(
- GraphNode.repository_id == repo_id,
- GraphNode.node_id.in_(batch),
- )
- )
-
- await _prune_table(GraphMetric, GraphMetric.node_id, "graph_metrics")
- await _prune_table(WikiSymbol, WikiSymbol.file_path, "wiki_symbols")
- await _prune_table(SecurityFinding, SecurityFinding.file_path, "security_findings")
- await _prune_table(DeadCodeFinding, DeadCodeFinding.file_path, "dead_code_findings")
- # Plans are resolved, not deleted, so a held id keeps answering. A scoped
- # run never names a deleted file (or a renamed file's old path) again, so
- # this is the one place they resolve. Before the facts below go: those are
- # the target's measures the payoff keeps.
- await _resolve_plans_of_deleted_files(session, repo_id, _dead, liveness)
- # Keyed on the symbol: a deleted file's rows are one key range of the id.
- await delete_file_rows(session, repo_id, dead_paths)
- # Keyed on the DOCUMENT. The incremental drift pass scopes its write to the
- # documents it read, so a deleted one is never in scope and its rows would
- # outlive the file without this. ``_FileLiveness`` asks disk and
- # ``git ls-files`` rather than the parse, so a ``.md`` path is judged
- # correctly here.
- await _prune_table(DocDriftFinding, DocDriftFinding.file_path, "doc_drift_findings")
- # On the document only. A reference to a deleted *target* is drift, not a
- # dead row: the next pass re-resolves it into a finding, and pruning by
- # target here would delete the evidence before anything reported it.
- await _prune_table(
- DocDriftReference, DocDriftReference.document_path, "doc_drift_references"
- )
- await _prune_table(HealthFileMetric, HealthFileMetric.file_path, "health_file_metrics")
- await _prune_table(HealthFinding, HealthFinding.file_path, "health_findings")
- # git_metadata is keyed off the git indexer on a full run, but an
- # incremental run only indexes the changed files, so the same liveness
- # question is the only authority available here too.
- await _prune_table(GitMetadata, GitMetadata.file_path, "git_metadata")
-
- return len(deleted), refusals
-
-
-# Generated page types keyed on run-scoped structure: module/scc pages on
-# clustering ordinals, layer pages on display names. Those keys shift between
-# runs, so re-runs mint fresh page ids and the previous rows linger as
-# duplicates unless swept against the current run's output.
-#
-# Same list generation stamps ``structural_key`` from, imported rather than
-# repeated: a type present in one and missing from the other is exactly the
-# bug the sweep exists to prevent.
-_SWEPT_GENERATED_PAGE_TYPES = STRUCTURALLY_KEYED_PAGE_TYPES
-
-
-async def sweep_retired_pages(session: Any, repo_id: str) -> list[str]:
- """Delete every row of a page that no longer exists, by type or by id.
-
- Distinct from the two sweeps below, and simpler than either: those ask what
- *this* run produced, because a page of a live type may legitimately be
- absent from a scoped run. A retired page has no legitimate rows at all —
- nothing emits one and no failure mode can make anything emit one — so the
- question never arises and this is safe on every path, full or scoped.
-
- The retirement tables are the source of truth rather than a list repeated
- here. A page is retired exactly when a reader following its id gets sent
- somewhere else, and that is what those tables say; keeping a second list
- would let a page be redirected without being swept, which is the state this
- function was written to clear.
-
- That state is the reason this exists. The architecture diagram merged into
- the overview and layer pages became grouping rows in the tree, both with
- redirects registered — but ``architecture_diagram`` is not structurally
- keyed, so no sweep ever covered it, and ``layer_page`` was only swept by a
- full run. An index that has only been updated incrementally since therefore
- still serves both. On this repository the retired diagram was the
- second-ranked retrieval hit for "how does the ingestion pipeline work",
- competing with the overview it had been merged into.
-
- Retirement by *id* is the second half of the same argument, and the reason
- this is no longer named for types. Three orientation slots retired out of
- the onboarding collection while five stayed, so their rows cannot be
- reached by page type: ``onboarding`` still has legitimate rows and always
- will. Sweeping the exact ids is the only way those leave a store, and the
- safety argument is unchanged — a retired id names a page nothing emits.
-
- Returns the swept page ids so the caller can drop them from the vector
- store and from FTS. A row deleted here but left in either of those is worse
- than one never swept: search still answers from the FTS copy, with the full
- title and snippet of a page the reader can no longer open.
- """
- from sqlalchemy import delete, or_, select
-
- from repowise.core.generation.page_redirects import (
- RETIRED_IDS,
- SUPERSEDED_TO_REPO_WIDE,
- SUPERSEDED_TYPES,
- )
- from repowise.core.persistence.models import Page, PageVersion
-
- retired_types = sorted(set(SUPERSEDED_TYPES) | set(SUPERSEDED_TO_REPO_WIDE))
- retired_ids = sorted(RETIRED_IDS)
- if not retired_types and not retired_ids:
- return []
-
- # Either rule can match, and a page matched by both is one row either way.
- match_clauses = []
- if retired_types:
- match_clauses.append(Page.page_type.in_(retired_types))
- if retired_ids:
- match_clauses.append(Page.id.in_(retired_ids))
-
- stale = (
- (
- await session.execute(
- select(Page.id).where(Page.repository_id == repo_id, or_(*match_clauses))
- )
- )
- .scalars()
- .all()
- )
- for i in range(0, len(stale), _PRUNE_CHUNK):
- batch = stale[i : i + _PRUNE_CHUNK]
- await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
- await session.execute(delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch)))
- if stale:
- logger.info(
- "retired_pages_swept",
- repo_id=repo_id,
- count=len(stale),
- types=retired_types,
- ids=retired_ids,
- )
- return list(stale)
-
-
-async def _sweep_stale_generated_pages(
- session: Any,
- repo_id: str,
- generated_pages: list[Any] | None,
- authoritative_page_types: set[str] | None = None,
- preserved_page_ids: set[str] | None = None,
-) -> list[str]:
- """Delete structurally-keyed generated pages this run did not produce.
-
- Sweeps a page type when the run either produced at least one page of it OR
- declared itself authoritative for it (``authoritative_page_types`` — set by
- the generation layer when it fully decided the type, even if that decision
- was "emit none"; e.g. a curated run whose modules all collapsed into their
- layers via ``wholeLayer``). A type that is neither produced nor authoritative
- is left untouched, so a skipped/failed/degraded level never wipes the last
- good set. When authoritative-but-empty, the current set is empty and every
- prior row of that type is retired. Page versions go with their page (FK
- enforcement requires it, and a retired structural id never comes back to
- claim its history). Returns the swept page ids so the caller can drop them
- from FTS after the session closes (the FTS store must not be touched
- in-session).
-
- ``preserved_page_ids`` are ids a ``--resume`` run skipped *because they
- already exist* (see ``_GenerationRun._emit``). They are absent from
- ``generated_pages`` by design, which is exactly what "stale" means to the
- rest of this function, so without this argument a resume that regenerated
- the missing half of a page type deleted the half it had just protected
- (issue #1089). A preserved id is as current as a produced one: the id did
- not drift, which is the only thing this sweep exists to catch.
- """
- from sqlalchemy import delete, select
-
- from repowise.core.persistence.models import Page, PageVersion
-
- produced: dict[str, set[str]] = {}
- for page in generated_pages or []:
- produced.setdefault(page.page_type, set()).add(page.page_id)
- authoritative = authoritative_page_types or set()
- preserved = preserved_page_ids or set()
-
- swept: list[str] = []
- for page_type in _SWEPT_GENERATED_PAGE_TYPES:
- current = produced.get(page_type)
- if not current and page_type not in authoritative:
- continue
- # Preserved ids join the current set rather than being subtracted from
- # the stale one: an authoritative type sweeps even when the run emitted
- # none of it, and that branch must still keep what a resume stood on.
- # (Defensive today — no caller sets both — but the two are independent
- # inputs and the failure mode if they ever meet is a deleted wiki.)
- # Filtered by type because ``preserved`` spans every page type while
- # this loop compares against one. Ids happen to be ``type:target`` so
- # a cross-type match is impossible, but the sweep is the wrong place to
- # depend on an id format nothing here enforces.
- prefix = f"{page_type}:"
- current = (current or set()) | {p for p in preserved if p.startswith(prefix)}
- existing = (
- (
- await session.execute(
- select(Page.id).where(
- Page.repository_id == repo_id, Page.page_type == page_type
- )
- )
- )
- .scalars()
- .all()
- )
- stale = [pid for pid in existing if pid not in current]
- for i in range(0, len(stale), _PRUNE_CHUNK):
- batch = stale[i : i + _PRUNE_CHUNK]
- await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
- await session.execute(
- delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch))
- )
- swept.extend(stale)
-
- if swept:
- logger.info("stale_generated_pages_swept", repo_id=repo_id, count=len(swept))
- return swept
-
-
-async def sweep_absent_cycle_pages(session: Any, repo_id: str, graph_builder: Any) -> list[str]:
- """Delete ``scc_page`` rows whose cycle no longer exists in the graph.
-
- The other sweeps ask "did this run *produce* this page?", which a scoped run
- cannot answer: ``repowise update`` runs with ``file_pages_only`` and never
- reaches level 3, so it emits no ``scc_page`` at all and every prior row
- looks stale to that question. ``_sweep_stale_generated_pages`` therefore
- gates on the run declaring itself authoritative, and only a keyless
- (``deterministic``) run does.
-
- Between them those two rules leave a cycle page immortal on the paths that
- matter: an update never regenerates it, and a keyed full re-index of a repo
- whose cycles all disappeared never claims authority to retire it. A user
- upgrading into a build that fixes a cycle-detection bug keeps being served
- the cycles it fixed.
-
- This asks a different question — "does the graph still contain this cycle?"
- — which the rebuilt graph answers directly and identically on every path,
- with no dependence on what generation chose to emit or what budget it had.
- A cycle's page id is a hash of its sorted members
- (:func:`~repowise.core.generation.models.scc_page_slug`), so the current
- cycle set names exactly the ids that may survive.
-
- Returns the deleted page ids so the caller can drop them from FTS and the
- vector store after the session closes.
- """
- from sqlalchemy import delete, select
-
- from repowise.core.generation.models import compute_page_id, scc_page_slug
- from repowise.core.persistence.models import Page, PageVersion
-
- if graph_builder is None:
- return []
- try:
- sccs = graph_builder.strongly_connected_components()
- except Exception: # a released graph has no cycles to speak for
- return []
-
- valid = {
- compute_page_id("scc_page", scc_page_slug(sorted(scc))) for scc in sccs if len(scc) > 1
- }
- existing = (
- (
- await session.execute(
- select(Page.id).where(Page.repository_id == repo_id, Page.page_type == "scc_page")
- )
- )
- .scalars()
- .all()
- )
- stale = [pid for pid in existing if pid not in valid]
- for i in range(0, len(stale), _PRUNE_CHUNK):
- batch = stale[i : i + _PRUNE_CHUNK]
- await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
- await session.execute(delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch)))
- if stale:
- logger.info("absent_cycle_pages_swept", repo_id=repo_id, count=len(stale))
- return stale
-
-
-def _symbol_names_by_file(graph_builder: Any) -> dict[str, set[str]]:
- """``file path -> names of the symbols it defines`` in the rebuilt graph.
-
- Empty when there is no graph to ask. The synthetic ``__module__`` symbol is
- left out, so a file that failed to parse has no entry at all.
- """
- if graph_builder is None:
- return {}
- try:
- graph = graph_builder.graph()
- except Exception: # a released graph cannot speak for any symbol
- return {}
- names_by_file: dict[str, set[str]] = {}
- for _node, data in graph.nodes(data=True):
- if data.get("node_type") != "symbol" or data.get("kind") == "module":
- continue
- path, name = data.get("file_path"), data.get("name")
- if path and name:
- names_by_file.setdefault(path, set()).add(name)
- return names_by_file
-
-
-async def sweep_absent_symbol_spotlights(
- session: Any, repo_id: str, graph_builder: Any
-) -> list[str]:
- """Delete ``symbol_spotlight`` rows whose symbol left a file that still exists.
-
- A spotlight targets ``<path>::<name>``. Deleting the file tombstones it
- (:func:`mark_tombstone_pages`), but moving or removing the symbol while the
- file stays left the row ``fresh``: nothing regenerates a page for a symbol
- the parser no longer emits, so it kept serving the old body and the old
- importer list.
-
- Same question as :func:`sweep_absent_cycle_pages`, asked of the rebuilt
- graph: does this file still define a symbol of that name? Only files the
- graph holds with at least one named symbol are judged, so a file outside
- the traversal or one that failed to parse keeps its pages.
-
- Returns the deleted page ids so the caller can drop them from FTS and the
- vector store after the session closes.
- """
- from sqlalchemy import delete, select
-
- from repowise.core.persistence.models import Page, PageVersion
-
- names_by_file = _symbol_names_by_file(graph_builder)
- if not names_by_file:
- return []
-
- rows = (
- await session.execute(
- select(Page.id, Page.target_path).where(
- Page.repository_id == repo_id,
- Page.page_type == "symbol_spotlight",
- Page.freshness_status != "tombstone",
- )
- )
- ).all()
- stale: list[str] = []
- for page_id, target in rows:
- path, sep, name = (target or "").partition("::")
- names = names_by_file.get(path)
- if sep and names is not None and name not in names:
- stale.append(page_id)
- for i in range(0, len(stale), _PRUNE_CHUNK):
- batch = stale[i : i + _PRUNE_CHUNK]
- await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
- await session.execute(delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch)))
- if stale:
- logger.info("absent_symbol_spotlights_swept", repo_id=repo_id, count=len(stale))
- return stale
-
-
-async def sweep_superseded_generated_pages(
- session: Any,
- repo_id: str,
- generated_pages: list[Any] | None,
-) -> list[str]:
- """Retire structurally-keyed rows whose coverage a scoped run just took over.
-
- :func:`_sweep_stale_generated_pages` cannot be used on the update path. It
- deletes every row of a page type the run did not reproduce, which is right
- for a full index and catastrophic for a scoped one: regenerating a single
- page would wipe the other fifty.
-
- That left a real gap. A structurally-keyed page's id is its
- ``target_path``, and a page that groups files can legitimately change which
- directory names it when its membership changes. ``repowise update`` goes
- through ``scoped_generation`` and never swept, so the regenerated page was
- written under its new id and the old row stayed behind as a duplicate until
- somebody ran a full index. Harmless while module and cycle pages were never
- regenerated incrementally, and not harmless once concept pages are.
-
- The rule here is narrower and does not need to know what the caller asked
- for: a prior row is superseded when **every file it covered is now covered
- by pages this run produced**, of the same type. That is exactly the
- condition under which the old row documents nothing that is not documented
- elsewhere. A page that failed to generate keeps files no produced page
- claims, so it survives — which matters, because deleting a page because its
- generation errored would be a worse bug than the one this fixes.
-
- Returns the swept page ids so the caller can drop them from FTS after the
- session closes.
- """
- from sqlalchemy import delete, select
-
- from repowise.core.persistence.models import Page, PageVersion
-
- produced_ids: dict[str, set[str]] = {}
- covered: dict[str, set[str]] = {}
- for page in generated_pages or []:
- page_type = page.page_type
- if page_type not in _SWEPT_GENERATED_PAGE_TYPES:
- continue
- # A stub standing in for a failed provider call is the "failed to
- # generate" case this function's contract already carves out: it claims
- # no files, so a prior row covering them is not superseded. Counting its
- # members would retire the very page whose regeneration just failed, and
- # take its version history with it.
- if STUB_FALLBACK_ERROR in (getattr(page, "metadata", None) or {}):
- continue
- produced_ids.setdefault(page_type, set()).add(page.page_id)
- metadata = getattr(page, "metadata", None) or {}
- members = metadata.get("file_paths") or metadata.get("files") or []
- covered.setdefault(page_type, set()).update(m for m in members if isinstance(m, str))
-
- swept: list[str] = []
- for page_type, current in produced_ids.items():
- union = covered.get(page_type) or set()
- if not union:
- # Nothing to compare against: a run that recorded no membership
- # cannot prove it superseded anything, so it retires nothing.
- continue
- rows = (
- await session.execute(
- select(Page.id, Page.metadata_json).where(
- Page.repository_id == repo_id, Page.page_type == page_type
- )
- )
- ).all()
- stale: list[str] = []
- for page_id, raw in rows:
- if page_id in current:
- continue
- try:
- metadata = json.loads(raw) if isinstance(raw, str) else (raw or {})
- except (TypeError, ValueError):
- continue
- if not isinstance(metadata, dict):
- continue
- members = metadata.get("file_paths") or metadata.get("files") or []
- members = {m for m in members if isinstance(m, str)}
- # No recorded membership means no proof of supersession. Those rows
- # are the pre-membership ones (backlog B20) and they are left for a
- # full index to retire.
- if members and members <= union:
- stale.append(page_id)
- for i in range(0, len(stale), _PRUNE_CHUNK):
- batch = stale[i : i + _PRUNE_CHUNK]
- await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
- await session.execute(
- delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch))
- )
- swept.extend(stale)
-
- if swept:
- logger.info("superseded_generated_pages_swept", repo_id=repo_id, count=len(swept))
- return swept
-
-
-async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
- """Persist ingestion-phase outputs: graph nodes/edges, external systems,
- symbols, and the per-file security scan.
-
- Every write here is an idempotent UPSERT keyed by ``(repo_id, …)``, so
- this is safe to call incrementally (per phase) and to re-run on resume.
-
- Returns the number of symbols written (for the summary log). Mutates
- ``sym.file_path`` on symbols that lack one — callers should treat the
- parsed-file symbols as consumed after this call.
- """
- from repowise.core.persistence import (
- batch_upsert_graph_edges,
- batch_upsert_symbols,
- bulk_upsert_external_systems,
- link_graph_nodes_to_external_systems,
- )
-
- # ---- Graph nodes ---------------------------------------------------------
- # Prefer the full candidate-score map (all scored entry points), falling
- # back to deriving from the builder when no report rode along on the
- # result. Passing ``None`` lets persist_graph_nodes derive them itself.
- report = result.execution_flow_report
- ep_scores: dict[str, float] | None
- if report is not None and getattr(report, "entry_point_scores", None):
- ep_scores = dict(report.entry_point_scores)
- elif report is not None and getattr(report, "flows", None):
- ep_scores = {
- f.entry_point_id: f.entry_point_score
- for f in report.flows
- if hasattr(f, "entry_point_id") and hasattr(f, "entry_point_score")
- }
- else:
- ep_scores = None
- await persist_graph_nodes(session, repo_id, result.graph_builder, ep_scores)
-
- # ---- Graph edges ---------------------------------------------------------
- graph = result.graph_builder.graph()
- edges = [_edge_row(u, v, data) for u, v, data in graph.edges(data=True)]
- fresh_store = not await has_graph_edges(session, repo_id)
- if edges:
- await batch_upsert_graph_edges(session, repo_id, edges)
- if fresh_store:
- from repowise.core.ingestion.parse_cache import parser_fingerprint
-
- await stamp_edges_parser_fingerprint(session, repo_id, parser_fingerprint())
-
- # ---- External systems (C4 L1) -------------------------------------------
- # Persist before symbols so the FK linkage step below sees the IDs.
- external_systems = getattr(result, "external_systems", None) or []
- if external_systems:
- id_map = await bulk_upsert_external_systems(session, repo_id, external_systems)
- from repowise.core.persistence.crud import build_external_system_link_map
-
- name_to_id = build_external_system_link_map(external_systems, id_map)
- await link_graph_nodes_to_external_systems(session, repo_id, name_to_id)
-
- # ---- Symbols -------------------------------------------------------------
- # NOTE: This mutates sym.file_path on the caller's PipelineResult objects.
- # The guard prevents double-set on retries, but callers should treat the
- # result as consumed after this call.
- all_symbols = []
- for pf in result.parsed_files:
- for sym in pf.symbols:
- if not getattr(sym, "file_path", None):
- sym.file_path = pf.file_info.path
- all_symbols.append(sym)
- if all_symbols:
- await batch_upsert_symbols(session, repo_id, all_symbols)
-
- # ---- Security scan -------------------------------------------------------
- # Best-effort — never breaks the rest of the phase.
- try:
- await persist_security_findings(result, session, repo_id)
- except Exception as _sec_err:
- logger.warning("security_scan_skipped", error=str(_sec_err))
-
- return len(all_symbols)
-
-
-async def persist_security_findings(result: Any, session: Any, repo_id: str) -> None:
- """Scan every parsed file's source and replace its security findings.
-
- Source bytes come from ``result.source_map`` (ingestion read them once);
- ``FileInfo`` itself carries no content, only ``content_hash``, so reading
- it off ``file_info`` yields empty text and a scan that can never fire.
- Resume views without a ``source_map`` degrade to the symbol-name scan.
- """
- source_map = getattr(result, "source_map", None) or {}
- await _replace_security_findings(session, repo_id, result.parsed_files, source_map)
-
-
-async def persist_incremental_security_findings(
- session: Any,
- repo_id: str,
- parsed_files: list[Any] | None,
- source_map: dict[str, Any] | None,
- changed_paths: list[str],
-) -> None:
- """Rescan the changed and added files' working-tree security findings.
-
- Without this, update kept every finding from the last full index: new
- secrets in changed files were missed and old rows pointed at moved lines.
- Deleted files are dropped by ``prune_deleted_file_rows``. No source map
- means no text to scan, and scanning empty text would wipe real findings,
- so that case is a no-op.
- """
- if not parsed_files or not source_map:
- return
- changed = set(changed_paths)
- targets = [pf for pf in parsed_files if pf.file_info.path in changed]
- if targets:
- await _replace_security_findings(session, repo_id, targets, source_map)
-
-
-async def _replace_security_findings(
- session: Any, repo_id: str, parsed_files: Any, source_map: dict[str, Any]
-) -> None:
- from repowise.core.analysis.security_scan import SecurityScanner, scan_source_map
-
- findings_by_file, scanned_paths = scan_source_map(parsed_files, source_map)
- await SecurityScanner(session, repo_id).replace_findings(findings_by_file, scanned_paths)
-
-
-async def persist_git(result: Any, session: Any, repo_id: str) -> None:
- """Persist git-phase outputs: per-file metadata and per-commit rows.
-
- Both writes are idempotent UPSERTs keyed by ``(repo_id, file_path)`` /
- ``(repo_id, sha)`` — safe to call incrementally and on resume.
- """
- from repowise.core.persistence.crud import (
- clear_attribution_if_disabled,
- prune_fix_events_before,
- update_repo_git_totals,
- upsert_fix_events_bulk,
- upsert_git_commit_files_bulk,
- upsert_git_commits_bulk,
- upsert_git_metadata_bulk,
- )
-
- if result.git_metadata_list:
- await upsert_git_metadata_bulk(session, repo_id, result.git_metadata_list)
-
- summary = getattr(result, "git_summary", None)
-
- # Per-commit rows + change-risk ride on the git summary.
- commit_rows = getattr(summary, "commit_rows", None)
- if commit_rows:
- await upsert_git_commits_bulk(session, repo_id, commit_rows)
-
- commit_file_rows = getattr(summary, "commit_file_rows", None)
- if commit_file_rows:
- await upsert_git_commit_files_bulk(session, repo_id, commit_file_rows)
- await clear_attribution_if_disabled(session, repo_id)
- if summary is not None:
- await _rebuild_changes(session, repo_id)
-
- # Per fix-commit x file rows (with their SZZ candidates). The prune keeps a
- # re-index of an already-indexed repo from leaving behind events that have
- # since aged out of the defect window.
- fix_event_rows = getattr(summary, "fix_event_rows", None)
- if fix_event_rows:
- await upsert_fix_events_bulk(session, repo_id, fix_event_rows)
- oldest_ts = getattr(summary, "fix_oldest_ts", 0)
- if oldest_ts and getattr(summary, "fix_events_built", False):
- from datetime import UTC, datetime
-
- await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))
-
- # Symbol attribution + bug-magnet rollups, over the rows just written.
- # Failure-isolated: a rollup that cannot be computed leaves the previous
- # values in place rather than blanking a surface mid-index.
- try:
- from repowise.core.pipeline.fix_rollups import apply_fix_rollups
-
- await apply_fix_rollups(session, repo_id)
- except Exception as exc: # pragma: no cover - defensive
- logger.debug("fix_rollups_failed", repo_id=repo_id, error=str(exc))
-
- # Whole-history totals (true age / commit / contributor counts) also ride on
- # the summary — stamp them on the Repository row so the stats page reads them
- # instead of deriving them from the bounded ``git_commits`` sample (#730).
- totals = getattr(summary, "repo_totals", None)
- if totals is not None:
- await update_repo_git_totals(
- session,
- repo_id,
- total_commit_count=totals.total_commit_count,
- total_merge_commit_count=getattr(totals, "total_merge_commit_count", None),
- first_commit_at=totals.first_commit_at,
- total_contributor_count=totals.total_contributor_count,
- first_commit_author=totals.first_commit_author,
- first_commit_subject=totals.first_commit_subject,
- total_lines_added=totals.total_lines_added,
- total_lines_deleted=totals.total_lines_deleted,
- churn_anchor_sha=getattr(totals, "churn_anchor_sha", None),
- )
-
-
-async def _rebuild_changes(session: Any, repo_id: str) -> None:
- """Change records from the same history, after the commit labels they read."""
- from repowise.core.changes.store import refresh_changes
- from repowise.core.persistence.models import Repository
-
- try:
- repo = await session.get(Repository, repo_id)
- except Exception as exc: # pragma: no cover - defensive
- logger.debug("changes_repo_lookup_failed", repo_id=repo_id, error=str(exc))
- return
- if repo is not None and repo.local_path:
- await refresh_changes(session, repo_id, repo.local_path, rebuild=True)
-
-
-async def replace_git_history(
- session: Any,
- repo_id: str,
- git_meta_map: dict[str, dict],
- git_summary: Any,
- *,
- keep_commit_health: bool = False,
-) -> None:
- """Replace every history-derived row from one authoritative Git walk.
-
- ``keep_commit_health`` keeps the per-commit health rows. A walk that only
- re-reads the same window under new rules leaves each commit's code, so its
- health is still right, and the capped ``refresh_commit_health`` could not
- rebuild rows past its budget. Those rows key on ``(repository_id, sha)``
- alone, so nothing dangles; unreachable shas are pruned by the update's
- orphan sweep.
- """
- from types import SimpleNamespace
-
- from sqlalchemy import delete
-
- from repowise.core.persistence.models import (
- FixEvent,
- GitCommit,
- GitCommitFile,
- GitCommitHealthDelta,
- GitCommitHealthFinding,
- GitMetadata,
- )
-
- # Function blame describes the current source tree and is produced by the
- # health pass, not by persist_git. Preserve it across a history-window
- # replacement; scope reconciliation prunes entries for excluded files.
- health = () if keep_commit_health else (GitCommitHealthDelta, GitCommitHealthFinding)
- for model in (FixEvent, GitCommit, GitCommitFile, *health, GitMetadata):
- await session.execute(delete(model).where(model.repository_id == repo_id))
- await persist_git(
- SimpleNamespace(
- git_metadata_list=list(git_meta_map.values()),
- git_summary=git_summary,
- ),
- session,
- repo_id,
- )
-
-
-async def persist_git_refresh(
- session: Any,
- repo_id: str,
- git_meta_map: dict[str, dict],
- git_decay_map: dict[str, dict] | None,
- full_git_summary: Any | None,
- *,
- keep_commit_health: bool = False,
-) -> None:
- """Persist either a full history replacement or an incremental refresh."""
- if full_git_summary is not None:
- await replace_git_history(
- session,
- repo_id,
- git_meta_map,
- full_git_summary,
- keep_commit_health=keep_commit_health,
- )
- return
-
- from sqlalchemy import select
-
- from repowise.core.persistence.crud import (
- clear_attribution_if_disabled,
- recompute_git_percentiles,
- upsert_git_metadata_bulk,
- )
- from repowise.core.persistence.models import GitMetadata
-
- decay_rows = list((git_decay_map or {}).values())
- if decay_rows:
- stored = set(
- (
- await session.execute(
- select(GitMetadata.file_path).where(GitMetadata.repository_id == repo_id)
- )
- ).scalars()
- )
- # A decay row is partial, so it only refreshes a stored row: inserted,
- # it is a fragment with no totals or owner. History-tier rows are
- # complete and upsert whole, which also fills the non-code rows an
- # index built before that tier never wrote.
- decay_rows = [
- row for row in decay_rows if row.get("history_only") or row["file_path"] in stored
- ]
- await upsert_git_metadata_bulk(session, repo_id, [*git_meta_map.values(), *decay_rows])
- await recompute_git_percentiles(session, repo_id)
- await clear_attribution_if_disabled(session, repo_id)
-
-
-async def _analyzed_commit(session: Any, repo_id: str) -> str | None:
- """Live HEAD of the repo being indexed, for stamping health rows.
-
- Read off disk rather than from ``Repository.head_commit``: the health pass
- just scored the working tree, and the stored column is written by a
- different step whose ordering relative to this one is not guaranteed.
- ``None`` on any failure — an unstamped row reads as "not recorded", which
- is honest, while a wrong sha would not be. Both index paths read it here;
- the pipeline result carries no sha, so the full path used to stamp ``NULL``.
- """
- from repowise.core.persistence.models import Repository
- from repowise.core.workspace.update import get_head_commit
-
- try:
- repo = await session.get(Repository, repo_id)
- local_path = getattr(repo, "local_path", None) if repo else None
- return get_head_commit(Path(local_path)) if local_path else None
- except Exception:
- return None
-
-
-async def snapshot_health_from_store(session: Any, repo_id: str) -> None:
- """Append a ``HealthSnapshot`` built from the repository's stored rows.
-
- One writer for the full index and the incremental update. A partial report
- cannot be snapshotted directly, because it holds only the changed files and
- a snapshot has to describe the whole repository; the store after the write
- holds exactly that, on both paths.
-
- Best-effort: a snapshot that fails to write is logged and never fails the
- run that produced the rows it describes.
- """
- from sqlalchemy import select
-
- from repowise.core.analysis.health.ranking import deduction_by_path
- from repowise.core.analysis.health.scoring import compute_kpis
- from repowise.core.analysis.health.trends import snapshot_fields
- from repowise.core.persistence.crud import get_hotspot_file_paths, save_health_snapshot
- from repowise.core.persistence.models import HealthFileMetric, HealthFinding
-
- try:
- metrics = list(
- (
- await session.execute(
- select(HealthFileMetric).where(HealthFileMetric.repository_id == repo_id)
- )
- )
- .scalars()
- .all()
- )
- if not metrics:
- return
- findings = list(
- (
- await session.execute(
- select(HealthFinding).where(
- HealthFinding.repository_id == repo_id,
- HealthFinding.status == "open",
- )
- )
- )
- .scalars()
- .all()
- )
- kpis = compute_kpis(
- metrics,
- await get_hotspot_file_paths(session, repo_id),
- deductions=deduction_by_path(findings),
- )
- fields = snapshot_fields(kpis, metrics, findings)
- if fields is not None:
- await save_health_snapshot(session, repo_id, **fields)
- except Exception as exc:
- logger.warning("health_snapshot_skipped", error=str(exc))
-
-
-async def save_full_health_report(
- session: Any,
- repo_id: str,
- health_report: Any,
- *,
- analyzed_commit: str | None,
- repo_path: Any = None,
-) -> None:
- """Full-replace a repository's health rows and everything derived from them.
-
- Both callers that re-score every file land here: the analysis phase of an
- index, and the update command's periodic/config-triggered re-score. The
- metrics, the findings, the non-performance refactoring suggestions and the
- two materialized read models move together, so a re-score cannot leave the
- queues describing findings that were deleted out from under them.
-
- ``analyzed_commit`` stamps the metric rows and the read models with the
- commit these scores were computed against; ``None`` reads as "not
- recorded", which is honest, while a wrong sha would not be. ``repo_path``
- lets a plan whose file is gone read as deleted.
- """
- from repowise.core.persistence.crud import (
- PayoffContext,
- finalize_performance_opportunities,
- finalize_refactoring_opportunities,
- save_health_findings,
- save_health_metrics,
- save_refactoring_suggestions,
- write_function_facts,
- )
-
- hr = health_report
- metrics = list(getattr(hr, "metrics", None) or [])
- findings = list(getattr(hr, "findings", None) or [])
- if not metrics and not findings:
- # A pass that scored nothing is a broken pass, not a clean repository.
- # Every write below replaces the repository's rows wholesale, so
- # honouring an empty report would delete every metric, resolve every
- # open plan a person has triaged, and empty both queues on the strength
- # of a parse failure or an exclude pattern that matched everything.
- return
- await save_health_metrics(session, repo_id, metrics, analyzed_commit=analyzed_commit)
- # One savepoint over the findings and everything derived from them, so a
- # rebuild that failed halfway cannot leave the queue describing findings
- # that were never stored. It runs on an empty finding set too: the queue
- # has to be reconciled to nothing just the same.
- async with session.begin_nested():
- if findings:
- await save_health_findings(session, repo_id, findings)
- # Structured refactoring suggestions (Extract Class, ...). Repo-wide
- # reconciliation: an unchanged plan keeps its id and its triage state,
- # and one nobody detects any more resolves rather than disappearing.
- # Performance plans are excluded: the finalizer below owns them, so
- # they are generated once, from the merged stored findings, by the same
- # writer on every path.
- await save_refactoring_suggestions(
- session,
- repo_id,
- [
- suggestion
- for suggestion in (getattr(hr, "refactoring_suggestions", None) or [])
- if getattr(suggestion, "refactoring_type", None) != "performance_fix"
- ],
- # Before the facts below replace the stored ones: those are the
- # measures a resolved plan was detected against.
- payoff=PayoffContext(
- fact_rows=getattr(hr, "function_facts", None),
- is_live=path_liveness(repo_path),
- commit=analyzed_commit,
- ),
- )
- # No rows means no graph to key them on: the stored ones stay. Before
- # the finalizers, which read each plan's nearest tests off these rows.
- fact_rows = getattr(hr, "function_facts", None)
- if fact_rows is not None:
- await write_function_facts(
- session,
- repo_id,
- fact_rows,
- roles=getattr(hr, "execution_roles", None),
- tests=getattr(hr, "function_tests", None),
- )
- # Group the stored performance findings into the materialized causal
- # read model, then reconcile lifecycle and plans.
- await finalize_performance_opportunities(
- session,
- repo_id,
- analyzed_commit=analyzed_commit,
- plan_policy=getattr(hr, "performance_plan_policy", None),
- execution_roles=getattr(hr, "execution_roles", None),
- )
- # Fold the plans just written into per-file opportunities. Last in the
- # savepoint because it composes over the stored rows, so it has to see
- # the reconciliation above rather than the detector output.
- await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)
-
-
-async def refresh_governance_findings(
- session: Any, repo_id: str, *, recompose_queue: bool = True
-) -> int:
- """Rebuild the governance findings from the stored decisions and health rows.
-
- Every writer that runs the governance pass comes through here: the index
- after its decisions are stored, the update after its decision steps, and
- the full health re-score, whose findings replace deletes these rows along
- with every other open finding. Returns the number of findings written.
-
- ``recompose_queue`` re-folds the refactoring queue when findings were
- written, since it is composed over the stored findings and may have been
- built before these rows existed. Only that queue: the performance
- finalizer reads ``performance`` findings, and every governance biomarker
- is ``organizational``. A caller that finalizes the queue next anyway
- passes ``False``.
- """
- from sqlalchemy import select
-
- from repowise.core.analysis.health.governance import build_governance_findings
- from repowise.core.persistence.crud import (
- finalize_refactoring_opportunities,
- get_decision_health_summary,
- get_scored_file_paths,
- replace_governance_findings,
- )
- from repowise.core.persistence.models import DecisionRecord
-
- # One savepoint: the replace deletes before it inserts, and the queue
- # reconciles as a whole, so a failure must leave neither half-written.
- async with session.begin_nested():
- decisions = list(
- (
- await session.execute(
- select(DecisionRecord).where(DecisionRecord.repository_id == repo_id)
- )
- )
- .scalars()
- .all()
- )
- findings = build_governance_findings(
- health_summary=await get_decision_health_summary(session, repo_id),
- decisions=decisions,
- scored_paths=await get_scored_file_paths(session, repo_id),
- )
- await replace_governance_findings(session, repo_id, findings)
- if findings and recompose_queue:
- await finalize_refactoring_opportunities(
- session, repo_id, analyzed_commit=await _analyzed_commit(session, repo_id)
- )
- if findings:
- logger.info("governance_findings_persisted", repo_id=repo_id, count=len(findings))
- return len(findings)
-
-
-async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
- """Persist analysis-phase outputs: dead code, health, decisions, drift.
-
- Dead-code, health and doc-drift writes are repo-wide DELETE-THEN-INSERT (so
- they converge on re-run but don't support partial-within-phase resume);
- decisions/governance are idempotent. Intended to run once the analysis
- phase has fully completed.
- """
- from repowise.core.persistence.crud import (
- bulk_upsert_decisions,
- recompute_decision_staleness,
- replace_doc_drift_guarded,
- save_coverage_files,
- save_dead_code_findings,
- set_repo_function_mod_p80,
- upsert_git_function_blame_bulk,
- )
-
- # ---- Dead code findings --------------------------------------------------
- # Written even when empty: a run that found nothing must clear the old
- # open rows, not leave them standing as current findings.
- if result.dead_code_report is not None:
- await save_dead_code_findings(session, repo_id, result.dead_code_report.findings or [])
-
- # ---- Documentation drift: findings and resolved references --------------
- # Both tables, one savepoint, one run. Written even when the finding list
- # is empty, unlike dead code above: a run that fixed the last drifted
- # reference must clear the rows, and a guard on ``.findings`` would leave
- # the old ones standing as though the documents were still wrong.
- # ``authoritative_paths`` is None on a full run, so the replace is
- # repo-wide.
- drift = getattr(result, "doc_drift_report", None)
- if drift is not None:
- try:
- await replace_doc_drift_guarded(session, repo_id, drift)
- except Exception as exc:
- logger.warning("doc_drift_persist_skipped", error=str(exc))
-
- # ---- Health findings + per-file metrics ---------------------------------
- if getattr(result, "health_report", None):
- hr = result.health_report
- # Hoisted out of the coverage branch below: the same sha now stamps the
- # metric rows, so a reader can tell how far the health pass lags the
- # index instead of assuming the two moved together.
- head_sha = await _analyzed_commit(session, repo_id)
- await save_full_health_report(
- session,
- repo_id,
- hr,
- analyzed_commit=head_sha,
- repo_path=getattr(result, "repo_path", None),
- )
- # Resolved coverage rows, when a report was ingested this run.
- coverage_files = getattr(hr, "coverage_files", None)
- if coverage_files:
- await save_coverage_files(
- session,
- repo_id,
- coverage_files,
- source_format=getattr(hr, "coverage_format", None) or "lcov",
- ingested_commit_sha=head_sha,
- provenance=getattr(hr, "coverage_provenance", None),
- )
- # Per-function blame rollup (FULL tier only; empty otherwise).
- fn_blame_rows = getattr(hr, "function_blame_rows", None)
- if fn_blame_rows:
- await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)
- # The hotspot gate an incremental update will score against. Written
- # only by a run that walked the whole repo (the analyzer leaves it None
- # otherwise), so an incremental run cannot publish its changed-files
- # subset as the repo-wide percentile.
- fn_mod_p80 = getattr(hr, "repo_function_mod_p80", None)
- if fn_mod_p80:
- await set_repo_function_mod_p80(session, repo_id, fn_mod_p80)
- # Snapshot the run for trend tracking (rolling delete inside). From
- # the rows just written, by the same writer the update path uses.
- await snapshot_health_from_store(session, repo_id)
-
- # ---- Decision records ----------------------------------------------------
- # One contributor: the multi-source extractor. A second read used to fold
- # ``page.metadata["harvested_decisions"]`` in from LLM page generation, but
- # nothing ever wrote that key — harvesting only ever ran on ``file_page``,
- # and file pages are rendered structurally now, so the directive had no
- # host and the loop was permanently a no-op.
- decision_dicts: list[dict] = []
- if result.decision_report and result.decision_report.decisions:
- decision_dicts.extend(dataclasses.asdict(d) for d in result.decision_report.decisions)
-
- # Restore records the semantic supersession detector retired before it was
- # turned off. ``superseded`` is a protected status, so nothing else will
- # ever walk these back, and a store that only stops retiring is still a
- # store with a quarter of its corpus hidden. Runs whether or not this run
- # produced decisions.
- #
- # BEFORE the purge below, not after: restoring puts a row back at
- # ``proposed``, which is exactly what the purge deletes. Un-retire first and
- # a run ends in one consistent state — good records visible, retired-source
- # records gone. The other order leaves a restored changelog row alive for
- # one run and silently deletes it on the next.
- try:
- from repowise.core.persistence.crud import unretire_auto_superseded
-
- await unretire_auto_superseded(session)
- except Exception as _unretire_err:
- logger.debug("decision_unretire_skipped", error=str(_unretire_err))
-
- # One-shot drain of proposals left by retired extraction sources; without
- # this, DBs indexed before a removal keep a flooded review queue forever
- # (#751 for code_comment). Confirmed/dismissed rows are kept.
- try:
- from repowise.core.analysis.decision_provenance import RETIRED_SOURCES
- from repowise.core.persistence.crud import purge_proposed_decisions_by_source
-
- for _retired in RETIRED_SOURCES:
- await purge_proposed_decisions_by_source(session, repo_id, _retired)
- except Exception as _purge_err:
- logger.debug("decision_purge_skipped", error=str(_purge_err))
-
- # Re-stamp evidence rows left on a previous SOURCE_RANK ladder. Local stores
- # are created by ``init_db`` and never see Alembic, so the migration alone
- # would only reach hosted; this is the same repair on the path every store
- # takes. No-op scan once reconciled, and it runs whether or not this run
- # produced decisions, because a store with nothing new still holds the rows.
- try:
- from repowise.core.persistence.crud import reconcile_source_ranks
-
- await reconcile_source_ranks(session)
- except Exception as _rank_err:
- logger.debug("decision_rank_reconcile_skipped", error=str(_rank_err))
-
- # The same repair for the scoring formula, which leaves every input valid
- # and every stored score stale, so no filter can find it. Its own try, so
- # a failure here is not logged as the rank repair's.
- try:
- from repowise.core.persistence.crud import reconcile_decision_confidence
-
- await reconcile_decision_confidence(session)
- except Exception as _conf_err:
- logger.debug("decision_confidence_reconcile_skipped", error=str(_conf_err))
-
- # Move legacy records onto ids derived from their own identity, before
- # anything else reads or writes one. A random id is re-minted whenever a
- # store is rebuilt rather than updated, which strands every reference held
- # outside the row. Idempotent, and it never deletes a record.
- try:
- from repowise.core.persistence.decision_id_migration import apply_id_migration
-
- await apply_id_migration(
- session, repo_id, vector_store=getattr(result, "vector_store", None)
- )
- except Exception as _id_err:
- logger.debug("decision_id_migration_skipped", error=str(_id_err))
-
- # Classify legacy rows against the entity split. A record promoted by
- # recurrence rather than by a person becomes a candidate, which visibly
- # shrinks what governs; leaving it to an explicit command would instead
- # leave the status column and the acceptance log permanently disagreeing,
- # with half the surfaces reading each. Idempotent, and it never reopens a
- # review action somebody already performed.
- 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,
- )
-
- await apply_migration(session, repo_id)
- # Beside it, and for the same reason: these repair rows written before
- # the rule existed, and nothing re-extracts them. The prune runs first
- # so the two basis repairs judge the file list they will leave behind.
- 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))
-
- if decision_dicts:
- # Reuse the run's shared vector store for semantic (paraphrase) dedup
- # and to make decisions searchable; title dedup still runs when None.
- store = getattr(result, "vector_store", None)
- touched_ids = await bulk_upsert_decisions(
- session,
- repo_id,
- decision_dicts,
- vector_store=store,
- )
- # Phase 3B: detect supersession/conflict among the just-upserted
- # decisions and record typed edges (auto-flipping the older only above
- # the high-confidence threshold). Heuristic-only here (no provider on
- # the persist path); the update path adds the gated LLM tiebreaker.
- if touched_ids and store is not None:
- try:
- from repowise.core.analysis.decision_evolution import (
- detect_supersessions_and_conflicts,
- )
-
- evo = await detect_supersessions_and_conflicts(
- session,
- repo_id,
- touched_ids=touched_ids,
- vector_store=store,
- )
- if any(evo.values()):
- logger.info("decision_supersession_detected", **evo)
- except Exception as _evo_err:
- logger.debug("supersession_detection_skipped", error=str(_evo_err))
- # Recompute staleness scores using git metadata.
- if result.git_metadata_list:
- try:
- git_meta_map: dict[str, dict] = {}
- for gm in result.git_metadata_list:
- gm_dict = gm if isinstance(gm, dict) else dataclasses.asdict(gm)
- fp = gm_dict.get("file_path", "")
- if fp:
- git_meta_map[fp] = gm_dict
- if git_meta_map:
- updated = await recompute_decision_staleness(session, repo_id, git_meta_map)
- if updated:
- logger.info("decision_staleness_recomputed", updated=updated)
- except Exception as _stale_err:
- logger.debug("staleness_scoring_skipped", error=str(_stale_err))
-
- # Retire records whose commits were reverted. Outside the block above: a
- # new revert retires a decision stored by an earlier run just as well.
- try:
- from repowise.core.analysis.decisions.reverts import apply_revert_supersession
-
- await apply_revert_supersession(session, repo_id, getattr(result, "repo_path", None))
- except Exception as _revert_err:
- logger.debug("revert_supersession_skipped", error=str(_revert_err))
- try:
- from repowise.core.analysis.decisions.head_artifacts import apply_head_artifact_check
-
- await apply_head_artifact_check(session, repo_id, getattr(result, "repo_path", None))
- except Exception as _artifact_err:
- logger.debug("head_artifact_check_skipped", error=str(_artifact_err))
-
- # ---- Governance findings (additive pass, after decisions are persisted) ----
- # Runs after bulk_upsert_decisions + detect_supersessions_and_conflicts so
- # the decision graph is complete. Best-effort: never breaks persist.
- try:
- await refresh_governance_findings(session, repo_id)
- except Exception as _gov_err:
- logger.debug("governance_findings_skipped", error=str(_gov_err))
-
-
-async def persist_generation(result: Any, session: Any, repo_id: str) -> None:
- """Persist generation-phase outputs: wiki pages and knowledge-graph layers.
-
- Pages upsert per ``page_id`` (archiving prior versions); KG layers/tour
- are full-replace. Both safe to call incrementally / on resume.
- """
- from repowise.core.persistence import upsert_pages_from_generated
-
- # ---- Pages (if generated) -----------------------------------------------
- # Batched: one SELECT + one flush instead of a SELECT+flush per page. The
- # per-page durability sink already streamed these during generation; this
- # end-of-run pass flushes the post-generation metadata enrichment. See
- # upsert_pages_from_generated for the equivalence contract.
- if result.generated_pages:
- await upsert_pages_from_generated(session, result.generated_pages, repo_id)
-
- # ---- Knowledge graph layers, tour steps & curated meta ------------------
- kg = getattr(result, "knowledge_graph_result", None)
- if kg is not None:
- await persist_kg(kg, session, repo_id)
-
-
-async def persist_kg(kg: Any, session: Any, repo_id: str) -> None:
- """Persist knowledge-graph layers, tour steps, and curated meta.
-
- Full-replace semantics, safe to call incrementally — shared by the full
- pipeline (:func:`persist_generation`) and the incremental update path so
- a refreshed KG lands through the same writers.
- """
- from repowise.core.persistence.crud import (
- file_node_meta_from_kg_nodes,
- upsert_kg_layers,
- upsert_kg_node_meta,
- upsert_kg_project_meta,
- upsert_kg_tour_steps,
- )
-
- if hasattr(kg, "layers") and kg.layers:
- await upsert_kg_layers(session, repo_id, kg.layers)
- if hasattr(kg, "tour") and kg.tour:
- await upsert_kg_tour_steps(session, repo_id, kg.tour)
-
- # Project-level curated meta (ranked entry points from the curation pass).
- project = getattr(kg, "project", None)
- if isinstance(project, dict) and project.get("entry_points"):
- await upsert_kg_project_meta(
- session,
- repo_id,
- entry_points=project["entry_points"],
- entry_candidates=project.get("entry_candidates", []),
- )
-
- # Per-node curated meta (type/summary/tags) for file nodes, stored with
- # the "file:" prefix stripped so the architecture view can match its
- # node ids (plain repo-relative paths) directly.
- file_node_meta = file_node_meta_from_kg_nodes(getattr(kg, "nodes", None) or [])
- if file_node_meta:
- await upsert_kg_node_meta(session, repo_id, file_node_meta)
-
-
-async def _refresh_commit_health(result: Any, session: Any, repo_id: str) -> None:
- """Seed the per-commit health rows for the commits this run wrote."""
- repo_path = getattr(result, "repo_path", "")
- summary = getattr(result, "git_summary", None)
- if not repo_path or summary is None:
- return
- from .commit_health import recent_shas, refresh_commit_health
-
- await refresh_commit_health(
- session,
- repo_id,
- repo_path,
- recent_shas(getattr(summary, "commit_rows", None)),
- )
-
-
-async def persist_pipeline_result(
- result: Any,
- session: Any,
- repo_id: str,
- *,
- replace_full_git_history: bool = False,
-) -> list[str]:
- """Persist all outputs from a :class:`PipelineResult` into the database.
-
- Thin composition of the four phase-scoped persisters
- (:func:`persist_ingestion`, :func:`persist_git`, :func:`persist_analysis`,
- :func:`persist_generation`) in dependency order. The same functions are
- reused by the incremental-persistence path so a resumed run can persist
- one phase at a time.
-
- Parameters
- ----------
- result:
- A ``PipelineResult`` from ``run_pipeline()``.
- session:
- An active SQLAlchemy ``AsyncSession`` (caller manages commit/rollback).
- repo_id:
- The repository ID to associate all records with.
-
- Returns
- -------
- The page ids of stale generated pages swept by this run. Callers should
- remove them from the FTS index after the session closes.
-
- Note
- ----
- FTS indexing is intentionally excluded here — callers must do it after
- this session closes to avoid SQLite write-lock conflicts.
-
- This function mutates ``sym.file_path`` on parsed-file symbols that
- lack one. Callers should treat *result* as consumed after this call.
- """
- # Prune rows for files absent from this full result before the phase
- # persisters re-upsert. graph/analysis tables key off parsed_files;
- # git_metadata keys off the git indexer's set (a file can be git-tracked
- # but unparsed). Runs only here, never in the reusable phase persisters.
- # ``file_infos`` is the successful traversal set and survives individual
- # read/parse failures. Using parsed_files here would misclassify a locked
- # or temporarily unparsable file as excluded and erase its prior rows.
- current_graph_file_paths = {file_info.path for file_info in result.file_infos}
- current_git_file_paths = {
- (gm if isinstance(gm, dict) else dataclasses.asdict(gm)).get("file_path", "")
- for gm in result.git_metadata_list
- }
- current_git_file_paths.discard("")
- swept_page_ids = await reconcile_full_index_scope(
- session, repo_id, current_graph_file_paths, current_git_file_paths
- )
-
- symbol_count = await persist_ingestion(result, session, repo_id)
- if replace_full_git_history:
- from repowise.core.persistence.crud import purge_proposed_decisions_by_source
-
- await purge_proposed_decisions_by_source(session, repo_id, "git_archaeology")
- await replace_git_history(
- session,
- repo_id,
- {
- (gm if isinstance(gm, dict) else dataclasses.asdict(gm))["file_path"]: (
- gm if isinstance(gm, dict) else dataclasses.asdict(gm)
- )
- for gm in result.git_metadata_list
- },
- result.git_summary,
- )
- else:
- await persist_git(result, session, repo_id)
- await persist_analysis(result, session, repo_id)
- await persist_generation(result, session, repo_id)
-
- # What each recent commit did to health. Needs the working tree, so it
- # runs here rather than on the read path, and it is bounded: older commits
- # keep no row until a later update reaches them.
- await _refresh_commit_health(result, session, repo_id)
-
- # Sweep structurally-keyed generated pages (module/layer/scc) that this
- # run did not reproduce — their ids drift between runs, so without the
- # sweep every re-index strands the previous set as duplicates. Full runs
- # only, same rule as _prune_stale_file_rows.
- swept_page_ids += await _sweep_stale_generated_pages(
- session,
- repo_id,
- result.generated_pages,
- getattr(result, "authoritative_page_types", None),
- getattr(result, "preserved_page_ids", None),
- )
- # Rows of a page type that no longer exists at all. Independent of what
- # this run produced, so it runs on every path rather than only here.
- swept_page_ids += await sweep_retired_pages(session, repo_id)
-
- # Placement depends on the whole page set, so it is computed here rather
- # than during generation, after the sweep has retired anything stale.
- from .page_tree_sync import rebuild_page_tree
-
- await rebuild_page_tree(session, repo_id)
-
- logger.info(
- "pipeline_result_persisted",
- repo_id=repo_id,
- pages=len(result.generated_pages) if result.generated_pages else 0,
- graph_nodes=result.graph_builder.graph().number_of_nodes(),
- symbols=symbol_count,
- git_files=len(result.git_metadata_list),
- )
- return swept_page_ids
diff --git a/packages/core/src/repowise/core/pipeline/persist/__init__.py b/packages/core/src/repowise/core/pipeline/persist/__init__.py
new file mode 100644
index 000000000..b44f7b61c
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/__init__.py
@@ -0,0 +1,227 @@
+"""Shared persistence logic for pipeline results.
+
+Extracted from ``cli/commands/init_cmd.py`` so both the CLI and the server
+can persist a ``PipelineResult`` without duplicating the upsert recipe.
+"""
+
+# The steps live in the submodules; every name they define, private ones
+# included, is re-exported here so imports and patches on this module keep working.
+# A submodule calls a step that callers patch here through the package
+# (``_persist.<name>``), never by bare name, or the patch stops reaching it.
+# ruff: noqa: F401
+
+from __future__ import annotations
+
+import dataclasses
+from typing import Any
+
+import structlog
+
+from .analysis import (
+ persist_analysis,
+)
+from .generation import (
+ persist_generation,
+ persist_kg,
+)
+from .git import (
+ _rebuild_changes,
+ persist_git,
+ persist_git_refresh,
+ replace_git_history,
+)
+from .graph import (
+ _betweenness_commits,
+ _changed_file_edges,
+ _changed_file_symbols,
+ _community_meta,
+ _derive_entry_point_scores,
+ _edge_row,
+ _edges_predate_cohesion,
+ _prune_vanished_symbol_nodes,
+ _stamp_betweenness_commit,
+ _stored_edges_parser_fingerprint,
+ has_graph_edges,
+ persist_graph_nodes,
+ persist_incremental_edges,
+ persist_incremental_symbols,
+ persist_symbol_analysis,
+ stamp_edges_parser_fingerprint,
+)
+from .health import (
+ _analyzed_commit,
+ refresh_governance_findings,
+ save_full_health_report,
+ snapshot_health_from_store,
+)
+from .ingestion import (
+ persist_ingestion,
+)
+from .prune import (
+ _PRUNE_CHUNK,
+ _PRUNE_FLOOR_MIN_ROWS,
+ _PRUNE_MAX_FRACTION,
+ _FileLiveness,
+ _git_tracked_paths,
+ _prune_stale_file_rows,
+ _resolve_plans_of_deleted_files,
+ path_liveness,
+ prune_deleted_file_rows,
+)
+from .security import (
+ _replace_security_findings,
+ persist_incremental_security_findings,
+ persist_security_findings,
+)
+from .sweeps import (
+ _SWEPT_GENERATED_PAGE_TYPES,
+ _sweep_stale_generated_pages,
+ _symbol_names_by_file,
+ sweep_absent_cycle_pages,
+ sweep_absent_symbol_spotlights,
+ sweep_retired_pages,
+ sweep_superseded_generated_pages,
+)
+from .tombstones import (
+ _SPOTLIGHT_PATHS_PER_QUERY,
+ _STALE_ID_CHUNK,
+ _log,
+ mark_page_ids_stale,
+ mark_stale_pages,
+ mark_tombstone_pages,
+ reconcile_full_index_scope,
+ tombstone_absent_file_pages,
+ tombstone_candidates,
+ tombstone_file_pages_outside_scope,
+ tombstone_pages_outside_generation,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+async def _refresh_commit_health(result: Any, session: Any, repo_id: str) -> None:
+ """Seed the per-commit health rows for the commits this run wrote."""
+ repo_path = getattr(result, "repo_path", "")
+ summary = getattr(result, "git_summary", None)
+ if not repo_path or summary is None:
+ return
+ from ..commit_health import recent_shas, refresh_commit_health
+
+ await refresh_commit_health(
+ session,
+ repo_id,
+ repo_path,
+ recent_shas(getattr(summary, "commit_rows", None)),
+ )
+
+
+async def persist_pipeline_result(
+ result: Any,
+ session: Any,
+ repo_id: str,
+ *,
+ replace_full_git_history: bool = False,
+) -> list[str]:
+ """Persist all outputs from a :class:`PipelineResult` into the database.
+
+ Thin composition of the four phase-scoped persisters
+ (:func:`persist_ingestion`, :func:`persist_git`, :func:`persist_analysis`,
+ :func:`persist_generation`) in dependency order. The same functions are
+ reused by the incremental-persistence path so a resumed run can persist
+ one phase at a time.
+
+ Parameters
+ ----------
+ result:
+ A ``PipelineResult`` from ``run_pipeline()``.
+ session:
+ An active SQLAlchemy ``AsyncSession`` (caller manages commit/rollback).
+ repo_id:
+ The repository ID to associate all records with.
+
+ Returns
+ -------
+ The page ids of stale generated pages swept by this run. Callers should
+ remove them from the FTS index after the session closes.
+
+ Note
+ ----
+ FTS indexing is intentionally excluded here — callers must do it after
+ this session closes to avoid SQLite write-lock conflicts.
+
+ This function mutates ``sym.file_path`` on parsed-file symbols that
+ lack one. Callers should treat *result* as consumed after this call.
+ """
+ # Prune rows for files absent from this full result before the phase
+ # persisters re-upsert. graph/analysis tables key off parsed_files;
+ # git_metadata keys off the git indexer's set (a file can be git-tracked
+ # but unparsed). Runs only here, never in the reusable phase persisters.
+ # ``file_infos`` is the successful traversal set and survives individual
+ # read/parse failures. Using parsed_files here would misclassify a locked
+ # or temporarily unparsable file as excluded and erase its prior rows.
+ current_graph_file_paths = {file_info.path for file_info in result.file_infos}
+ current_git_file_paths = {
+ (gm if isinstance(gm, dict) else dataclasses.asdict(gm)).get("file_path", "")
+ for gm in result.git_metadata_list
+ }
+ current_git_file_paths.discard("")
+ swept_page_ids = await reconcile_full_index_scope(
+ session, repo_id, current_graph_file_paths, current_git_file_paths
+ )
+
+ symbol_count = await persist_ingestion(result, session, repo_id)
+ if replace_full_git_history:
+ from repowise.core.persistence.crud import purge_proposed_decisions_by_source
+
+ await purge_proposed_decisions_by_source(session, repo_id, "git_archaeology")
+ await replace_git_history(
+ session,
+ repo_id,
+ {
+ (gm if isinstance(gm, dict) else dataclasses.asdict(gm))["file_path"]: (
+ gm if isinstance(gm, dict) else dataclasses.asdict(gm)
+ )
+ for gm in result.git_metadata_list
+ },
+ result.git_summary,
+ )
+ else:
+ await persist_git(result, session, repo_id)
+ await persist_analysis(result, session, repo_id)
+ await persist_generation(result, session, repo_id)
+
+ # What each recent commit did to health. Needs the working tree, so it
+ # runs here rather than on the read path, and it is bounded: older commits
+ # keep no row until a later update reaches them.
+ await _refresh_commit_health(result, session, repo_id)
+
+ # Sweep structurally-keyed generated pages (module/layer/scc) that this
+ # run did not reproduce — their ids drift between runs, so without the
+ # sweep every re-index strands the previous set as duplicates. Full runs
+ # only, same rule as _prune_stale_file_rows.
+ swept_page_ids += await _sweep_stale_generated_pages(
+ session,
+ repo_id,
+ result.generated_pages,
+ getattr(result, "authoritative_page_types", None),
+ getattr(result, "preserved_page_ids", None),
+ )
+ # Rows of a page type that no longer exists at all. Independent of what
+ # this run produced, so it runs on every path rather than only here.
+ swept_page_ids += await sweep_retired_pages(session, repo_id)
+
+ # Placement depends on the whole page set, so it is computed here rather
+ # than during generation, after the sweep has retired anything stale.
+ from ..page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
+
+ logger.info(
+ "pipeline_result_persisted",
+ repo_id=repo_id,
+ pages=len(result.generated_pages) if result.generated_pages else 0,
+ graph_nodes=result.graph_builder.graph().number_of_nodes(),
+ symbols=symbol_count,
+ git_files=len(result.git_metadata_list),
+ )
+ return swept_page_ids
diff --git a/packages/core/src/repowise/core/pipeline/persist/analysis.py b/packages/core/src/repowise/core/pipeline/persist/analysis.py
new file mode 100644
index 000000000..1b2db3888
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/analysis.py
@@ -0,0 +1,263 @@
+"""Analysis-phase persistence: dead code, drift, health and decisions."""
+
+from __future__ import annotations
+
+import dataclasses
+from typing import Any
+
+import structlog
+
+# Patchable steps are looked up on the package at call time, so a patch on
+# ``repowise.core.pipeline.persist`` reaches this module too.
+from repowise.core.pipeline import persist as _persist
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
+ """Persist analysis-phase outputs: dead code, health, decisions, drift.
+
+ Dead-code, health and doc-drift writes are repo-wide DELETE-THEN-INSERT (so
+ they converge on re-run but don't support partial-within-phase resume);
+ decisions/governance are idempotent. Intended to run once the analysis
+ phase has fully completed.
+ """
+ from repowise.core.persistence.crud import (
+ bulk_upsert_decisions,
+ recompute_decision_staleness,
+ replace_doc_drift_guarded,
+ save_coverage_files,
+ save_dead_code_findings,
+ set_repo_function_mod_p80,
+ upsert_git_function_blame_bulk,
+ )
+
+ # ---- Dead code findings --------------------------------------------------
+ # Written even when empty: a run that found nothing must clear the old
+ # open rows, not leave them standing as current findings.
+ if result.dead_code_report is not None:
+ await save_dead_code_findings(session, repo_id, result.dead_code_report.findings or [])
+
+ # ---- Documentation drift: findings and resolved references --------------
+ # Both tables, one savepoint, one run. Written even when the finding list
+ # is empty, unlike dead code above: a run that fixed the last drifted
+ # reference must clear the rows, and a guard on ``.findings`` would leave
+ # the old ones standing as though the documents were still wrong.
+ # ``authoritative_paths`` is None on a full run, so the replace is
+ # repo-wide.
+ drift = getattr(result, "doc_drift_report", None)
+ if drift is not None:
+ try:
+ await replace_doc_drift_guarded(session, repo_id, drift)
+ except Exception as exc:
+ logger.warning("doc_drift_persist_skipped", error=str(exc))
+
+ # ---- Health findings + per-file metrics ---------------------------------
+ if getattr(result, "health_report", None):
+ hr = result.health_report
+ # Hoisted out of the coverage branch below: the same sha now stamps the
+ # metric rows, so a reader can tell how far the health pass lags the
+ # index instead of assuming the two moved together.
+ head_sha = await _persist._analyzed_commit(session, repo_id)
+ await _persist.save_full_health_report(
+ session,
+ repo_id,
+ hr,
+ analyzed_commit=head_sha,
+ repo_path=getattr(result, "repo_path", None),
+ )
+ # Resolved coverage rows, when a report was ingested this run.
+ coverage_files = getattr(hr, "coverage_files", None)
+ if coverage_files:
+ await save_coverage_files(
+ session,
+ repo_id,
+ coverage_files,
+ source_format=getattr(hr, "coverage_format", None) or "lcov",
+ ingested_commit_sha=head_sha,
+ provenance=getattr(hr, "coverage_provenance", None),
+ )
+ # Per-function blame rollup (FULL tier only; empty otherwise).
+ fn_blame_rows = getattr(hr, "function_blame_rows", None)
+ if fn_blame_rows:
+ await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)
+ # The hotspot gate an incremental update will score against. Written
+ # only by a run that walked the whole repo (the analyzer leaves it None
+ # otherwise), so an incremental run cannot publish its changed-files
+ # subset as the repo-wide percentile.
+ fn_mod_p80 = getattr(hr, "repo_function_mod_p80", None)
+ if fn_mod_p80:
+ await set_repo_function_mod_p80(session, repo_id, fn_mod_p80)
+ # Snapshot the run for trend tracking (rolling delete inside). From
+ # the rows just written, by the same writer the update path uses.
+ await _persist.snapshot_health_from_store(session, repo_id)
+
+ # ---- Decision records ----------------------------------------------------
+ # One contributor: the multi-source extractor. A second read used to fold
+ # ``page.metadata["harvested_decisions"]`` in from LLM page generation, but
+ # nothing ever wrote that key — harvesting only ever ran on ``file_page``,
+ # and file pages are rendered structurally now, so the directive had no
+ # host and the loop was permanently a no-op.
+ decision_dicts: list[dict] = []
+ if result.decision_report and result.decision_report.decisions:
+ decision_dicts.extend(dataclasses.asdict(d) for d in result.decision_report.decisions)
+
+ # Restore records the semantic supersession detector retired before it was
+ # turned off. ``superseded`` is a protected status, so nothing else will
+ # ever walk these back, and a store that only stops retiring is still a
+ # store with a quarter of its corpus hidden. Runs whether or not this run
+ # produced decisions.
+ #
+ # BEFORE the purge below, not after: restoring puts a row back at
+ # ``proposed``, which is exactly what the purge deletes. Un-retire first and
+ # a run ends in one consistent state — good records visible, retired-source
+ # records gone. The other order leaves a restored changelog row alive for
+ # one run and silently deletes it on the next.
+ try:
+ from repowise.core.persistence.crud import unretire_auto_superseded
+
+ await unretire_auto_superseded(session)
+ except Exception as _unretire_err:
+ logger.debug("decision_unretire_skipped", error=str(_unretire_err))
+
+ # One-shot drain of proposals left by retired extraction sources; without
+ # this, DBs indexed before a removal keep a flooded review queue forever
+ # (#751 for code_comment). Confirmed/dismissed rows are kept.
+ try:
+ from repowise.core.analysis.decision_provenance import RETIRED_SOURCES
+ from repowise.core.persistence.crud import purge_proposed_decisions_by_source
+
+ for _retired in RETIRED_SOURCES:
+ await purge_proposed_decisions_by_source(session, repo_id, _retired)
+ except Exception as _purge_err:
+ logger.debug("decision_purge_skipped", error=str(_purge_err))
+
+ # Re-stamp evidence rows left on a previous SOURCE_RANK ladder. Local stores
+ # are created by ``init_db`` and never see Alembic, so the migration alone
+ # would only reach hosted; this is the same repair on the path every store
+ # takes. No-op scan once reconciled, and it runs whether or not this run
+ # produced decisions, because a store with nothing new still holds the rows.
+ try:
+ from repowise.core.persistence.crud import reconcile_source_ranks
+
+ await reconcile_source_ranks(session)
+ except Exception as _rank_err:
+ logger.debug("decision_rank_reconcile_skipped", error=str(_rank_err))
+
+ # The same repair for the scoring formula, which leaves every input valid
+ # and every stored score stale, so no filter can find it. Its own try, so
+ # a failure here is not logged as the rank repair's.
+ try:
+ from repowise.core.persistence.crud import reconcile_decision_confidence
+
+ await reconcile_decision_confidence(session)
+ except Exception as _conf_err:
+ logger.debug("decision_confidence_reconcile_skipped", error=str(_conf_err))
+
+ # Move legacy records onto ids derived from their own identity, before
+ # anything else reads or writes one. A random id is re-minted whenever a
+ # store is rebuilt rather than updated, which strands every reference held
+ # outside the row. Idempotent, and it never deletes a record.
+ try:
+ from repowise.core.persistence.decision_id_migration import apply_id_migration
+
+ await apply_id_migration(
+ session, repo_id, vector_store=getattr(result, "vector_store", None)
+ )
+ except Exception as _id_err:
+ logger.debug("decision_id_migration_skipped", error=str(_id_err))
+
+ # Classify legacy rows against the entity split. A record promoted by
+ # recurrence rather than by a person becomes a candidate, which visibly
+ # shrinks what governs; leaving it to an explicit command would instead
+ # leave the status column and the acceptance log permanently disagreeing,
+ # with half the surfaces reading each. Idempotent, and it never reopens a
+ # review action somebody already performed.
+ 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,
+ )
+
+ await apply_migration(session, repo_id)
+ # Beside it, and for the same reason: these repair rows written before
+ # the rule existed, and nothing re-extracts them. The prune runs first
+ # so the two basis repairs judge the file list they will leave behind.
+ 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))
+
+ if decision_dicts:
+ # Reuse the run's shared vector store for semantic (paraphrase) dedup
+ # and to make decisions searchable; title dedup still runs when None.
+ store = getattr(result, "vector_store", None)
+ touched_ids = await bulk_upsert_decisions(
+ session,
+ repo_id,
+ decision_dicts,
+ vector_store=store,
+ )
+ # Phase 3B: detect supersession/conflict among the just-upserted
+ # decisions and record typed edges (auto-flipping the older only above
+ # the high-confidence threshold). Heuristic-only here (no provider on
+ # the persist path); the update path adds the gated LLM tiebreaker.
+ if touched_ids and store is not None:
+ try:
+ from repowise.core.analysis.decision_evolution import (
+ detect_supersessions_and_conflicts,
+ )
+
+ evo = await detect_supersessions_and_conflicts(
+ session,
+ repo_id,
+ touched_ids=touched_ids,
+ vector_store=store,
+ )
+ if any(evo.values()):
+ logger.info("decision_supersession_detected", **evo)
+ except Exception as _evo_err:
+ logger.debug("supersession_detection_skipped", error=str(_evo_err))
+ # Recompute staleness scores using git metadata.
+ if result.git_metadata_list:
+ try:
+ git_meta_map: dict[str, dict] = {}
+ for gm in result.git_metadata_list:
+ gm_dict = gm if isinstance(gm, dict) else dataclasses.asdict(gm)
+ fp = gm_dict.get("file_path", "")
+ if fp:
+ git_meta_map[fp] = gm_dict
+ if git_meta_map:
+ updated = await recompute_decision_staleness(session, repo_id, git_meta_map)
+ if updated:
+ logger.info("decision_staleness_recomputed", updated=updated)
+ except Exception as _stale_err:
+ logger.debug("staleness_scoring_skipped", error=str(_stale_err))
+
+ # Retire records whose commits were reverted. Outside the block above: a
+ # new revert retires a decision stored by an earlier run just as well.
+ try:
+ from repowise.core.analysis.decisions.reverts import apply_revert_supersession
+
+ await apply_revert_supersession(session, repo_id, getattr(result, "repo_path", None))
+ except Exception as _revert_err:
+ logger.debug("revert_supersession_skipped", error=str(_revert_err))
+ try:
+ from repowise.core.analysis.decisions.head_artifacts import apply_head_artifact_check
+
+ await apply_head_artifact_check(session, repo_id, getattr(result, "repo_path", None))
+ except Exception as _artifact_err:
+ logger.debug("head_artifact_check_skipped", error=str(_artifact_err))
+
+ # ---- Governance findings (additive pass, after decisions are persisted) ----
+ # Runs after bulk_upsert_decisions + detect_supersessions_and_conflicts so
+ # the decision graph is complete. Best-effort: never breaks persist.
+ try:
+ await _persist.refresh_governance_findings(session, repo_id)
+ except Exception as _gov_err:
+ logger.debug("governance_findings_skipped", error=str(_gov_err))
diff --git a/packages/core/src/repowise/core/pipeline/persist/generation.py b/packages/core/src/repowise/core/pipeline/persist/generation.py
new file mode 100644
index 000000000..3567cd4c5
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/generation.py
@@ -0,0 +1,73 @@
+"""Generation-phase persistence: wiki pages and knowledge-graph layers."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+# Patchable steps are looked up on the package at call time, so a patch on
+# ``repowise.core.pipeline.persist`` reaches this module too.
+from repowise.core.pipeline import persist as _persist
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+async def persist_generation(result: Any, session: Any, repo_id: str) -> None:
+ """Persist generation-phase outputs: wiki pages and knowledge-graph layers.
+
+ Pages upsert per ``page_id`` (archiving prior versions); KG layers/tour
+ are full-replace. Both safe to call incrementally / on resume.
+ """
+ from repowise.core.persistence import upsert_pages_from_generated
+
+ # ---- Pages (if generated) -----------------------------------------------
+ # Batched: one SELECT + one flush instead of a SELECT+flush per page. The
+ # per-page durability sink already streamed these during generation; this
+ # end-of-run pass flushes the post-generation metadata enrichment. See
+ # upsert_pages_from_generated for the equivalence contract.
+ if result.generated_pages:
+ await upsert_pages_from_generated(session, result.generated_pages, repo_id)
+
+ # ---- Knowledge graph layers, tour steps & curated meta ------------------
+ kg = getattr(result, "knowledge_graph_result", None)
+ if kg is not None:
+ await _persist.persist_kg(kg, session, repo_id)
+
+
+async def persist_kg(kg: Any, session: Any, repo_id: str) -> None:
+ """Persist knowledge-graph layers, tour steps, and curated meta.
+
+ Full-replace semantics, safe to call incrementally — shared by the full
+ pipeline (:func:`persist_generation`) and the incremental update path so
+ a refreshed KG lands through the same writers.
+ """
+ from repowise.core.persistence.crud import (
+ file_node_meta_from_kg_nodes,
+ upsert_kg_layers,
+ upsert_kg_node_meta,
+ upsert_kg_project_meta,
+ upsert_kg_tour_steps,
+ )
+
+ if hasattr(kg, "layers") and kg.layers:
+ await upsert_kg_layers(session, repo_id, kg.layers)
+ if hasattr(kg, "tour") and kg.tour:
+ await upsert_kg_tour_steps(session, repo_id, kg.tour)
+
+ # Project-level curated meta (ranked entry points from the curation pass).
+ project = getattr(kg, "project", None)
+ if isinstance(project, dict) and project.get("entry_points"):
+ await upsert_kg_project_meta(
+ session,
+ repo_id,
+ entry_points=project["entry_points"],
+ entry_candidates=project.get("entry_candidates", []),
+ )
+
+ # Per-node curated meta (type/summary/tags) for file nodes, stored with
+ # the "file:" prefix stripped so the architecture view can match its
+ # node ids (plain repo-relative paths) directly.
+ file_node_meta = file_node_meta_from_kg_nodes(getattr(kg, "nodes", None) or [])
+ if file_node_meta:
+ await upsert_kg_node_meta(session, repo_id, file_node_meta)
diff --git a/packages/core/src/repowise/core/pipeline/persist/git.py b/packages/core/src/repowise/core/pipeline/persist/git.py
new file mode 100644
index 000000000..9d8201522
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/git.py
@@ -0,0 +1,194 @@
+"""Git metadata and history writers."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+async def persist_git(result: Any, session: Any, repo_id: str) -> None:
+ """Persist git-phase outputs: per-file metadata and per-commit rows.
+
+ Both writes are idempotent UPSERTs keyed by ``(repo_id, file_path)`` /
+ ``(repo_id, sha)`` — safe to call incrementally and on resume.
+ """
+ from repowise.core.persistence.crud import (
+ clear_attribution_if_disabled,
+ prune_fix_events_before,
+ update_repo_git_totals,
+ upsert_fix_events_bulk,
+ upsert_git_commit_files_bulk,
+ upsert_git_commits_bulk,
+ upsert_git_metadata_bulk,
+ )
+
+ if result.git_metadata_list:
+ await upsert_git_metadata_bulk(session, repo_id, result.git_metadata_list)
+
+ summary = getattr(result, "git_summary", None)
+
+ # Per-commit rows + change-risk ride on the git summary.
+ commit_rows = getattr(summary, "commit_rows", None)
+ if commit_rows:
+ await upsert_git_commits_bulk(session, repo_id, commit_rows)
+
+ commit_file_rows = getattr(summary, "commit_file_rows", None)
+ if commit_file_rows:
+ await upsert_git_commit_files_bulk(session, repo_id, commit_file_rows)
+ await clear_attribution_if_disabled(session, repo_id)
+ if summary is not None:
+ await _rebuild_changes(session, repo_id)
+
+ # Per fix-commit x file rows (with their SZZ candidates). The prune keeps a
+ # re-index of an already-indexed repo from leaving behind events that have
+ # since aged out of the defect window.
+ fix_event_rows = getattr(summary, "fix_event_rows", None)
+ if fix_event_rows:
+ await upsert_fix_events_bulk(session, repo_id, fix_event_rows)
+ oldest_ts = getattr(summary, "fix_oldest_ts", 0)
+ if oldest_ts and getattr(summary, "fix_events_built", False):
+ from datetime import UTC, datetime
+
+ await prune_fix_events_before(session, repo_id, datetime.fromtimestamp(oldest_ts, tz=UTC))
+
+ # Symbol attribution + bug-magnet rollups, over the rows just written.
+ # Failure-isolated: a rollup that cannot be computed leaves the previous
+ # values in place rather than blanking a surface mid-index.
+ try:
+ from repowise.core.pipeline.fix_rollups import apply_fix_rollups
+
+ await apply_fix_rollups(session, repo_id)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.debug("fix_rollups_failed", repo_id=repo_id, error=str(exc))
+
+ # Whole-history totals (true age / commit / contributor counts) also ride on
+ # the summary — stamp them on the Repository row so the stats page reads them
+ # instead of deriving them from the bounded ``git_commits`` sample (#730).
+ totals = getattr(summary, "repo_totals", None)
+ if totals is not None:
+ await update_repo_git_totals(
+ session,
+ repo_id,
+ total_commit_count=totals.total_commit_count,
+ total_merge_commit_count=getattr(totals, "total_merge_commit_count", None),
+ first_commit_at=totals.first_commit_at,
+ total_contributor_count=totals.total_contributor_count,
+ first_commit_author=totals.first_commit_author,
+ first_commit_subject=totals.first_commit_subject,
+ total_lines_added=totals.total_lines_added,
+ total_lines_deleted=totals.total_lines_deleted,
+ churn_anchor_sha=getattr(totals, "churn_anchor_sha", None),
+ )
+
+
+async def _rebuild_changes(session: Any, repo_id: str) -> None:
+ """Change records from the same history, after the commit labels they read."""
+ from repowise.core.changes.store import refresh_changes
+ from repowise.core.persistence.models import Repository
+
+ try:
+ repo = await session.get(Repository, repo_id)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.debug("changes_repo_lookup_failed", repo_id=repo_id, error=str(exc))
+ return
+ if repo is not None and repo.local_path:
+ await refresh_changes(session, repo_id, repo.local_path, rebuild=True)
+
+
+async def replace_git_history(
+ session: Any,
+ repo_id: str,
+ git_meta_map: dict[str, dict],
+ git_summary: Any,
+ *,
+ keep_commit_health: bool = False,
+) -> None:
+ """Replace every history-derived row from one authoritative Git walk.
+
+ ``keep_commit_health`` keeps the per-commit health rows. A walk that only
+ re-reads the same window under new rules leaves each commit's code, so its
+ health is still right, and the capped ``refresh_commit_health`` could not
+ rebuild rows past its budget. Those rows key on ``(repository_id, sha)``
+ alone, so nothing dangles; unreachable shas are pruned by the update's
+ orphan sweep.
+ """
+ from types import SimpleNamespace
+
+ from sqlalchemy import delete
+
+ from repowise.core.persistence.models import (
+ FixEvent,
+ GitCommit,
+ GitCommitFile,
+ GitCommitHealthDelta,
+ GitCommitHealthFinding,
+ GitMetadata,
+ )
+
+ # Function blame describes the current source tree and is produced by the
+ # health pass, not by persist_git. Preserve it across a history-window
+ # replacement; scope reconciliation prunes entries for excluded files.
+ health = () if keep_commit_health else (GitCommitHealthDelta, GitCommitHealthFinding)
+ for model in (FixEvent, GitCommit, GitCommitFile, *health, GitMetadata):
+ await session.execute(delete(model).where(model.repository_id == repo_id))
+ await persist_git(
+ SimpleNamespace(
+ git_metadata_list=list(git_meta_map.values()),
+ git_summary=git_summary,
+ ),
+ session,
+ repo_id,
+ )
+
+
+async def persist_git_refresh(
+ session: Any,
+ repo_id: str,
+ git_meta_map: dict[str, dict],
+ git_decay_map: dict[str, dict] | None,
+ full_git_summary: Any | None,
+ *,
+ keep_commit_health: bool = False,
+) -> None:
+ """Persist either a full history replacement or an incremental refresh."""
+ if full_git_summary is not None:
+ await replace_git_history(
+ session,
+ repo_id,
+ git_meta_map,
+ full_git_summary,
+ keep_commit_health=keep_commit_health,
+ )
+ return
+
+ from sqlalchemy import select
+
+ from repowise.core.persistence.crud import (
+ clear_attribution_if_disabled,
+ recompute_git_percentiles,
+ upsert_git_metadata_bulk,
+ )
+ from repowise.core.persistence.models import GitMetadata
+
+ decay_rows = list((git_decay_map or {}).values())
+ if decay_rows:
+ stored = set(
+ (
+ await session.execute(
+ select(GitMetadata.file_path).where(GitMetadata.repository_id == repo_id)
+ )
+ ).scalars()
+ )
+ # A decay row is partial, so it only refreshes a stored row: inserted,
+ # it is a fragment with no totals or owner. History-tier rows are
+ # complete and upsert whole, which also fills the non-code rows an
+ # index built before that tier never wrote.
+ decay_rows = [
+ row for row in decay_rows if row.get("history_only") or row["file_path"] in stored
+ ]
+ await upsert_git_metadata_bulk(session, repo_id, [*git_meta_map.values(), *decay_rows])
+ await recompute_git_percentiles(session, repo_id)
+ await clear_attribution_if_disabled(session, repo_id)
diff --git a/packages/core/src/repowise/core/pipeline/persist/graph.py b/packages/core/src/repowise/core/pipeline/persist/graph.py
new file mode 100644
index 000000000..864159b95
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/graph.py
@@ -0,0 +1,568 @@
+"""Graph node, symbol and edge writers for the full and incremental paths."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import structlog
+
+from repowise.core.entry_candidacy import is_reachability_root
+
+from .prune import _PRUNE_CHUNK
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+def _derive_entry_point_scores(graph_builder: Any) -> dict[str, float]:
+ """Best-effort entry-point scores from the builder's execution-flow report.
+
+ Returns ``{node_id: score}`` for every scored entry-point candidate (not
+ just the ones that produced a traced flow). The call is cached on the
+ builder, so this is cheap when flows were already computed.
+ """
+ try:
+ report = graph_builder.execution_flows()
+ except Exception as exc: # analysis is non-load-bearing for persistence
+ logger.warning("entry_point_scores_derive_failed", error=str(exc))
+ return {}
+ if report is None:
+ return {}
+ scores = getattr(report, "entry_point_scores", None)
+ if scores:
+ return dict(scores)
+ # Back-compat: older reports only expose per-flow scores.
+ return {
+ f.entry_point_id: f.entry_point_score
+ for f in getattr(report, "flows", []) or []
+ if hasattr(f, "entry_point_id") and hasattr(f, "entry_point_score")
+ }
+
+
+def _betweenness_commits(graph_builder: Any) -> dict[str, str | None]:
+ """Per kind, the commit its betweenness was last exactly computed at.
+
+ ``None`` means the builder cannot say, which is not "never scored" and must
+ not be written as one: a builder rehydrated from SQL serves real values it
+ did not compute, and stamping those NULL would report an entire indexed
+ repository as unscored.
+ """
+ scoring = getattr(graph_builder, "betweenness_scoring", None)
+ if scoring is None:
+ return {"file": None, "symbol": None}
+ try:
+ return {k: getattr(scoring(k), "scored_commit", None) for k in ("file", "symbol")}
+ except Exception: # pragma: no cover - a builder without the accessor
+ return {"file": None, "symbol": None}
+
+
+def _stamp_betweenness_commit(
+ node_dict: dict[str, Any],
+ node_type: str,
+ bc: dict[str, float],
+ sym_bc: dict[str, float],
+ bt_commits: dict[str, str | None],
+) -> None:
+ """Set ``betweenness_commit`` on a graph-node row when its scoring is known."""
+ node_id = node_dict["node_id"]
+ # Scored → its commit; in no scoring → NULL, the unscored marker;
+ # provenance unknown → key omitted, so the stored stamp survives.
+ if node_id in bc:
+ kind, scored = "file", True
+ elif node_id in sym_bc:
+ kind, scored = "symbol", True
+ else:
+ kind, scored = ("file" if node_type == "file" else "symbol"), False
+ if bt_commits[kind] is not None:
+ node_dict["betweenness_commit"] = bt_commits[kind] if scored else None
+
+
+def _community_meta(
+ node_id: str,
+ node_type: str,
+ cd: dict[str, Any],
+ sc: dict[str, Any],
+ ci: dict[Any, Any],
+ ep_scores: dict[str, float],
+) -> dict[str, Any]:
+ """The ``community_meta_json`` payload of one graph node."""
+ community_meta: dict[str, Any] = {}
+ if node_type == "file":
+ cid = cd.get(node_id, 0)
+ comm_info = ci.get(cid)
+ if comm_info:
+ community_meta = {
+ "label": comm_info.label,
+ "cohesion": comm_info.cohesion,
+ "conductance": comm_info.conductance,
+ }
+ elif node_type == "symbol":
+ sym_cid = sc.get(node_id)
+ if sym_cid is not None:
+ community_meta = {"symbol_community_id": sym_cid}
+ if node_id in ep_scores:
+ community_meta["entry_point_score"] = ep_scores[node_id]
+ return community_meta
+
+
+async def persist_graph_nodes(
+ session: Any,
+ repo_id: str,
+ graph_builder: Any,
+ ep_scores: dict[str, float] | None = None,
+ *,
+ timings: Any | None = None,
+) -> None:
+ """Persist file- and symbol-level graph nodes with full centrality metrics.
+
+ Lifted out of :func:`persist_pipeline_result` so the incremental
+ update path can refresh ``graph_nodes`` (including symbol-level
+ PageRank / betweenness) without constructing a full ``PipelineResult``.
+ """
+ from repowise.core.analysis.communities import stored_community_id
+ from repowise.core.persistence import (
+ batch_upsert_graph_metrics,
+ batch_upsert_graph_node_membership,
+ batch_upsert_graph_nodes,
+ )
+ from repowise.core.pipeline.phase_timing import timed
+
+ graph = graph_builder.graph()
+ with timed(timings, "persist.graph_nodes.metrics"):
+ pr = graph_builder.pagerank()
+ bc = graph_builder.betweenness_centrality()
+ sym_pr = graph_builder.symbol_pagerank()
+ sym_bc = graph_builder.symbol_betweenness_centrality()
+ cd = graph_builder.community_detection()
+ sc = graph_builder.symbol_communities()
+ ci = graph_builder.community_info()
+ # ``None`` means "derive scores from the graph" (the incremental update
+ # path passes nothing). An explicit ``{}`` means "no scores" and is left
+ # untouched. Without this, every ``update`` re-upserted symbol nodes with
+ # empty community_meta and wiped the entry_point_scores written at init,
+ # leaving get_execution_flows / the dashboard panel permanently empty.
+ if ep_scores is None:
+ with timed(timings, "persist.graph_nodes.entry_points"):
+ ep_scores = _derive_entry_point_scores(graph_builder)
+
+ bt_commits = _betweenness_commits(graph_builder)
+
+ timings_rows = timed(timings, "persist.graph_nodes.rows")
+ timings_rows.__enter__()
+ nodes = []
+ for node_id in graph.nodes:
+ data = graph.nodes[node_id]
+ node_type = data.get("node_type", "file")
+
+ node_dict: dict[str, Any] = {
+ "node_id": node_id,
+ "node_type": node_type,
+ "language": data.get("language", "unknown"),
+ "symbol_count": data.get("symbol_count", 0),
+ "has_error": data.get("has_error", False),
+ "is_test": data.get("is_test", False),
+ "is_entry_point": data.get("is_entry_point", False),
+ "is_reachability_root": is_reachability_root(data),
+ "always_run_reason": data.get("always_run_reason"),
+ # Files draw from the file-level metric tables; symbols fall
+ # back to the symbol subgraph (calls + heritage) so that the
+ # per-symbol UI panel shows real centrality instead of 0.
+ "pagerank": pr.get(node_id, sym_pr.get(node_id, 0.0)),
+ "betweenness": bc.get(node_id, sym_bc.get(node_id, 0.0)),
+ "community_id": stored_community_id(cd, node_id),
+ }
+
+ _stamp_betweenness_commit(node_dict, node_type, bc, sym_bc, bt_commits)
+
+ community_meta = _community_meta(node_id, node_type, cd, sc, ci, ep_scores)
+ node_dict["community_meta_json"] = json.dumps(community_meta)
+
+ if node_type == "symbol":
+ node_dict.update(
+ {
+ "kind": data.get("kind"),
+ "name": data.get("name"),
+ "qualified_name": data.get("qualified_name"),
+ "file_path": data.get("file_path"),
+ "start_line": data.get("start_line"),
+ "end_line": data.get("end_line"),
+ "visibility": data.get("visibility"),
+ "signature": data.get("signature"),
+ "parent_symbol_id": data.get("parent_name"),
+ "public_api": data.get("public_api"),
+ }
+ )
+ nodes.append(node_dict)
+ timings_rows.__exit__(None, None, None)
+
+ if nodes:
+ with timed(timings, "persist.graph_nodes.upsert"):
+ await batch_upsert_graph_nodes(session, repo_id, nodes)
+
+ # Materialize the file-level metrics snapshot (graph_metrics) so large
+ # repos can serve metric reads from SQL without recomputing the NetworkX
+ # centrality kernels. Additive to graph_nodes; never changes node rows.
+ try:
+ with timed(timings, "persist.graph_nodes.snapshots"):
+ await batch_upsert_graph_metrics(
+ session, repo_id, graph_builder.file_metrics_snapshot()
+ )
+ except Exception as exc: # materialization is non-load-bearing
+ logger.warning("graph_metrics_materialize_skipped", error=str(exc))
+
+ # Materialize file-level SCCs (import cycles) + symbol communities as
+ # queryable rows (graph_node_membership). Feeds the break-cycle /
+ # move-method refactoring surfaces; non-load-bearing like graph_metrics.
+ try:
+ with timed(timings, "persist.graph_nodes.snapshots"):
+ await batch_upsert_graph_node_membership(
+ session, repo_id, graph_builder.node_membership_snapshot()
+ )
+ except Exception as exc: # materialization is non-load-bearing
+ logger.warning("graph_node_membership_materialize_skipped", error=str(exc))
+
+
+def _changed_file_symbols(
+ parsed_files: list[Any] | None, changed_paths: list[str]
+) -> tuple[list[str], list[Any]]:
+ """``(reconcile_paths, symbols)`` for files that both changed and parsed.
+
+ Restricting to the intersection means a changed file that failed to parse
+ this run keeps its existing symbol rows (mirrors the graph, which skips
+ unparsed files) rather than having them wrongly pruned on a transient
+ failure. Mutates ``sym.file_path`` where the parser left it unset, same as
+ the full persist path.
+ """
+ changed = set(changed_paths or [])
+ reconcile_paths: list[str] = []
+ symbols: list[Any] = []
+ for pf in parsed_files or []:
+ path = pf.file_info.path
+ if path not in changed:
+ continue
+ reconcile_paths.append(path)
+ for sym in pf.symbols:
+ if not getattr(sym, "file_path", None):
+ sym.file_path = path
+ symbols.append(sym)
+ return reconcile_paths, symbols
+
+
+async def persist_incremental_symbols(
+ session: Any,
+ repo_id: str,
+ parsed_files: list[Any] | None,
+ changed_paths: list[str],
+) -> None:
+ """Refresh ``wiki_symbols`` for changed+parsed files on an incremental update.
+
+ The incremental update path re-parses changed files but never persisted
+ their symbols, so wiki_symbols bounds fossilized at the last full index and
+ the get_answer hydrator served drifted signatures/bodies. This upserts the
+ changed files' fresh symbols and prunes symbols that vanished from a
+ still-existing file. Scoped to the changed set for cost — the repo-wide
+ ``batch_upsert_symbols`` reloads every symbol row.
+ """
+ if not parsed_files:
+ return
+ from repowise.core.ingestion.parse_cache import parser_fingerprint
+ from repowise.core.persistence.crud import reconcile_symbols_for_files
+
+ # An extraction change can re-key symbols in files git did not touch (an
+ # overload gaining its own id), so it widens to the whole parsed set on the
+ # same check that widens edges. The stamp is written once, by
+ # :func:`persist_incremental_edges`, which runs after this.
+ if await _stored_edges_parser_fingerprint(session, repo_id) != parser_fingerprint():
+ changed_paths = [pf.file_info.path for pf in parsed_files]
+ reconcile_paths, symbols = _changed_file_symbols(parsed_files, changed_paths)
+ if not reconcile_paths:
+ return
+ await reconcile_symbols_for_files(session, repo_id, reconcile_paths, symbols)
+
+
+async def persist_symbol_analysis(
+ session: Any,
+ repo_id: str,
+ parsed_files: list[Any] | None,
+) -> None:
+ """Reconcile symbol rows after analysis mutates their derived fields.
+
+ Health analysis computes ``complexity_estimate`` on the in-memory symbols
+ after the resumable INDEX checkpoint has already persisted the parser
+ defaults. Re-upsert just those symbol records before ANALYSIS is marked
+ complete; graph construction, Git analysis, and the rest of ingestion stay
+ untouched. The upsert preserves each persisted row's database identity.
+ """
+ if not parsed_files:
+ return
+ from repowise.core.persistence.crud import batch_upsert_symbols
+
+ symbols: list[Any] = []
+ for pf in parsed_files:
+ for sym in pf.symbols:
+ if not getattr(sym, "file_path", None):
+ sym.file_path = pf.file_info.path
+ symbols.append(sym)
+ if symbols:
+ await batch_upsert_symbols(session, repo_id, symbols)
+
+
+def _changed_file_edges(
+ graph_builder: Any,
+ parsed_files: list[Any] | None,
+ changed_paths: list[str],
+) -> tuple[list[str], list[dict]]:
+ """``(reconcile_paths, edges)`` for edges emanating from changed+parsed files.
+
+ An edge is attributed to the file that owns its *source* node: a file node
+ is the path itself; a symbol node carries ``file_path``. An edge whose fact
+ sits at its target (``TARGET_OWNED_HINTS``) belongs to the target's file
+ as well, so editing the decorated file rewrites it. Restricting to
+ files that both changed and parsed this run mirrors ``_changed_file_symbols``
+ — a changed file that failed to parse keeps its existing edges rather than
+ having them wrongly wiped on a transient failure.
+ """
+ from repowise.core.ingestion.models import TARGET_OWNED_HINTS
+
+ changed = set(changed_paths or [])
+ parsed = {pf.file_info.path for pf in parsed_files or []}
+ reconcile = changed & parsed
+ if not reconcile:
+ return [], []
+
+ graph = graph_builder.graph()
+ owner: dict[str, str | None] = {}
+ for node_id in graph.nodes:
+ data = graph.nodes[node_id]
+ owner[node_id] = (
+ node_id if data.get("node_type", "file") == "file" else data.get("file_path")
+ )
+
+ edges: list[dict] = []
+ for u, v, data in graph.edges(data=True):
+ if owner.get(u) in reconcile or (
+ data.get("hint_source") in TARGET_OWNED_HINTS and owner.get(v) in reconcile
+ ):
+ edges.append(_edge_row(u, v, data))
+ return sorted(reconcile), edges
+
+
+def _edge_row(source: str, target: str, data: dict) -> dict:
+ """One ``graph_edges`` payload from an in-memory edge; both writers use it."""
+ return {
+ "source_node_id": source,
+ "target_node_id": target,
+ "imported_names_json": json.dumps(data.get("imported_names", [])),
+ "edge_type": data.get("edge_type", "imports"),
+ "confidence": data.get("confidence", 1.0),
+ "hint_source": data.get("hint_source"),
+ "resolution_origin": data.get("resolution_origin"),
+ "call_lines_json": json.dumps(data.get("call_lines", [])),
+ "type_only": bool(data.get("type_only", False)),
+ "deferred": bool(data.get("deferred", False)),
+ }
+
+
+async def _edges_predate_cohesion(session: Any, repo_id: str, graph_builder: Any) -> bool:
+ """True when ``graph_edges`` was written before edge cohesion was recorded.
+
+ An incremental update rewrites only the changed files' edges, so a store
+ indexed by an older build keeps that build's edges — and its resolution
+ mistakes — on every file that has not happened to change since. The health
+ engine and the server both read a graph rehydrated from those rows, so they
+ would go on reporting cycles the current engine no longer finds.
+
+ The signal is the store's own content rather than a version marker: a
+ routine update deliberately clamps ``store_format_version`` below the first
+ reindex gate, so a version comparison would refire on every run. Here, a
+ repo whose graph now has cohesion edges but whose table has no cohesion
+ ``hint_source`` anywhere is exactly a pre-cohesion store. Rewriting it
+ stamps those rows, so this answers False from then on and the full
+ reconcile happens once.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.ingestion.cohesion import COHESION_HINTS, is_cohesion_edge
+ from repowise.core.persistence.models import GraphEdge
+
+ try:
+ graph = graph_builder.graph()
+ except Exception:
+ return False
+ if not any(is_cohesion_edge(d) for _u, _v, d in graph.edges(data=True)):
+ return False # nothing to record, so nothing can be missing
+
+ row = (
+ await session.execute(
+ select(GraphEdge.id)
+ .where(
+ GraphEdge.repository_id == repo_id,
+ # Cohesion hints only: other passes (pytest conftest) stamp a
+ # hint too, and one of theirs is not a cohesion stamp.
+ GraphEdge.hint_source.in_(COHESION_HINTS),
+ )
+ .limit(1)
+ )
+ ).first()
+ return row is None
+
+
+async def has_graph_edges(session: Any, repo_id: str) -> bool:
+ """Whether this repo already has any ``graph_edges`` row."""
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import GraphEdge
+
+ row = (
+ await session.execute(
+ select(GraphEdge.repository_id).where(GraphEdge.repository_id == repo_id).limit(1)
+ )
+ ).first()
+ return row is not None
+
+
+async def _stored_edges_parser_fingerprint(session: Any, repo_id: str) -> str | None:
+ """The ``parser_fingerprint()`` recorded when this repo's edges were written.
+
+ ``None`` on a store written before the column existed, which is what makes
+ every already-shipped store take the widen once.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository
+
+ return (
+ await session.execute(
+ select(Repository.graph_edges_parser_fingerprint).where(Repository.id == repo_id)
+ )
+ ).scalar_one_or_none()
+
+
+async def stamp_edges_parser_fingerprint(session: Any, repo_id: str, fingerprint: str) -> None:
+ """Record the parser build that just wrote this repo's ``graph_edges``.
+
+ Written by :func:`persist_incremental_edges` after a widen, and by the full
+ :func:`persist_ingestion` path only when the store held no edges before it.
+ That path upserts edges (:func:`batch_upsert_graph_edges`) and prunes only
+ the nodes of files that vanished, so a re-index over an existing store adds
+ the new build's edges without removing the old build's surplus ones.
+ Stamping such a store would mark it parser-current and permanently suppress
+ the delete-then-insert reconcile that is the only thing which clears them;
+ it stays unstamped, and the first update widens. A fresh store has no
+ surplus, so it is stamped: unstamped, the next parser change could not be
+ told apart from "already up to date" on a quiet checkout.
+ """
+ from sqlalchemy import update
+
+ from repowise.core.persistence.models import Repository
+
+ await session.execute(
+ update(Repository)
+ .where(Repository.id == repo_id)
+ .values(graph_edges_parser_fingerprint=fingerprint)
+ )
+
+
+async def persist_incremental_edges(
+ session: Any,
+ repo_id: str,
+ graph_builder: Any,
+ parsed_files: list[Any] | None,
+ changed_paths: list[str],
+) -> None:
+ """Refresh ``graph_edges`` for changed files on an incremental update.
+
+ Sibling of :func:`persist_incremental_symbols`. The full-init path was the
+ only one that ever wrote ``graph_edges``; ``repowise update`` rebuilt the
+ graph but never repersisted edges, so adjacency froze at the last full
+ index. Phase E flow-path answers and any graph expansion read adjacency
+ straight from this table, so they decayed on every incremental update. This
+ delete-then-inserts the changed files' outgoing edges (dropping edges those
+ files no longer have). Scoped to the changed set for cost.
+
+ That scoping is also this function's one structural blind spot: an
+ extraction change (a tree-sitter query edit, an extractor fix) alters the
+ edges of *every* file, but only the git-changed ones get rewritten, so the
+ rest keep the old build's edges until they happen to change. The parse cache
+ self-invalidates on such a change (``parser_fingerprint`` hashes the ``.scm``
+ sources) and the update rebuilds the whole graph in memory anyway, so the
+ correct edges are already computed and only the write is too narrow. Widen
+ it whenever the fingerprint that last wrote the table differs from the
+ running one, then re-stamp. One comparison covers every future extraction
+ change; :func:`_edges_predate_cohesion` is the bespoke predecessor, kept
+ until shipped stores have all been stamped.
+ """
+ # An empty parse still counts: a repo with no source files has nothing to
+ # widen, and it must be stamped, or a missing stamp re-parses it forever.
+ if graph_builder is None or parsed_files is None:
+ return
+ from repowise.core.ingestion.parse_cache import parser_fingerprint
+ from repowise.core.persistence.crud import reconcile_edges_for_files
+
+ # Widen the reconcile to the whole parsed set, once. Same code path, so the
+ # delete-then-insert still drops edges a file no longer has — which is what
+ # clears the old build's resolution mistakes, an upsert alone would leave
+ # them behind.
+ fingerprint = parser_fingerprint()
+ parser_changed = await _stored_edges_parser_fingerprint(session, repo_id) != fingerprint
+ if parser_changed:
+ changed_paths = [pf.file_info.path for pf in parsed_files]
+ logger.info("graph_edges_parser_backfill", repo_id=repo_id, files=len(changed_paths))
+ elif await _edges_predate_cohesion(session, repo_id, graph_builder):
+ changed_paths = [pf.file_info.path for pf in parsed_files]
+ logger.info("graph_edges_cohesion_backfill", repo_id=repo_id, files=len(changed_paths))
+
+ reconcile_paths, edges = _changed_file_edges(graph_builder, parsed_files, changed_paths)
+ if reconcile_paths:
+ await reconcile_edges_for_files(session, repo_id, reconcile_paths, edges)
+ # Every reconciled file, not only a widen's: a symbol renamed or removed
+ # in a changed file otherwise keeps its node beside the new one.
+ await _prune_vanished_symbol_nodes(session, repo_id, graph_builder, reconcile_paths)
+ # Only after the widen actually ran to completion. Raising here (or in any
+ # caller before the commit) leaves the old stamp, so the next update retries
+ # rather than stranding the files it never reached.
+ if parser_changed:
+ await stamp_edges_parser_fingerprint(session, repo_id, fingerprint)
+
+
+async def _prune_vanished_symbol_nodes(
+ session: Any, repo_id: str, graph_builder: Any, paths: list[str]
+) -> None:
+ """Delete symbol ``graph_nodes`` of *paths* a re-extraction no longer produces.
+
+ ``persist_graph_nodes`` upserts the current graph and never deletes, so a
+ symbol whose id changed (a rename, or an overload gaining its own id under
+ a new parser) would otherwise keep its old row beside the new ones. Scoped
+ to files this run reconciled; a file that is gone is
+ :func:`_prune_stale_file_rows`'s job.
+ Membership rows prune themselves on their next write, and ``graph_metrics``
+ holds files only.
+ """
+ from sqlalchemy import delete, or_, select
+
+ from repowise.core.persistence.models import GraphEdge, GraphNode
+
+ graph = graph_builder.graph()
+ stale: list[str] = []
+ for i in range(0, len(paths), _PRUNE_CHUNK):
+ rows = await session.execute(
+ select(GraphNode.node_id).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_type != "file",
+ GraphNode.file_path.in_(paths[i : i + _PRUNE_CHUNK]),
+ )
+ )
+ stale.extend(node_id for node_id in rows.scalars() if node_id not in graph)
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(
+ delete(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ or_(GraphEdge.source_node_id.in_(batch), GraphEdge.target_node_id.in_(batch)),
+ )
+ )
+ await session.execute(
+ delete(GraphNode).where(GraphNode.repository_id == repo_id, GraphNode.node_id.in_(batch))
+ )
+ if stale:
+ logger.info("graph_nodes_parser_prune", repo_id=repo_id, nodes=len(stale))
diff --git a/packages/core/src/repowise/core/pipeline/persist/health.py b/packages/core/src/repowise/core/pipeline/persist/health.py
new file mode 100644
index 000000000..95f73d959
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/health.py
@@ -0,0 +1,244 @@
+"""Health report writers and the governance findings refresh."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+# Patchable steps are looked up on the package at call time, so a patch on
+# ``repowise.core.pipeline.persist`` reaches this module too.
+from repowise.core.pipeline import persist as _persist
+
+from .prune import path_liveness
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+async def _analyzed_commit(session: Any, repo_id: str) -> str | None:
+ """Live HEAD of the repo being indexed, for stamping health rows.
+
+ Read off disk rather than from ``Repository.head_commit``: the health pass
+ just scored the working tree, and the stored column is written by a
+ different step whose ordering relative to this one is not guaranteed.
+ ``None`` on any failure — an unstamped row reads as "not recorded", which
+ is honest, while a wrong sha would not be. Both index paths read it here;
+ the pipeline result carries no sha, so the full path used to stamp ``NULL``.
+ """
+ from repowise.core.persistence.models import Repository
+ from repowise.core.workspace.update import get_head_commit
+
+ try:
+ repo = await session.get(Repository, repo_id)
+ local_path = getattr(repo, "local_path", None) if repo else None
+ return get_head_commit(Path(local_path)) if local_path else None
+ except Exception:
+ return None
+
+
+async def snapshot_health_from_store(session: Any, repo_id: str) -> None:
+ """Append a ``HealthSnapshot`` built from the repository's stored rows.
+
+ One writer for the full index and the incremental update. A partial report
+ cannot be snapshotted directly, because it holds only the changed files and
+ a snapshot has to describe the whole repository; the store after the write
+ holds exactly that, on both paths.
+
+ Best-effort: a snapshot that fails to write is logged and never fails the
+ run that produced the rows it describes.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.analysis.health.ranking import deduction_by_path
+ from repowise.core.analysis.health.scoring import compute_kpis
+ from repowise.core.analysis.health.trends import snapshot_fields
+ from repowise.core.persistence.crud import get_hotspot_file_paths, save_health_snapshot
+ from repowise.core.persistence.models import HealthFileMetric, HealthFinding
+
+ try:
+ metrics = list(
+ (
+ await session.execute(
+ select(HealthFileMetric).where(HealthFileMetric.repository_id == repo_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ if not metrics:
+ return
+ findings = list(
+ (
+ await session.execute(
+ select(HealthFinding).where(
+ HealthFinding.repository_id == repo_id,
+ HealthFinding.status == "open",
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ kpis = compute_kpis(
+ metrics,
+ await get_hotspot_file_paths(session, repo_id),
+ deductions=deduction_by_path(findings),
+ )
+ fields = snapshot_fields(kpis, metrics, findings)
+ if fields is not None:
+ await save_health_snapshot(session, repo_id, **fields)
+ except Exception as exc:
+ logger.warning("health_snapshot_skipped", error=str(exc))
+
+
+async def save_full_health_report(
+ session: Any,
+ repo_id: str,
+ health_report: Any,
+ *,
+ analyzed_commit: str | None,
+ repo_path: Any = None,
+) -> None:
+ """Full-replace a repository's health rows and everything derived from them.
+
+ Both callers that re-score every file land here: the analysis phase of an
+ index, and the update command's periodic/config-triggered re-score. The
+ metrics, the findings, the non-performance refactoring suggestions and the
+ two materialized read models move together, so a re-score cannot leave the
+ queues describing findings that were deleted out from under them.
+
+ ``analyzed_commit`` stamps the metric rows and the read models with the
+ commit these scores were computed against; ``None`` reads as "not
+ recorded", which is honest, while a wrong sha would not be. ``repo_path``
+ lets a plan whose file is gone read as deleted.
+ """
+ from repowise.core.persistence.crud import (
+ PayoffContext,
+ finalize_performance_opportunities,
+ finalize_refactoring_opportunities,
+ save_health_findings,
+ save_health_metrics,
+ save_refactoring_suggestions,
+ write_function_facts,
+ )
+
+ hr = health_report
+ metrics = list(getattr(hr, "metrics", None) or [])
+ findings = list(getattr(hr, "findings", None) or [])
+ if not metrics and not findings:
+ # A pass that scored nothing is a broken pass, not a clean repository.
+ # Every write below replaces the repository's rows wholesale, so
+ # honouring an empty report would delete every metric, resolve every
+ # open plan a person has triaged, and empty both queues on the strength
+ # of a parse failure or an exclude pattern that matched everything.
+ return
+ await save_health_metrics(session, repo_id, metrics, analyzed_commit=analyzed_commit)
+ # One savepoint over the findings and everything derived from them, so a
+ # rebuild that failed halfway cannot leave the queue describing findings
+ # that were never stored. It runs on an empty finding set too: the queue
+ # has to be reconciled to nothing just the same.
+ async with session.begin_nested():
+ if findings:
+ await save_health_findings(session, repo_id, findings)
+ # Structured refactoring suggestions (Extract Class, ...). Repo-wide
+ # reconciliation: an unchanged plan keeps its id and its triage state,
+ # and one nobody detects any more resolves rather than disappearing.
+ # Performance plans are excluded: the finalizer below owns them, so
+ # they are generated once, from the merged stored findings, by the same
+ # writer on every path.
+ await save_refactoring_suggestions(
+ session,
+ repo_id,
+ [
+ suggestion
+ for suggestion in (getattr(hr, "refactoring_suggestions", None) or [])
+ if getattr(suggestion, "refactoring_type", None) != "performance_fix"
+ ],
+ # Before the facts below replace the stored ones: those are the
+ # measures a resolved plan was detected against.
+ payoff=PayoffContext(
+ fact_rows=getattr(hr, "function_facts", None),
+ is_live=path_liveness(repo_path),
+ commit=analyzed_commit,
+ ),
+ )
+ # No rows means no graph to key them on: the stored ones stay. Before
+ # the finalizers, which read each plan's nearest tests off these rows.
+ fact_rows = getattr(hr, "function_facts", None)
+ if fact_rows is not None:
+ await write_function_facts(
+ session,
+ repo_id,
+ fact_rows,
+ roles=getattr(hr, "execution_roles", None),
+ tests=getattr(hr, "function_tests", None),
+ )
+ # Group the stored performance findings into the materialized causal
+ # read model, then reconcile lifecycle and plans.
+ await finalize_performance_opportunities(
+ session,
+ repo_id,
+ analyzed_commit=analyzed_commit,
+ plan_policy=getattr(hr, "performance_plan_policy", None),
+ execution_roles=getattr(hr, "execution_roles", None),
+ )
+ # Fold the plans just written into per-file opportunities. Last in the
+ # savepoint because it composes over the stored rows, so it has to see
+ # the reconciliation above rather than the detector output.
+ await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)
+
+
+async def refresh_governance_findings(
+ session: Any, repo_id: str, *, recompose_queue: bool = True
+) -> int:
+ """Rebuild the governance findings from the stored decisions and health rows.
+
+ Every writer that runs the governance pass comes through here: the index
+ after its decisions are stored, the update after its decision steps, and
+ the full health re-score, whose findings replace deletes these rows along
+ with every other open finding. Returns the number of findings written.
+
+ ``recompose_queue`` re-folds the refactoring queue when findings were
+ written, since it is composed over the stored findings and may have been
+ built before these rows existed. Only that queue: the performance
+ finalizer reads ``performance`` findings, and every governance biomarker
+ is ``organizational``. A caller that finalizes the queue next anyway
+ passes ``False``.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.analysis.health.governance import build_governance_findings
+ from repowise.core.persistence.crud import (
+ finalize_refactoring_opportunities,
+ get_decision_health_summary,
+ get_scored_file_paths,
+ replace_governance_findings,
+ )
+ from repowise.core.persistence.models import DecisionRecord
+
+ # One savepoint: the replace deletes before it inserts, and the queue
+ # reconciles as a whole, so a failure must leave neither half-written.
+ async with session.begin_nested():
+ decisions = list(
+ (
+ await session.execute(
+ select(DecisionRecord).where(DecisionRecord.repository_id == repo_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ findings = build_governance_findings(
+ health_summary=await get_decision_health_summary(session, repo_id),
+ decisions=decisions,
+ scored_paths=await get_scored_file_paths(session, repo_id),
+ )
+ await replace_governance_findings(session, repo_id, findings)
+ if findings and recompose_queue:
+ await finalize_refactoring_opportunities(
+ session, repo_id, analyzed_commit=await _persist._analyzed_commit(session, repo_id)
+ )
+ if findings:
+ logger.info("governance_findings_persisted", repo_id=repo_id, count=len(findings))
+ return len(findings)
diff --git a/packages/core/src/repowise/core/pipeline/persist/ingestion.py b/packages/core/src/repowise/core/pipeline/persist/ingestion.py
new file mode 100644
index 000000000..8eb6c879c
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/ingestion.py
@@ -0,0 +1,95 @@
+"""Ingestion-phase persistence: files, symbols, graph and edges."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+# Patchable steps are looked up on the package at call time, so a patch on
+# ``repowise.core.pipeline.persist`` reaches this module too.
+from repowise.core.pipeline import persist as _persist
+
+from .graph import _edge_row, has_graph_edges, stamp_edges_parser_fingerprint
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
+ """Persist ingestion-phase outputs: graph nodes/edges, external systems,
+ symbols, and the per-file security scan.
+
+ Every write here is an idempotent UPSERT keyed by ``(repo_id, …)``, so
+ this is safe to call incrementally (per phase) and to re-run on resume.
+
+ Returns the number of symbols written (for the summary log). Mutates
+ ``sym.file_path`` on symbols that lack one — callers should treat the
+ parsed-file symbols as consumed after this call.
+ """
+ from repowise.core.persistence import (
+ batch_upsert_graph_edges,
+ batch_upsert_symbols,
+ bulk_upsert_external_systems,
+ link_graph_nodes_to_external_systems,
+ )
+
+ # ---- Graph nodes ---------------------------------------------------------
+ # Prefer the full candidate-score map (all scored entry points), falling
+ # back to deriving from the builder when no report rode along on the
+ # result. Passing ``None`` lets persist_graph_nodes derive them itself.
+ report = result.execution_flow_report
+ ep_scores: dict[str, float] | None
+ if report is not None and getattr(report, "entry_point_scores", None):
+ ep_scores = dict(report.entry_point_scores)
+ elif report is not None and getattr(report, "flows", None):
+ ep_scores = {
+ f.entry_point_id: f.entry_point_score
+ for f in report.flows
+ if hasattr(f, "entry_point_id") and hasattr(f, "entry_point_score")
+ }
+ else:
+ ep_scores = None
+ await _persist.persist_graph_nodes(session, repo_id, result.graph_builder, ep_scores)
+
+ # ---- Graph edges ---------------------------------------------------------
+ graph = result.graph_builder.graph()
+ edges = [_edge_row(u, v, data) for u, v, data in graph.edges(data=True)]
+ fresh_store = not await has_graph_edges(session, repo_id)
+ if edges:
+ await batch_upsert_graph_edges(session, repo_id, edges)
+ if fresh_store:
+ from repowise.core.ingestion.parse_cache import parser_fingerprint
+
+ await stamp_edges_parser_fingerprint(session, repo_id, parser_fingerprint())
+
+ # ---- External systems (C4 L1) -------------------------------------------
+ # Persist before symbols so the FK linkage step below sees the IDs.
+ external_systems = getattr(result, "external_systems", None) or []
+ if external_systems:
+ id_map = await bulk_upsert_external_systems(session, repo_id, external_systems)
+ from repowise.core.persistence.crud import build_external_system_link_map
+
+ name_to_id = build_external_system_link_map(external_systems, id_map)
+ await link_graph_nodes_to_external_systems(session, repo_id, name_to_id)
+
+ # ---- Symbols -------------------------------------------------------------
+ # NOTE: This mutates sym.file_path on the caller's PipelineResult objects.
+ # The guard prevents double-set on retries, but callers should treat the
+ # result as consumed after this call.
+ all_symbols = []
+ for pf in result.parsed_files:
+ for sym in pf.symbols:
+ if not getattr(sym, "file_path", None):
+ sym.file_path = pf.file_info.path
+ all_symbols.append(sym)
+ if all_symbols:
+ await batch_upsert_symbols(session, repo_id, all_symbols)
+
+ # ---- Security scan -------------------------------------------------------
+ # Best-effort — never breaks the rest of the phase.
+ try:
+ await _persist.persist_security_findings(result, session, repo_id)
+ except Exception as _sec_err:
+ logger.warning("security_scan_skipped", error=str(_sec_err))
+
+ return len(all_symbols)
diff --git a/packages/core/src/repowise/core/pipeline/persist/prune.py b/packages/core/src/repowise/core/pipeline/persist/prune.py
new file mode 100644
index 000000000..ccffba53d
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/prune.py
@@ -0,0 +1,431 @@
+"""Pruning of rows for files that left the repository or the index scope."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+# Patchable steps are looked up on the package at call time, so a patch on
+# ``repowise.core.pipeline.persist`` reaches this module too.
+from repowise.core.pipeline import persist as _persist
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+# Chunk size for IN (...) deletes — stays under SQLite's host-parameter limit.
+_PRUNE_CHUNK = 500
+
+
+async def _prune_stale_file_rows(
+ session: Any,
+ repo_id: str,
+ current_graph_file_paths: set[str],
+ current_git_file_paths: set[str],
+ *,
+ authoritative_empty: bool = False,
+) -> None:
+ """Delete file-scoped rows for files absent from the latest full pipeline run.
+
+ The parser and git indexer disagree on the file set — a file can be
+ git-tracked yet absent from ``parsed_files`` (parse failure, unparsed
+ extension, skipped) — so the tables use different sources of truth.
+ *current_graph_file_paths* (from ``parsed_files``) governs graph/analysis
+ tables; *current_git_file_paths* (from ``git_metadata_list``) governs
+ ``git_metadata`` only. Each set independently no-ops when empty to avoid
+ wiping rows on a broken run, unless ``authoritative_empty`` confirms that a
+ successful full traversal really produced an empty scope.
+
+ Full runs only. The authority here is "absent from this run's output",
+ which is only safe because a full run rebuilds every table it prunes from
+ in the same transaction. Incremental runs use
+ :func:`prune_deleted_file_rows`, whose authority is the filesystem and git
+ rather than the parse — see its docstring for why the two differ.
+ """
+ from sqlalchemy import delete, or_, select
+
+ from repowise.core.persistence.models import (
+ CoverageFile,
+ DeadCodeFinding,
+ GitFunctionBlame,
+ GitMetadata,
+ GraphEdge,
+ GraphMetric,
+ GraphNode,
+ HealthFileMetric,
+ HealthFinding,
+ SecurityFinding,
+ WikiSymbol,
+ )
+
+ async def _delete_stale_by_paths(
+ model: Any,
+ column: Any,
+ current: set[str],
+ *,
+ allow_empty: bool | None = None,
+ ) -> None:
+ # Diff persisted paths against *current* in Python so the IN (...) is
+ # bounded by the stale set, not the whole repo (SQLite param limit).
+ empty_is_authoritative = authoritative_empty if allow_empty is None else allow_empty
+ if not current and not empty_is_authoritative:
+ return
+ existing = set(
+ (await session.execute(select(column).where(model.repository_id == repo_id).distinct()))
+ .scalars()
+ .all()
+ )
+ stale = [p for p in existing if p not in current]
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ await session.execute(
+ delete(model).where(
+ model.repository_id == repo_id,
+ column.in_(stale[i : i + _PRUNE_CHUNK]),
+ )
+ )
+
+ # ---- Graph nodes + edges -------------------------------------------------
+ # File nodes key on node_id; symbol nodes on file_path. Delete edges before
+ # nodes (no FK cascade between the tables).
+ if current_graph_file_paths or authoritative_empty:
+ node_rows = (
+ await session.execute(
+ select(GraphNode.node_id, GraphNode.node_type, GraphNode.file_path).where(
+ GraphNode.repository_id == repo_id
+ )
+ )
+ ).all()
+ stale_node_ids = [
+ node_id
+ for node_id, node_type, file_path in node_rows
+ if (node_type == "file" and node_id not in current_graph_file_paths)
+ or (
+ node_type != "file"
+ and file_path is not None
+ and file_path not in current_graph_file_paths
+ )
+ ]
+ for i in range(0, len(stale_node_ids), _PRUNE_CHUNK):
+ batch = stale_node_ids[i : i + _PRUNE_CHUNK]
+ await session.execute(
+ delete(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ or_(
+ GraphEdge.source_node_id.in_(batch),
+ GraphEdge.target_node_id.in_(batch),
+ ),
+ )
+ )
+ await session.execute(
+ delete(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_id.in_(batch),
+ )
+ )
+
+ # GraphMetric is file-level only (node_id == path).
+ await _delete_stale_by_paths(GraphMetric, GraphMetric.node_id, current_graph_file_paths)
+ await _delete_stale_by_paths(WikiSymbol, WikiSymbol.file_path, current_graph_file_paths)
+ await _delete_stale_by_paths(
+ SecurityFinding, SecurityFinding.file_path, current_graph_file_paths
+ )
+ await _delete_stale_by_paths(
+ DeadCodeFinding, DeadCodeFinding.file_path, current_graph_file_paths
+ )
+ await _delete_stale_by_paths(
+ HealthFileMetric, HealthFileMetric.file_path, current_graph_file_paths
+ )
+ await _delete_stale_by_paths(HealthFinding, HealthFinding.file_path, current_graph_file_paths)
+ await _delete_stale_by_paths(CoverageFile, CoverageFile.file_path, current_graph_file_paths)
+ await _delete_stale_by_paths(
+ GitFunctionBlame, GitFunctionBlame.file_path, current_graph_file_paths
+ )
+ await _delete_stale_by_paths(
+ GitMetadata,
+ GitMetadata.file_path,
+ current_git_file_paths,
+ # An empty Git result is authoritative only when the successful source
+ # traversal is empty too. Otherwise it may be a degraded Git walk.
+ allow_empty=authoritative_empty and not current_graph_file_paths,
+ )
+
+
+# A prune that would take more than this share of a table is read as a broken
+# run rather than a large commit, and refused. The asymmetry is the whole
+# argument: refusing leaves stale rows, which are visible in the UI and cleared
+# by a reindex, where proceeding deletes live ones, which are invisible until
+# someone notices the symbol is missing.
+_PRUNE_MAX_FRACTION = 0.5
+# ...but a small repo can legitimately lose half its files in one commit, so the
+# fraction only applies once the *deletion* is big enough for the ratio to mean
+# something. Measured on the deletion rather than the table so that a 25-row
+# store losing 20 rows still prunes: at that size "most of it went" is an
+# ordinary commit, not evidence of a broken run.
+_PRUNE_FLOOR_MIN_ROWS = 20
+
+
+def _git_tracked_paths(root: Path) -> frozenset[str]:
+ """Every path git tracks at HEAD, POSIX-relative, or an empty set on failure.
+
+ Empty is indistinguishable from "git failed" on purpose: both mean this
+ witness has nothing to say, and the caller treats silence as "no opinion"
+ rather than as "nothing is tracked".
+ """
+ from repowise.core.git_refs import tracked_paths
+
+ return tracked_paths(str(root))
+
+
+class _FileLiveness:
+ """Is this path still a real file, judged without consulting this run's parser.
+
+ Two witnesses, neither of which is the parse: the file is present on disk,
+ or git still tracks it. A path has to fail both to count as deleted.
+
+ That split is the point. Deriving deletions from ``parsed_files`` alone
+ makes every transient read or parse failure look like a deletion, and on
+ Windows a file lock or an antivirus scan produces exactly that: the file is
+ there, the run could not read it, and the naive prune deletes its rows.
+ The disk check answers for that case; git covers the narrower one where the
+ stat itself fails (``Path.exists()`` reports False on a permission error).
+
+ The deliberate cost of taking the union: a file that a config change has
+ newly *excluded* still exists and is still tracked, so its rows survive an
+ incremental update. That matches the behaviour before this guard existed
+ (which pruned nothing at all on this path), and a full reindex still clears
+ it, so nothing regresses.
+
+ ``git ls-files`` is spawned lazily, on the first path that is not on disk,
+ so an update with no deletions never pays for it.
+ """
+
+ def __init__(self, repo_path: Any) -> None:
+ self._root = Path(repo_path)
+ self._tracked: frozenset[str] | None = None
+ # The same path is asked about once per table it has rows in, and a
+ # stat under an antivirus scanner is not free.
+ self._memo: dict[str, bool] = {}
+
+ def is_live(self, path: str) -> bool:
+ answer = self._memo.get(path)
+ if answer is None:
+ answer = self._is_live(path)
+ self._memo[path] = answer
+ return answer
+
+ def _is_live(self, path: str) -> bool:
+ if (self._root / path).exists():
+ return True
+ if self._tracked is None:
+ self._tracked = _git_tracked_paths(self._root)
+ return path in self._tracked
+
+
+def path_liveness(repo_path: Any) -> Callable[[str], bool] | None:
+ """Whether a repo-relative path is still on disk or tracked by git; ``None``
+ without a checkout to ask, so no caller reads a path as deleted on no evidence."""
+ return _FileLiveness(repo_path).is_live if repo_path else None
+
+
+async def _resolve_plans_of_deleted_files(
+ session: Any, repo_id: str, dead: Callable[[set[str], str], list[str]], liveness: Any
+) -> None:
+ from sqlalchemy import select
+
+ from repowise.core.persistence.crud import PayoffContext, upsert_refactoring_suggestions
+ from repowise.core.persistence.models import RefactoringSuggestion
+
+ live_plan_paths = await session.execute(
+ select(RefactoringSuggestion.file_path)
+ .where(
+ RefactoringSuggestion.repository_id == repo_id,
+ RefactoringSuggestion.status.in_(("open", "acknowledged")),
+ )
+ .distinct()
+ )
+ gone = dead(set(live_plan_paths.scalars().all()), "refactoring_suggestions")
+ if gone:
+ payoff = PayoffContext(
+ fact_rows=None,
+ is_live=liveness.is_live,
+ commit=await _persist._analyzed_commit(session, repo_id),
+ )
+ await upsert_refactoring_suggestions(session, repo_id, [], file_paths=gone, payoff=payoff)
+
+
+async def prune_deleted_file_rows(
+ session: Any,
+ repo_id: str,
+ repo_path: Any,
+ *,
+ live_hint: set[str] | None = None,
+) -> tuple[int, list[str]]:
+ """Delete file-scoped rows for files that are gone, on an incremental update.
+
+ The incremental path never pruned anything: deleting a file tombstoned its
+ wiki page and left its graph nodes, edges, metrics, symbols, health rows and
+ git metadata behind, so MCP, search and every health aggregate kept counting
+ a file that no longer exists until someone ran a full reindex.
+
+ The authority is deliberately *not* the one :func:`_prune_stale_file_rows`
+ uses. A full run rebuilds every table it prunes from, so "absent from this
+ run's output" is a safe question there. An incremental run rebuilds nothing:
+ a row deleted here is not rewritten, so the question has to be "is the file
+ gone", answered by :class:`_FileLiveness` from the filesystem and git rather
+ than from the parse. They differ exactly in the transient-failure case, and
+ that case is the one that loses data.
+
+ *live_hint* is what this run already knows to be live: the paths that
+ parsed, plus every file node the rebuilt graph holds. The first half is
+ purely an optimisation, since anything in it would pass the liveness test
+ anyway and the stat is skipped. The second half is load-bearing: a node
+ like ``external:...`` or Spring's ``META-INF/services/<iface>`` names no
+ file, so it fails every liveness test there is, and only the fact that the
+ graph build just re-minted it says it is not a deletion.
+
+ Returns ``(deleted_path_count, refusals)``, where a refusal is a one-line
+ explanation of a floor guard that fired, for the caller's degraded report.
+ """
+ from sqlalchemy import delete, or_, select
+
+ # Not every ``node_type == "file"`` row names a file. ``external:`` and
+ # ``framework:`` nodes are minted for third-party imports and for
+ # convention-based loading, they are stored as file nodes, and they answer
+ # "no" to every liveness question there is because no such file was ever
+ # meant to exist. Without this they read as a mass deletion: 223 of hugo's
+ # 2,356 file nodes, 590 of react's 3,353, and 70% of spring-petclinic's,
+ # which is past the floor guard and would have been reported as a refusal
+ # rather than as the bug it is.
+ #
+ # Imported rather than re-listed: a prefix added to one copy and not the
+ # other is exactly the bug above. Costs nothing on this path, where the
+ # partial dead-code analysis has already loaded the module (13.7 ms when
+ # it has not, measured cold after the CLI modules are up).
+ from repowise.core.analysis.dead_code.analyzer import _is_synthetic_node
+ from repowise.core.persistence.crud.analysis.function_facts import delete_file_rows
+ from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ DocDriftFinding,
+ DocDriftReference,
+ GitMetadata,
+ GraphEdge,
+ GraphMetric,
+ GraphNode,
+ HealthFileMetric,
+ HealthFinding,
+ SecurityFinding,
+ WikiSymbol,
+ )
+
+ hint = live_hint or set()
+ liveness = _FileLiveness(repo_path)
+ refusals: list[str] = []
+ deleted: set[str] = set()
+
+ def _dead(persisted: set[str], label: str) -> list[str]:
+ """Paths in *persisted* that no longer exist, or [] if the floor fired."""
+ persisted = {p for p in persisted if not _is_synthetic_node(p)}
+ dead = [p for p in persisted if p not in hint and not liveness.is_live(p)]
+ if (
+ len(dead) > _PRUNE_FLOOR_MIN_ROWS
+ and persisted
+ and len(dead) > _PRUNE_MAX_FRACTION * len(persisted)
+ ):
+ refusals.append(
+ f"Deleted-file prune refused for {label}: {len(dead)} of "
+ f"{len(persisted)} paths looked deleted, which reads as a broken "
+ "run rather than a commit. Run a full reindex to clear them."
+ )
+ return []
+ deleted.update(dead)
+ return dead
+
+ async def _prune_table(model: Any, column: Any, label: str) -> None:
+ persisted = set(
+ (await session.execute(select(column).where(model.repository_id == repo_id).distinct()))
+ .scalars()
+ .all()
+ )
+ persisted.discard(None)
+ dead = _dead(persisted, label)
+ for i in range(0, len(dead), _PRUNE_CHUNK):
+ await session.execute(
+ delete(model).where(
+ model.repository_id == repo_id,
+ column.in_(dead[i : i + _PRUNE_CHUNK]),
+ )
+ )
+
+ # ---- Graph nodes + edges -------------------------------------------------
+ # File nodes key on node_id, symbol nodes on file_path, and edges have no FK
+ # cascade from either, so edges go first.
+ node_rows = (
+ await session.execute(
+ select(GraphNode.node_id, GraphNode.node_type, GraphNode.file_path).where(
+ GraphNode.repository_id == repo_id
+ )
+ )
+ ).all()
+ node_paths = {
+ (node_id if node_type == "file" else file_path)
+ for node_id, node_type, file_path in node_rows
+ if node_type == "file" or file_path
+ }
+ dead_paths = set(_dead(node_paths, "graph_nodes"))
+ if dead_paths:
+ stale_node_ids = [
+ node_id
+ for node_id, node_type, file_path in node_rows
+ if (node_id if node_type == "file" else file_path) in dead_paths
+ ]
+ for i in range(0, len(stale_node_ids), _PRUNE_CHUNK):
+ batch = stale_node_ids[i : i + _PRUNE_CHUNK]
+ await session.execute(
+ delete(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ or_(
+ GraphEdge.source_node_id.in_(batch),
+ GraphEdge.target_node_id.in_(batch),
+ ),
+ )
+ )
+ await session.execute(
+ delete(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_id.in_(batch),
+ )
+ )
+
+ await _prune_table(GraphMetric, GraphMetric.node_id, "graph_metrics")
+ await _prune_table(WikiSymbol, WikiSymbol.file_path, "wiki_symbols")
+ await _prune_table(SecurityFinding, SecurityFinding.file_path, "security_findings")
+ await _prune_table(DeadCodeFinding, DeadCodeFinding.file_path, "dead_code_findings")
+ # Plans are resolved, not deleted, so a held id keeps answering. A scoped
+ # run never names a deleted file (or a renamed file's old path) again, so
+ # this is the one place they resolve. Before the facts below go: those are
+ # the target's measures the payoff keeps.
+ await _resolve_plans_of_deleted_files(session, repo_id, _dead, liveness)
+ # Keyed on the symbol: a deleted file's rows are one key range of the id.
+ await delete_file_rows(session, repo_id, dead_paths)
+ # Keyed on the DOCUMENT. The incremental drift pass scopes its write to the
+ # documents it read, so a deleted one is never in scope and its rows would
+ # outlive the file without this. ``_FileLiveness`` asks disk and
+ # ``git ls-files`` rather than the parse, so a ``.md`` path is judged
+ # correctly here.
+ await _prune_table(DocDriftFinding, DocDriftFinding.file_path, "doc_drift_findings")
+ # On the document only. A reference to a deleted *target* is drift, not a
+ # dead row: the next pass re-resolves it into a finding, and pruning by
+ # target here would delete the evidence before anything reported it.
+ await _prune_table(
+ DocDriftReference, DocDriftReference.document_path, "doc_drift_references"
+ )
+ await _prune_table(HealthFileMetric, HealthFileMetric.file_path, "health_file_metrics")
+ await _prune_table(HealthFinding, HealthFinding.file_path, "health_findings")
+ # git_metadata is keyed off the git indexer on a full run, but an
+ # incremental run only indexes the changed files, so the same liveness
+ # question is the only authority available here too.
+ await _prune_table(GitMetadata, GitMetadata.file_path, "git_metadata")
+
+ return len(deleted), refusals
diff --git a/packages/core/src/repowise/core/pipeline/persist/security.py b/packages/core/src/repowise/core/pipeline/persist/security.py
new file mode 100644
index 000000000..c1b050146
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/security.py
@@ -0,0 +1,53 @@
+"""Security finding writers."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+async def persist_security_findings(result: Any, session: Any, repo_id: str) -> None:
+ """Scan every parsed file's source and replace its security findings.
+
+ Source bytes come from ``result.source_map`` (ingestion read them once);
+ ``FileInfo`` itself carries no content, only ``content_hash``, so reading
+ it off ``file_info`` yields empty text and a scan that can never fire.
+ Resume views without a ``source_map`` degrade to the symbol-name scan.
+ """
+ source_map = getattr(result, "source_map", None) or {}
+ await _replace_security_findings(session, repo_id, result.parsed_files, source_map)
+
+
+async def persist_incremental_security_findings(
+ session: Any,
+ repo_id: str,
+ parsed_files: list[Any] | None,
+ source_map: dict[str, Any] | None,
+ changed_paths: list[str],
+) -> None:
+ """Rescan the changed and added files' working-tree security findings.
+
+ Without this, update kept every finding from the last full index: new
+ secrets in changed files were missed and old rows pointed at moved lines.
+ Deleted files are dropped by ``prune_deleted_file_rows``. No source map
+ means no text to scan, and scanning empty text would wipe real findings,
+ so that case is a no-op.
+ """
+ if not parsed_files or not source_map:
+ return
+ changed = set(changed_paths)
+ targets = [pf for pf in parsed_files if pf.file_info.path in changed]
+ if targets:
+ await _replace_security_findings(session, repo_id, targets, source_map)
+
+
+async def _replace_security_findings(
+ session: Any, repo_id: str, parsed_files: Any, source_map: dict[str, Any]
+) -> None:
+ from repowise.core.analysis.security_scan import SecurityScanner, scan_source_map
+
+ findings_by_file, scanned_paths = scan_source_map(parsed_files, source_map)
+ await SecurityScanner(session, repo_id).replace_findings(findings_by_file, scanned_paths)
diff --git a/packages/core/src/repowise/core/pipeline/persist/sweeps.py b/packages/core/src/repowise/core/pipeline/persist/sweeps.py
new file mode 100644
index 000000000..f952f89ac
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/sweeps.py
@@ -0,0 +1,420 @@
+"""Sweeps of generated pages a run no longer produces."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import structlog
+
+from repowise.core.generation.models import (
+ STRUCTURALLY_KEYED_PAGE_TYPES,
+ STUB_FALLBACK_ERROR,
+)
+
+from .prune import _PRUNE_CHUNK
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+# Generated page types keyed on run-scoped structure: module/scc pages on
+# clustering ordinals, layer pages on display names. Those keys shift between
+# runs, so re-runs mint fresh page ids and the previous rows linger as
+# duplicates unless swept against the current run's output.
+#
+# Same list generation stamps ``structural_key`` from, imported rather than
+# repeated: a type present in one and missing from the other is exactly the
+# bug the sweep exists to prevent.
+_SWEPT_GENERATED_PAGE_TYPES = STRUCTURALLY_KEYED_PAGE_TYPES
+
+
+async def sweep_retired_pages(session: Any, repo_id: str) -> list[str]:
+ """Delete every row of a page that no longer exists, by type or by id.
+
+ Distinct from the two sweeps below, and simpler than either: those ask what
+ *this* run produced, because a page of a live type may legitimately be
+ absent from a scoped run. A retired page has no legitimate rows at all —
+ nothing emits one and no failure mode can make anything emit one — so the
+ question never arises and this is safe on every path, full or scoped.
+
+ The retirement tables are the source of truth rather than a list repeated
+ here. A page is retired exactly when a reader following its id gets sent
+ somewhere else, and that is what those tables say; keeping a second list
+ would let a page be redirected without being swept, which is the state this
+ function was written to clear.
+
+ That state is the reason this exists. The architecture diagram merged into
+ the overview and layer pages became grouping rows in the tree, both with
+ redirects registered — but ``architecture_diagram`` is not structurally
+ keyed, so no sweep ever covered it, and ``layer_page`` was only swept by a
+ full run. An index that has only been updated incrementally since therefore
+ still serves both. On this repository the retired diagram was the
+ second-ranked retrieval hit for "how does the ingestion pipeline work",
+ competing with the overview it had been merged into.
+
+ Retirement by *id* is the second half of the same argument, and the reason
+ this is no longer named for types. Three orientation slots retired out of
+ the onboarding collection while five stayed, so their rows cannot be
+ reached by page type: ``onboarding`` still has legitimate rows and always
+ will. Sweeping the exact ids is the only way those leave a store, and the
+ safety argument is unchanged — a retired id names a page nothing emits.
+
+ Returns the swept page ids so the caller can drop them from the vector
+ store and from FTS. A row deleted here but left in either of those is worse
+ than one never swept: search still answers from the FTS copy, with the full
+ title and snippet of a page the reader can no longer open.
+ """
+ from sqlalchemy import delete, or_, select
+
+ from repowise.core.generation.page_redirects import (
+ RETIRED_IDS,
+ SUPERSEDED_TO_REPO_WIDE,
+ SUPERSEDED_TYPES,
+ )
+ from repowise.core.persistence.models import Page, PageVersion
+
+ retired_types = sorted(set(SUPERSEDED_TYPES) | set(SUPERSEDED_TO_REPO_WIDE))
+ retired_ids = sorted(RETIRED_IDS)
+ if not retired_types and not retired_ids:
+ return []
+
+ # Either rule can match, and a page matched by both is one row either way.
+ match_clauses = []
+ if retired_types:
+ match_clauses.append(Page.page_type.in_(retired_types))
+ if retired_ids:
+ match_clauses.append(Page.id.in_(retired_ids))
+
+ stale = (
+ (
+ await session.execute(
+ select(Page.id).where(Page.repository_id == repo_id, or_(*match_clauses))
+ )
+ )
+ .scalars()
+ .all()
+ )
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
+ await session.execute(delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch)))
+ if stale:
+ logger.info(
+ "retired_pages_swept",
+ repo_id=repo_id,
+ count=len(stale),
+ types=retired_types,
+ ids=retired_ids,
+ )
+ return list(stale)
+
+
+async def _sweep_stale_generated_pages(
+ session: Any,
+ repo_id: str,
+ generated_pages: list[Any] | None,
+ authoritative_page_types: set[str] | None = None,
+ preserved_page_ids: set[str] | None = None,
+) -> list[str]:
+ """Delete structurally-keyed generated pages this run did not produce.
+
+ Sweeps a page type when the run either produced at least one page of it OR
+ declared itself authoritative for it (``authoritative_page_types`` — set by
+ the generation layer when it fully decided the type, even if that decision
+ was "emit none"; e.g. a curated run whose modules all collapsed into their
+ layers via ``wholeLayer``). A type that is neither produced nor authoritative
+ is left untouched, so a skipped/failed/degraded level never wipes the last
+ good set. When authoritative-but-empty, the current set is empty and every
+ prior row of that type is retired. Page versions go with their page (FK
+ enforcement requires it, and a retired structural id never comes back to
+ claim its history). Returns the swept page ids so the caller can drop them
+ from FTS after the session closes (the FTS store must not be touched
+ in-session).
+
+ ``preserved_page_ids`` are ids a ``--resume`` run skipped *because they
+ already exist* (see ``_GenerationRun._emit``). They are absent from
+ ``generated_pages`` by design, which is exactly what "stale" means to the
+ rest of this function, so without this argument a resume that regenerated
+ the missing half of a page type deleted the half it had just protected
+ (issue #1089). A preserved id is as current as a produced one: the id did
+ not drift, which is the only thing this sweep exists to catch.
+ """
+ from sqlalchemy import delete, select
+
+ from repowise.core.persistence.models import Page, PageVersion
+
+ produced: dict[str, set[str]] = {}
+ for page in generated_pages or []:
+ produced.setdefault(page.page_type, set()).add(page.page_id)
+ authoritative = authoritative_page_types or set()
+ preserved = preserved_page_ids or set()
+
+ swept: list[str] = []
+ for page_type in _SWEPT_GENERATED_PAGE_TYPES:
+ current = produced.get(page_type)
+ if not current and page_type not in authoritative:
+ continue
+ # Preserved ids join the current set rather than being subtracted from
+ # the stale one: an authoritative type sweeps even when the run emitted
+ # none of it, and that branch must still keep what a resume stood on.
+ # (Defensive today — no caller sets both — but the two are independent
+ # inputs and the failure mode if they ever meet is a deleted wiki.)
+ # Filtered by type because ``preserved`` spans every page type while
+ # this loop compares against one. Ids happen to be ``type:target`` so
+ # a cross-type match is impossible, but the sweep is the wrong place to
+ # depend on an id format nothing here enforces.
+ prefix = f"{page_type}:"
+ current = (current or set()) | {p for p in preserved if p.startswith(prefix)}
+ existing = (
+ (
+ await session.execute(
+ select(Page.id).where(
+ Page.repository_id == repo_id, Page.page_type == page_type
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ stale = [pid for pid in existing if pid not in current]
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
+ await session.execute(
+ delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch))
+ )
+ swept.extend(stale)
+
+ if swept:
+ logger.info("stale_generated_pages_swept", repo_id=repo_id, count=len(swept))
+ return swept
+
+
+async def sweep_absent_cycle_pages(session: Any, repo_id: str, graph_builder: Any) -> list[str]:
+ """Delete ``scc_page`` rows whose cycle no longer exists in the graph.
+
+ The other sweeps ask "did this run *produce* this page?", which a scoped run
+ cannot answer: ``repowise update`` runs with ``file_pages_only`` and never
+ reaches level 3, so it emits no ``scc_page`` at all and every prior row
+ looks stale to that question. ``_sweep_stale_generated_pages`` therefore
+ gates on the run declaring itself authoritative, and only a keyless
+ (``deterministic``) run does.
+
+ Between them those two rules leave a cycle page immortal on the paths that
+ matter: an update never regenerates it, and a keyed full re-index of a repo
+ whose cycles all disappeared never claims authority to retire it. A user
+ upgrading into a build that fixes a cycle-detection bug keeps being served
+ the cycles it fixed.
+
+ This asks a different question — "does the graph still contain this cycle?"
+ — which the rebuilt graph answers directly and identically on every path,
+ with no dependence on what generation chose to emit or what budget it had.
+ A cycle's page id is a hash of its sorted members
+ (:func:`~repowise.core.generation.models.scc_page_slug`), so the current
+ cycle set names exactly the ids that may survive.
+
+ Returns the deleted page ids so the caller can drop them from FTS and the
+ vector store after the session closes.
+ """
+ from sqlalchemy import delete, select
+
+ from repowise.core.generation.models import compute_page_id, scc_page_slug
+ from repowise.core.persistence.models import Page, PageVersion
+
+ if graph_builder is None:
+ return []
+ try:
+ sccs = graph_builder.strongly_connected_components()
+ except Exception: # a released graph has no cycles to speak for
+ return []
+
+ valid = {
+ compute_page_id("scc_page", scc_page_slug(sorted(scc))) for scc in sccs if len(scc) > 1
+ }
+ existing = (
+ (
+ await session.execute(
+ select(Page.id).where(Page.repository_id == repo_id, Page.page_type == "scc_page")
+ )
+ )
+ .scalars()
+ .all()
+ )
+ stale = [pid for pid in existing if pid not in valid]
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
+ await session.execute(delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch)))
+ if stale:
+ logger.info("absent_cycle_pages_swept", repo_id=repo_id, count=len(stale))
+ return stale
+
+
+def _symbol_names_by_file(graph_builder: Any) -> dict[str, set[str]]:
+ """``file path -> names of the symbols it defines`` in the rebuilt graph.
+
+ Empty when there is no graph to ask. The synthetic ``__module__`` symbol is
+ left out, so a file that failed to parse has no entry at all.
+ """
+ if graph_builder is None:
+ return {}
+ try:
+ graph = graph_builder.graph()
+ except Exception: # a released graph cannot speak for any symbol
+ return {}
+ names_by_file: dict[str, set[str]] = {}
+ for _node, data in graph.nodes(data=True):
+ if data.get("node_type") != "symbol" or data.get("kind") == "module":
+ continue
+ path, name = data.get("file_path"), data.get("name")
+ if path and name:
+ names_by_file.setdefault(path, set()).add(name)
+ return names_by_file
+
+
+async def sweep_absent_symbol_spotlights(
+ session: Any, repo_id: str, graph_builder: Any
+) -> list[str]:
+ """Delete ``symbol_spotlight`` rows whose symbol left a file that still exists.
+
+ A spotlight targets ``<path>::<name>``. Deleting the file tombstones it
+ (:func:`mark_tombstone_pages`), but moving or removing the symbol while the
+ file stays left the row ``fresh``: nothing regenerates a page for a symbol
+ the parser no longer emits, so it kept serving the old body and the old
+ importer list.
+
+ Same question as :func:`sweep_absent_cycle_pages`, asked of the rebuilt
+ graph: does this file still define a symbol of that name? Only files the
+ graph holds with at least one named symbol are judged, so a file outside
+ the traversal or one that failed to parse keeps its pages.
+
+ Returns the deleted page ids so the caller can drop them from FTS and the
+ vector store after the session closes.
+ """
+ from sqlalchemy import delete, select
+
+ from repowise.core.persistence.models import Page, PageVersion
+
+ names_by_file = _symbol_names_by_file(graph_builder)
+ if not names_by_file:
+ return []
+
+ rows = (
+ await session.execute(
+ select(Page.id, Page.target_path).where(
+ Page.repository_id == repo_id,
+ Page.page_type == "symbol_spotlight",
+ Page.freshness_status != "tombstone",
+ )
+ )
+ ).all()
+ stale: list[str] = []
+ for page_id, target in rows:
+ path, sep, name = (target or "").partition("::")
+ names = names_by_file.get(path)
+ if sep and names is not None and name not in names:
+ stale.append(page_id)
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
+ await session.execute(delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch)))
+ if stale:
+ logger.info("absent_symbol_spotlights_swept", repo_id=repo_id, count=len(stale))
+ return stale
+
+
+async def sweep_superseded_generated_pages(
+ session: Any,
+ repo_id: str,
+ generated_pages: list[Any] | None,
+) -> list[str]:
+ """Retire structurally-keyed rows whose coverage a scoped run just took over.
+
+ :func:`_sweep_stale_generated_pages` cannot be used on the update path. It
+ deletes every row of a page type the run did not reproduce, which is right
+ for a full index and catastrophic for a scoped one: regenerating a single
+ page would wipe the other fifty.
+
+ That left a real gap. A structurally-keyed page's id is its
+ ``target_path``, and a page that groups files can legitimately change which
+ directory names it when its membership changes. ``repowise update`` goes
+ through ``scoped_generation`` and never swept, so the regenerated page was
+ written under its new id and the old row stayed behind as a duplicate until
+ somebody ran a full index. Harmless while module and cycle pages were never
+ regenerated incrementally, and not harmless once concept pages are.
+
+ The rule here is narrower and does not need to know what the caller asked
+ for: a prior row is superseded when **every file it covered is now covered
+ by pages this run produced**, of the same type. That is exactly the
+ condition under which the old row documents nothing that is not documented
+ elsewhere. A page that failed to generate keeps files no produced page
+ claims, so it survives — which matters, because deleting a page because its
+ generation errored would be a worse bug than the one this fixes.
+
+ Returns the swept page ids so the caller can drop them from FTS after the
+ session closes.
+ """
+ from sqlalchemy import delete, select
+
+ from repowise.core.persistence.models import Page, PageVersion
+
+ produced_ids: dict[str, set[str]] = {}
+ covered: dict[str, set[str]] = {}
+ for page in generated_pages or []:
+ page_type = page.page_type
+ if page_type not in _SWEPT_GENERATED_PAGE_TYPES:
+ continue
+ # A stub standing in for a failed provider call is the "failed to
+ # generate" case this function's contract already carves out: it claims
+ # no files, so a prior row covering them is not superseded. Counting its
+ # members would retire the very page whose regeneration just failed, and
+ # take its version history with it.
+ if STUB_FALLBACK_ERROR in (getattr(page, "metadata", None) or {}):
+ continue
+ produced_ids.setdefault(page_type, set()).add(page.page_id)
+ metadata = getattr(page, "metadata", None) or {}
+ members = metadata.get("file_paths") or metadata.get("files") or []
+ covered.setdefault(page_type, set()).update(m for m in members if isinstance(m, str))
+
+ swept: list[str] = []
+ for page_type, current in produced_ids.items():
+ union = covered.get(page_type) or set()
+ if not union:
+ # Nothing to compare against: a run that recorded no membership
+ # cannot prove it superseded anything, so it retires nothing.
+ continue
+ rows = (
+ await session.execute(
+ select(Page.id, Page.metadata_json).where(
+ Page.repository_id == repo_id, Page.page_type == page_type
+ )
+ )
+ ).all()
+ stale: list[str] = []
+ for page_id, raw in rows:
+ if page_id in current:
+ continue
+ try:
+ metadata = json.loads(raw) if isinstance(raw, str) else (raw or {})
+ except (TypeError, ValueError):
+ continue
+ if not isinstance(metadata, dict):
+ continue
+ members = metadata.get("file_paths") or metadata.get("files") or []
+ members = {m for m in members if isinstance(m, str)}
+ # No recorded membership means no proof of supersession. Those rows
+ # are the pre-membership ones (backlog B20) and they are left for a
+ # full index to retire.
+ if members and members <= union:
+ stale.append(page_id)
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
+ await session.execute(
+ delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch))
+ )
+ swept.extend(stale)
+
+ if swept:
+ logger.info("superseded_generated_pages_swept", repo_id=repo_id, count=len(swept))
+ return swept
diff --git a/packages/core/src/repowise/core/pipeline/persist/tombstones.py b/packages/core/src/repowise/core/pipeline/persist/tombstones.py
new file mode 100644
index 000000000..ecd521ba3
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/persist/tombstones.py
@@ -0,0 +1,389 @@
+"""Tombstoning and stale-marking of wiki pages whose source left the index."""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Iterable
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+# Patchable steps are looked up on the package at call time, so a patch on
+# ``repowise.core.pipeline.persist`` reaches this module too.
+from repowise.core.pipeline import persist as _persist
+
+from .prune import _prune_stale_file_rows
+
+logger = structlog.get_logger("repowise.core.pipeline.persist")
+
+
+#: Candidate paths per spotlight query: each path is one ``LIKE`` term, and
+#: SQLite caps how deep an expression tree may grow.
+_SPOTLIGHT_PATHS_PER_QUERY = 200
+
+# A second, stdlib logger for the one message here that has to survive
+# ``repowise init``. ``configure_cli_logging`` pins both ``repowise.core`` and
+# structlog to ERROR for the progress-bar commands, so anything below ERROR is
+# discarded in the exact command that writes the index. The refusal below is
+# logged through this at ERROR for that reason; the routine counts stay on
+# structlog with their siblings.
+_log = logging.getLogger("repowise.core.pipeline.persist")
+
+# Max page ids per UPDATE ... IN (...) so a large cascade cannot exceed
+# SQLite's bound-variable limit on the local CLI store.
+_STALE_ID_CHUNK = 500
+
+
+def tombstone_candidates(file_diffs: list[Any]) -> list[tuple[str, list[str]]]:
+ """(dead_path, successor_paths) pairs from deleted/renamed file diffs.
+
+ A renamed file's old path gets its new path as the successor; a deleted
+ file has no successor. Diffs of other statuses contribute nothing.
+ """
+ out: list[tuple[str, list[str]]] = []
+ for fd in file_diffs or []:
+ status = getattr(fd, "status", None)
+ if status == "deleted" and fd.path:
+ out.append((fd.path, []))
+ elif status == "renamed" and fd.old_path:
+ out.append((fd.old_path, [fd.path] if fd.path else []))
+ return out
+
+
+async def mark_tombstone_pages(
+ session: Any, repo_id: str, candidates: list[tuple[str, list[str]]]
+) -> list[str]:
+ """Mark the pages of deleted/renamed files as tombstones: each file's page
+ and the symbol spotlight pages of the symbols it defined.
+
+ A ``freshness_status="fresh"`` page for a file that no longer exists is
+ an active trap: retrieval serves it, agents cite it, and the index-age
+ metadata says nothing is wrong. Tombstoned pages keep their content
+ (the prose may still orient a reader) but carry status=tombstone and
+ ``successor_paths`` in metadata so serving layers can skip or redirect.
+
+ Returns the page ids marked, so the caller can drop them from the
+ full-text index once its session has closed. Every serving layer already
+ discards a tombstone, but retrieval fetches a fixed number of rows before
+ any of that runs, so a tombstone still takes one of those slots and pushes
+ a real candidate out of the fetch. The row has to go, and only the caller
+ knows when it is safe to write to the index — on SQLite it shares a file
+ with this session.
+ """
+ if not candidates:
+ return []
+ from sqlalchemy import or_, select
+
+ from repowise.core.persistence.models import Page
+
+ page_ids = {f"file_page:{path}": (path, successors) for path, successors in candidates}
+ pages = list(
+ (
+ await session.execute(
+ select(Page).where(Page.repository_id == repo_id, Page.id.in_(page_ids))
+ )
+ ).scalars()
+ )
+ # A symbol spotlight page targets ``<path>::<symbol>``, so its id is never
+ # ``file_page:<path>``; it goes with its file all the same. Matched on the
+ # ``<path>::`` prefix, so a file whose name merely starts with *path* stays.
+ successors_by_path = dict(candidates)
+ paths = list(successors_by_path)
+ for start in range(0, len(paths), _SPOTLIGHT_PATHS_PER_QUERY):
+ chunk = paths[start : start + _SPOTLIGHT_PATHS_PER_QUERY]
+ res = await session.execute(
+ select(Page).where(
+ Page.repository_id == repo_id,
+ Page.page_type == "symbol_spotlight",
+ or_(*(Page.target_path.startswith(f"{p}::", autoescape=True) for p in chunk)),
+ )
+ )
+ for page in res.scalars():
+ path = (page.target_path or "").split("::", 1)[0]
+ # SQLite LIKE ignores ASCII case, so ``pkg/Foo.py::`` also matches
+ # a live ``pkg/foo.py``; keep only exact path matches.
+ if path not in successors_by_path:
+ continue
+ page_ids[page.id] = (path, successors_by_path.get(path, []))
+ pages.append(page)
+ marked: list[str] = []
+ for page in pages:
+ _, successors = page_ids[page.id]
+ page.freshness_status = "tombstone"
+ try:
+ meta = json.loads(page.metadata_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+ meta["successor_paths"] = successors
+ page.metadata_json = json.dumps(meta)
+ marked.append(page.id)
+ if marked:
+ logger.info("pages_tombstoned", repo_id=repo_id, count=len(marked))
+ elif candidates:
+ # Candidates existed but no page matched — the id scheme drifted from
+ # ``file_page:{path}`` or the paths don't line up. Silent success here
+ # would let stale pages keep serving, so surface it.
+ logger.debug(
+ "tombstone_no_match",
+ repo_id=repo_id,
+ candidate_count=len(candidates),
+ sample=[p for p, _ in candidates[:3]],
+ )
+ return marked
+
+
+async def tombstone_file_pages_outside_scope(
+ session: Any, repo_id: str, current_file_paths: set[str]
+) -> list[str]:
+ """Tombstone active source-backed pages outside a full traversal's scope.
+
+ Files removed by ``exclude_patterns`` still exist on disk, so the ordinary
+ deleted-file tombstone path cannot identify them. A successful full
+ traversal can: any active file page outside its parsed-file set is no longer
+ part of this index.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Page
+
+ pages = (
+ await session.execute(
+ select(Page).where(
+ Page.repository_id == repo_id,
+ Page.page_type.in_(("file_page", "api_contract", "infra_page", "symbol_spotlight")),
+ Page.freshness_status != "tombstone",
+ )
+ )
+ ).scalars()
+ marked: list[str] = []
+ for page in pages:
+ target = page.target_path or ""
+ source_path = target.split("::", 1)[0] if page.page_type == "symbol_spotlight" else target
+ if source_path in current_file_paths:
+ continue
+ page.freshness_status = "tombstone"
+ try:
+ metadata = json.loads(page.metadata_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ metadata = {}
+ metadata["successor_paths"] = []
+ page.metadata_json = json.dumps(metadata)
+ marked.append(page.id)
+ return marked
+
+
+async def reconcile_full_index_scope(
+ session: Any,
+ repo_id: str,
+ current_graph_paths: set[str],
+ current_git_paths: set[str],
+) -> list[str]:
+ """Reconcile every source-backed store against one successful traversal."""
+ tombstoned = await tombstone_file_pages_outside_scope(session, repo_id, current_graph_paths)
+ await _prune_stale_file_rows(
+ session,
+ repo_id,
+ current_graph_paths,
+ current_git_paths,
+ authoritative_empty=True,
+ )
+ from repowise.core.persistence.crud.decisions import (
+ purge_proposed_decisions_outside_files,
+ )
+
+ await purge_proposed_decisions_outside_files(session, repo_id, current_graph_paths)
+ return tombstoned
+
+
+async def tombstone_pages_outside_generation(
+ session: Any, repo_id: str, current_page_ids: set[str]
+) -> list[str]:
+ """Retire generated pages absent from an authoritative full generation.
+
+ This is used only when generation configuration changed and the update ran
+ the complete generation ladder. It covers selection changes such as page
+ caps, spotlight ranking, and disabling onboarding, none of which imply that
+ the backing source file disappeared.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.generation.models import GENERATION_LEVELS
+ from repowise.core.persistence.models import Page
+
+ pages = (
+ await session.execute(
+ select(Page).where(
+ Page.repository_id == repo_id,
+ Page.page_type.in_(tuple(GENERATION_LEVELS)),
+ Page.freshness_status != "tombstone",
+ )
+ )
+ ).scalars()
+ marked: list[str] = []
+ for page in pages:
+ if page.id in current_page_ids:
+ continue
+ page.freshness_status = "tombstone"
+ try:
+ metadata = json.loads(page.metadata_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ metadata = {}
+ metadata["successor_paths"] = []
+ page.metadata_json = json.dumps(metadata)
+ marked.append(page.id)
+ return marked
+
+
+async def tombstone_absent_file_pages(
+ session: Any, repo_id: str, repo_path: Path | str
+) -> list[str]:
+ """Tombstone every file page whose file is no longer on disk.
+
+ :func:`mark_tombstone_pages` works from a diff, so it only ever sees a
+ file that was deleted or renamed *between two commits this run compared*.
+ ``repowise init`` compares nothing — it indexes a checkout as it stands —
+ so it has never tombstoned anything, and a page written before a file was
+ deleted keeps ``freshness_status='fresh'`` through every later index.
+
+ That page is the trap the tombstone exists to close: retrieval serves it,
+ agents cite it, and the index-age metadata says nothing is wrong.
+
+ The check is a plain existence test against the checkout rather than a
+ comparison with what this run parsed. A file can be present but unparsed —
+ an unsupported extension, a parse failure, a changed exclude list — and
+ such a file is stale, not deleted. Calling it deleted would put a
+ ``successor_paths: []`` on a page whose file a reader can still open.
+
+ Returns the page ids marked, so the caller can drop them from the
+ full-text index once its session has closed, on the same terms as
+ :func:`mark_tombstone_pages`.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Page
+
+ root = Path(repo_path)
+ res = await session.execute(
+ select(Page).where(
+ Page.repository_id == repo_id,
+ Page.page_type == "file_page",
+ Page.freshness_status != "tombstone",
+ )
+ )
+ live = list(res.scalars().all())
+ if not live:
+ return []
+
+ absent = [p for p in live if not (root / (p.target_path or "")).exists()]
+ if not absent:
+ return []
+
+ # Every page absent means the paths are not being resolved against the
+ # tree they were written from — a wrong root, a bare-repo checkout, a
+ # working copy that has not been restored yet. Tombstoning the whole wiki
+ # on that reading is worse than leaving it, and unlike a partial mistake
+ # it is not recoverable by re-indexing a file. Refuse, loudly, and let the
+ # rest of the run proceed.
+ if len(absent) == len(live):
+ _log.error(
+ "tombstone_sweep_refused repo_id=%s file_pages=%d root=%s: every file "
+ "page's path is missing from the checkout, which reads as a wrong "
+ "root rather than a deleted repository. Nothing was tombstoned.",
+ repo_id,
+ len(live),
+ root,
+ )
+ return []
+
+ marked: list[str] = []
+ for page in absent:
+ page.freshness_status = "tombstone"
+ try:
+ meta = json.loads(page.metadata_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ meta = {}
+ # Deleted, not renamed: rename detection is the diff-driven sweep's
+ # job and it has evidence this one does not.
+ meta["successor_paths"] = []
+ page.metadata_json = json.dumps(meta)
+ marked.append(page.id)
+
+ logger.info(
+ "file_pages_tombstoned_absent",
+ repo_id=repo_id,
+ count=len(marked),
+ sample=[p.target_path for p in absent[:3]],
+ )
+ return marked
+
+
+async def mark_stale_pages(session: Any, repo_id: str, paths: Iterable[str]) -> int:
+ """Decay weakly-affected file pages to ``freshness_status='stale'``.
+
+ ``ChangeDetector.get_affected_pages`` returns ``decay_only`` — pages hit
+ by the change cascade but beyond the regeneration budget (budget
+ overflow, co-change partners, 2-hop rename fallout). They keep serving
+ their existing content, but the stale bit makes the coverage view and
+ ``get_stale_pages`` truthful so the next docs run (or a reader) knows
+ they lag the code. Only ``fresh`` pages are downgraded — tombstoned or
+ already-stale pages keep their stronger status, and pages regenerated in
+ this run are never in ``decay_only`` by construction.
+
+ Maps each path to its ``file_page:<path>`` id and hands off to
+ :func:`mark_page_ids_stale`, so both entry points share one UPDATE.
+
+ The two were separate copies of the same statement, and only the sibling
+ was chunked against ``SQLITE_MAX_VARIABLE_NUMBER``. That is not a crash
+ anyone is hitting today: SQLite has defaulted to 32766 bind variables since
+ 3.32, and a ``decay_only`` set that large would take an enormous cascade.
+ It is reachable on the 999-variable builds older interpreters still ship,
+ but the reason to collapse the two is narrower than that. They answered the
+ same question differently, in the file with the most bug fixes in this repo,
+ and now there is one place to answer it.
+
+ Returns the number of pages marked.
+ """
+ return await _persist.mark_page_ids_stale(
+ session, repo_id, (f"file_page:{path}" for path in paths)
+ )
+
+
+async def mark_page_ids_stale(session: Any, repo_id: str, page_ids: Iterable[str]) -> int:
+ """Decay arbitrary pages to ``freshness_status='stale'`` by full page id.
+
+ The sibling of :func:`mark_stale_pages`, which only understands
+ ``file_page:<path>`` ids. Scoped generation's cascade needs to mark
+ dependents of every type — module, SCC, layer and the repo-wide overview /
+ architecture / onboarding pages — stale when the run regenerated a file but
+ not its summaries. Same ``fresh``-only downgrade so a tombstoned or
+ already-stale page keeps its stronger status.
+
+ Returns the number of pages marked.
+ """
+ ids = list(dict.fromkeys(page_ids)) # dedupe, preserve order
+ if not ids:
+ return 0
+ from sqlalchemy import update
+
+ from repowise.core.persistence.models import Page
+
+ # Chunk the IN list: SQLite (the local CLI store) binds one variable per id
+ # and caps at SQLITE_MAX_VARIABLE_NUMBER, so a large cascade could exceed it.
+ marked = 0
+ for i in range(0, len(ids), _STALE_ID_CHUNK):
+ batch = ids[i : i + _STALE_ID_CHUNK]
+ res = await session.execute(
+ update(Page)
+ .where(
+ Page.repository_id == repo_id,
+ Page.id.in_(batch),
+ Page.freshness_status == "fresh",
+ )
+ .values(freshness_status="stale")
+ )
+ marked += int(res.rowcount or 0)
+ if marked:
+ logger.info("pages_decayed_stale", repo_id=repo_id, count=marked)
+ return marked