Skip to content

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

fix(cli): prevent stale file_page rows from surviving repowise update (#1744) (#1906)

Kunal Singh46d32de0c2cf
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 75e3205d4..e1daf9d14 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -874,13 +874,25 @@ def run_update(
if not dry_run:
_repair_module_attribution(repo_path)
- if (
+ git_is_current = bool(
head
and head == base_ref
and not config_changed
and not renderer_changed
and not working_tree_diffs
- ):
+ )
+ # A page can be stale for a reason no commit explains: a cascade that ran
+ # out of budget, an interrupted run, an expiry. Git says nothing changed,
+ # so the shortcut below is the only place such a page could be skipped
+ # forever, and the store is asked only once the git checks would otherwise
+ # have exited, so the common case stays free of a store read.
+ stale_db_paths: list[str] = []
+ if git_is_current:
+ from repowise.core.persistence import load_stale_structural_file_paths
+
+ stale_db_paths = load_stale_structural_file_paths(repo_path)
+
+ if git_is_current and not stale_db_paths:
console.print("[green]Already up to date.[/green]")
# D7: on a template (index-only) wiki, "up to date" is true of the code
# but the pages are still unwritten. Point at the command that writes
@@ -1096,7 +1108,31 @@ def run_update(
working_tree_diffs,
)
- if not file_diffs and not config_changed and not renderer_changed:
+ # A stale page whose file is gone is a deletion the diff walk never saw
+ # (the file left in a range an earlier run did not cover, or was never
+ # committed). Re-rendering cannot clear it, so hand it to the same
+ # tombstone and prune steps a diffed deletion goes through. The pages
+ # whose files still exist stay on the regeneration list below.
+ if stale_db_paths:
+ from repowise.core.ingestion.change_detector import FileDiff
+
+ present, absent = [], []
+ for path in stale_db_paths:
+ (present if (repo_path / path).exists() else absent).append(path)
+ stale_db_paths = present
+ known = {fd.path for fd in file_diffs}
+ file_diffs = [
+ *file_diffs,
+ *(
+ FileDiff(path, "deleted", None, None, None, None)
+ for path in absent
+ if path not in known
+ ),
+ ]
+ if absent:
+ console.print(f"Stale pages for deleted files: [cyan]{len(absent)}[/cyan]")
+
+ if not file_diffs and not config_changed and not renderer_changed and not stale_db_paths:
console.print("[green]No changed files detected.[/green]")
# Always advance the sync pointer so the on-disk freshness marker stays
# current on no-op syncs. In docs mode, no changed files means no docs
@@ -1262,8 +1298,18 @@ def run_update(
stale_renderer_paths = _stale_renderer_paths(repo_path, parsed_files)
timings.stop("plan_pages")
if stale_renderer_paths:
- affected.regenerate = list(dict.fromkeys([*affected.regenerate, *stale_renderer_paths]))
console.print(f"Pages from an older renderer: [cyan]{len(stale_renderer_paths)}[/cyan]")
+ # Pages already marked stale in the store, on the same list for the same
+ # reason: nothing else re-renders a file page whose file did not change.
+ # Ceiling: a stale page for a file that exists but is no longer indexed
+ # (excluded since, or unsupported) is not in parsed_files, so the render
+ # skips it and it stays stale; it costs a full reparse on every idle run
+ # until it is retired.
+ if stale_db_paths:
+ console.print(f"Reconciling stale structural pages: [cyan]{len(stale_db_paths)}[/cyan]")
+ stale_extra = list(dict.fromkeys([*stale_renderer_paths, *stale_db_paths]))
+ if stale_extra:
+ affected.regenerate = list(dict.fromkeys([*affected.regenerate, *stale_extra]))
if affected.stale_due_to_budget > 0:
console.print(
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
index 685f30d52..7ac984f4d 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
@@ -20,6 +20,9 @@ from pathlib import Path
from typing import Any
from repowise.cli.helpers import console, run_async
+from repowise.core.persistence import (
+ load_stale_structural_file_paths as load_stale_structural_file_paths,
+)
def deterministic_embedder_name(cfg: dict) -> str:
diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.py
index 8da06a792..286fe8fb8 100644
--- a/packages/core/src/repowise/core/persistence/__init__.py
+++ b/packages/core/src/repowise/core/persistence/__init__.py
@@ -62,6 +62,7 @@ from .crud import (
get_stale_decisions,
get_stale_file_page_ages,
get_stale_pages,
+ get_stale_structural_file_paths,
get_top_entry_points,
link_graph_nodes_to_external_systems,
list_chat_messages,
@@ -72,6 +73,7 @@ from .crud import (
list_page_ids,
list_pages,
load_prior_pages,
+ load_stale_structural_file_paths,
mark_webhook_processed,
recompute_decision_staleness,
save_dead_code_findings,
@@ -258,6 +260,7 @@ __all__ = [
"get_stale_decisions",
"get_stale_file_page_ages",
"get_stale_pages",
+ "get_stale_structural_file_paths",
"get_top_entry_points",
"init_db",
"link_graph_nodes_to_external_systems",
@@ -270,6 +273,7 @@ __all__ = [
"list_page_ids",
"list_pages",
"load_prior_pages",
+ "load_stale_structural_file_paths",
"mark_webhook_processed",
"recompute_decision_staleness",
"resolve_db_url",
diff --git a/packages/core/src/repowise/core/persistence/crud/pages.py b/packages/core/src/repowise/core/persistence/crud/pages.py
index 5f157a910..05dcfd497 100644
--- a/packages/core/src/repowise/core/persistence/crud/pages.py
+++ b/packages/core/src/repowise/core/persistence/crud/pages.py
@@ -661,6 +661,110 @@ async def get_stale_pages(
return list(result.scalars().all())
+#: Page types a scoped ``update`` can re-render for one file. Every other
+#: structural type (cycle, layer, contract, infra) describes the whole
+#: repository and is only written by a full run, so a stale row of those types
+#: is not something an update can clear and must not make it think it can.
+_FILE_SCOPED_PAGE_TYPES = frozenset({"file_page", "symbol_spotlight"})
+
+
+async def get_stale_structural_file_paths(
+ session: AsyncSession,
+ repository_id: str,
+) -> list[str]:
+ """File paths whose file-scoped pages are marked ``stale`` or ``expired``.
+
+ Covers ``file_page`` rows (``target_path`` is the file) and
+ ``symbol_spotlight`` rows (``target_path`` is ``<file>::<symbol>``), which
+ are the two page kinds a scoped ``update`` re-renders for a file. The
+ caller feeds these paths into the same regeneration list the renderer
+ staleness path uses, so an already-stale page is reconciled even when HEAD
+ has not moved.
+ """
+ result = await session.execute(
+ select(Page.target_path).where(
+ Page.repository_id == repository_id,
+ Page.page_type.in_(sorted(_FILE_SCOPED_PAGE_TYPES)),
+ Page.freshness_status.in_(["stale", "expired"]),
+ )
+ )
+ stale_paths: list[str] = []
+ for (target_path,) in result:
+ file_path = (target_path or "").split("::", 1)[0]
+ if file_path:
+ stale_paths.append(file_path)
+ return list(dict.fromkeys(stale_paths))
+
+
+def load_stale_structural_file_paths(repo_path: Any) -> list[str]:
+ """Sync entry point for :func:`_load_stale_structural_file_paths_async`.
+
+ Called from synchronous CLI code and from ``check_repo_staleness``, which
+ the async workspace update calls from inside a running loop. ``asyncio.run``
+ refuses to nest, so that one caller gets its own loop on a worker thread.
+ """
+ import asyncio
+ import concurrent.futures
+ from pathlib import Path
+
+ path_obj = Path(repo_path)
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = None
+
+ if loop and loop.is_running():
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
+ return pool.submit(
+ lambda: asyncio.run(_load_stale_structural_file_paths_async(path_obj))
+ ).result()
+ return asyncio.run(_load_stale_structural_file_paths_async(path_obj))
+
+
+async def _load_stale_structural_file_paths_async(repo_path: Any) -> list[str]:
+ """Load the stale file-scoped page paths for *repo_path* from its store.
+
+ Returns ``[]`` when no store is reachable: no configured database URL and
+ no local ``wiki.db``. A store that is reachable but fails to answer raises,
+ because reading that as "nothing is stale" would silently retire the
+ reconciliation this exists for.
+ """
+ from pathlib import Path
+
+ import structlog
+
+ from ..database import (
+ create_engine,
+ create_session_factory,
+ get_configured_db_url,
+ get_repo_db_path,
+ get_session,
+ resolve_db_url,
+ )
+ from .repository import get_repository_by_path
+
+ logger = structlog.get_logger(__name__)
+ path_obj = Path(repo_path)
+
+ if get_configured_db_url() is None and not get_repo_db_path(path_obj).exists():
+ return []
+
+ url = resolve_db_url(path_obj)
+ engine = create_engine(url)
+ try:
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await get_repository_by_path(session, str(path_obj))
+ if repo is None:
+ return []
+ return await get_stale_structural_file_paths(session, repo.id)
+ except Exception as exc:
+ logger.warning("load_stale_structural_file_paths_failed", error=str(exc))
+ raise
+ finally:
+ await engine.dispose()
+
+
async def get_stale_file_page_ages(
session: AsyncSession,
repository_id: str,
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 6d115b403..6714c1220 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -273,6 +273,15 @@ def check_repo_staleness(
return True, current_head, 0
if current_head == last_commit:
+ # Same reconciliation as the single-repo update: a page can be stale
+ # with HEAD unmoved, and only an update clears it.
+ try:
+ from repowise.core.persistence import load_stale_structural_file_paths
+
+ if load_stale_structural_file_paths(repo_path):
+ return True, current_head, 0
+ except Exception:
+ _log.debug("stale page probe failed for %s", repo_path, exc_info=True)
return False, current_head, 0
behind = count_commits_between(repo_path, last_commit, current_head)
diff --git a/tests/unit/cli/test_update_reconciles_stale_pages.py b/tests/unit/cli/test_update_reconciles_stale_pages.py
new file mode 100644
index 000000000..8637fd476
--- /dev/null
+++ b/tests/unit/cli/test_update_reconciles_stale_pages.py
@@ -0,0 +1,149 @@
+"""``repowise update`` reconciles stale file pages when HEAD has not moved (#1744).
+
+The early exit gates on git alone, and the "no changed files" exit right after
+it does too. A page marked stale by a budget-capped cascade, an interrupted
+run or an expiry therefore had no command that could clear it. These drive
+the real command over a one-file repository and read the page back.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import subprocess
+from pathlib import Path
+
+from sqlalchemy import select
+
+
+def _git(repo: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=str(repo), capture_output=True, text=True, check=True
+ ).stdout.strip()
+
+
+def _db_url(repo: Path) -> str:
+ return f"sqlite+aiosqlite:///{repo / '.repowise' / 'wiki.db'}"
+
+
+async def _seed(repo: Path, pages: dict[str, str]) -> None:
+ """A repository row plus one file page per ``{path: freshness_status}``."""
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_page,
+ upsert_repository,
+ )
+
+ engine = create_engine(_db_url(repo))
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ row = await upsert_repository(session, name=repo.name, local_path=str(repo))
+ for path, status in pages.items():
+ await upsert_page(
+ session,
+ page_id=f"file_page:{path}",
+ repository_id=row.id,
+ page_type="file_page",
+ title=f"File: {path}",
+ content=f"# {path}\n",
+ summary="",
+ target_path=path,
+ source_hash="",
+ model_name="template",
+ provider_name="template",
+ freshness_status=status,
+ )
+ await session.commit()
+ await engine.dispose()
+
+
+async def _freshness(repo: Path) -> dict[str, str]:
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.models import Page
+
+ engine = create_engine(_db_url(repo))
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ rows = await session.execute(select(Page.target_path, Page.freshness_status))
+ return dict(rows.all())
+ finally:
+ await engine.dispose()
+
+
+def _repo_at_head(tmp_path: Path) -> tuple[Path, str]:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init", "-q")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "T")
+ (repo / "foo.py").write_text("def foo():\n return 1\n", encoding="utf-8")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-q", "-m", "c0")
+ head = _git(repo, "rev-parse", "HEAD")
+ (repo / ".repowise").mkdir()
+ return repo, head
+
+
+def _update(repo: Path) -> str:
+ from click.testing import CliRunner
+
+ from repowise.cli.main import cli
+
+ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])
+ assert result.exit_code == 0, result.output
+ return result.output
+
+
+def _state_at(repo: Path, head: str) -> None:
+ from repowise.cli.helpers import save_state
+
+ save_state(
+ repo,
+ {"last_sync_commit": head, "last_docs_commit": head, "docs_mode": "deterministic"},
+ )
+
+
+def test_stale_page_for_a_present_file_is_re_rendered(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ repo, head = _repo_at_head(tmp_path)
+ asyncio.run(_seed(repo, {"foo.py": "stale"}))
+ _state_at(repo, head)
+
+ output = _update(repo)
+
+ assert "Already up to date" not in output
+ assert "Reconciling stale structural pages: 1" in output
+ assert asyncio.run(_freshness(repo))["foo.py"] == "fresh"
+ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ assert state["last_sync_commit"] == head
+
+
+def test_stale_page_for_a_missing_file_is_tombstoned(tmp_path: Path, monkeypatch) -> None:
+ """Re-rendering cannot clear it; the deletion path can."""
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ repo, head = _repo_at_head(tmp_path)
+ asyncio.run(_seed(repo, {"foo.py": "fresh", "gone.py": "stale"}))
+ _state_at(repo, head)
+
+ output = _update(repo)
+
+ assert "Stale pages for deleted files: 1" in output
+ freshness = asyncio.run(_freshness(repo))
+ assert freshness["gone.py"] == "tombstone"
+ assert freshness["foo.py"] == "fresh"
+
+
+def test_no_stale_pages_keeps_the_fast_path(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ repo, head = _repo_at_head(tmp_path)
+ asyncio.run(_seed(repo, {"foo.py": "fresh"}))
+ _state_at(repo, head)
+
+ output = _update(repo)
+
+ assert "Already up to date" in output
+ assert "Reconciling" not in output
diff --git a/tests/unit/cli/test_update_stale_reconciliation.py b/tests/unit/cli/test_update_stale_reconciliation.py
new file mode 100644
index 000000000..25c55a0a6
--- /dev/null
+++ b/tests/unit/cli/test_update_stale_reconciliation.py
@@ -0,0 +1,265 @@
+"""Tests for stale structural page reconciliation during repowise update and workspace staleness checks."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.doctor_cmd import repo_checks
+from repowise.core.persistence import load_stale_structural_file_paths
+from repowise.core.workspace.update import check_repo_staleness
+
+
+async def _setup_repo_with_pages(
+ tmp_path: Path, stale_paths: list[str]
+) -> tuple[Path, str]:
+ """Helper to initialize a git repo with a DB and pages (some of which are marked stale)."""
+ import git as gitpython
+
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_page,
+ upsert_repository,
+ )
+
+ repo_path = (tmp_path / "test_repo").resolve()
+ repo_path.mkdir(parents=True, exist_ok=True)
+ git_repo = gitpython.Repo.init(repo_path)
+
+ # Commit a dummy file
+ dummy = repo_path / "foo.py"
+ dummy.write_text("def foo(): pass\n")
+ git_repo.index.add(["foo.py"])
+ commit = git_repo.index.commit("Initial commit")
+ head_sha = commit.hexsha
+
+ repowise_dir = repo_path / ".repowise"
+ repowise_dir.mkdir(exist_ok=True)
+
+ engine = create_engine(f"sqlite+aiosqlite:///{repowise_dir / 'wiki.db'}")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session, name="test_repo", local_path=str(repo_path), url="https://example.test/repo"
+ )
+ for path in ["foo.py", "bar.py"]:
+ page_id = f"file_page:{path}"
+ freshness = "stale" if path in stale_paths else "fresh"
+ await upsert_page(
+ session,
+ page_id=page_id,
+ repository_id=repo.id,
+ page_type="file_page",
+ title=f"File: {path}",
+ content="def code(): pass",
+ summary="Summary",
+ target_path=path,
+ source_hash="hash",
+ model_name="mock",
+ provider_name="mock",
+ freshness_status=freshness,
+ )
+ # Also test symbol spotlight structural page with target_path using '::'
+ if "spotlight.py" in stale_paths:
+ await upsert_page(
+ session,
+ page_id="symbol_spotlight:spotlight.py::my_func",
+ repository_id=repo.id,
+ page_type="symbol_spotlight",
+ title="Spotlight: my_func",
+ content="def my_func(): pass",
+ summary="Summary",
+ target_path="spotlight.py::my_func",
+ source_hash="hash",
+ model_name="mock",
+ provider_name="mock",
+ freshness_status="stale",
+ )
+ await session.commit()
+
+ await engine.dispose()
+ return repo_path, head_sha
+
+
+def test_load_stale_structural_file_paths(tmp_path: Path) -> None:
+ """load_stale_structural_file_paths returns file paths for file_pages marked stale or expired."""
+ repo_path, _ = asyncio.run(_setup_repo_with_pages(tmp_path, ["bar.py"]))
+
+ stale = load_stale_structural_file_paths(repo_path)
+ assert stale == ["bar.py"]
+
+
+def test_repo_wide_structural_pages_are_not_reported(tmp_path: Path) -> None:
+ """A stale cycle or layer page is only ever rewritten by a full run.
+
+ Reporting it would make every idle update pay a full reparse that cannot
+ clear it, on every run, forever.
+ """
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ upsert_page,
+ upsert_repository,
+ )
+
+ repo_path, _ = asyncio.run(_setup_repo_with_pages(tmp_path, []))
+
+ async def _add_stale_layer_page() -> None:
+ engine = create_engine(f"sqlite+aiosqlite:///{repo_path / '.repowise' / 'wiki.db'}")
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name="test_repo", local_path=str(repo_path))
+ await upsert_page(
+ session,
+ page_id="layer_page:core",
+ repository_id=repo.id,
+ page_type="layer_page",
+ title="Layer: core",
+ content="# core\n",
+ summary="Summary",
+ target_path="core",
+ source_hash="hash",
+ model_name="mock",
+ provider_name="mock",
+ freshness_status="stale",
+ )
+ await session.commit()
+ await engine.dispose()
+
+ asyncio.run(_add_stale_layer_page())
+ assert load_stale_structural_file_paths(repo_path) == []
+
+
+def test_load_stale_structural_file_paths_spotlight(tmp_path: Path) -> None:
+ """load_stale_structural_file_paths extracts file path from symbol_spotlight target_path."""
+ repo_path, _ = asyncio.run(_setup_repo_with_pages(tmp_path, ["spotlight.py"]))
+
+ stale = load_stale_structural_file_paths(repo_path)
+ assert stale == ["spotlight.py"]
+
+
+def test_load_stale_structural_file_paths_empty_when_all_fresh(tmp_path: Path) -> None:
+ """load_stale_structural_file_paths returns empty list when all pages are fresh."""
+ repo_path, _ = asyncio.run(_setup_repo_with_pages(tmp_path, []))
+
+ stale = load_stale_structural_file_paths(repo_path)
+ assert stale == []
+
+
+def test_check_repo_staleness_detects_stale_structural_pages(tmp_path: Path) -> None:
+ """check_repo_staleness returns is_stale=True when current_head == last_commit but DB has stale pages."""
+ repo_path, head_sha = asyncio.run(_setup_repo_with_pages(tmp_path, ["bar.py"]))
+
+ is_stale, current_head, behind = check_repo_staleness(repo_path, head_sha)
+ assert is_stale is True
+ assert current_head == head_sha
+ assert behind == 0
+
+
+def test_check_repo_staleness_returns_false_when_all_fresh(tmp_path: Path) -> None:
+ """check_repo_staleness returns is_stale=False when current_head == last_commit and no pages are stale."""
+ repo_path, head_sha = asyncio.run(_setup_repo_with_pages(tmp_path, []))
+
+ is_stale, current_head, behind = check_repo_staleness(repo_path, head_sha)
+ assert is_stale is False
+ assert current_head == head_sha
+ assert behind == 0
+
+
+def test_doctor_detects_stale_pages_and_clears_after_reconciliation(tmp_path: Path) -> None:
+ """Doctor check flags stale pages, and load_stale_structural_file_paths identifies them."""
+ repo_path, _ = asyncio.run(_setup_repo_with_pages(tmp_path, ["foo.py", "bar.py"]))
+
+ # 1. Doctor initially reports stale pages
+ _, checks = repo_checks._run_repo_checks(repo_path, repair=False, fmt="quiet")
+ stale_check = next(c for c in checks if c.name == "Stale pages")
+ assert stale_check.ok is False
+ assert stale_check.detail.startswith("2 stale")
+
+ # 2. Verify load_stale_structural_file_paths returns the 2 stale paths
+ stale_paths = load_stale_structural_file_paths(repo_path)
+ assert sorted(stale_paths) == ["bar.py", "foo.py"]
+
+
+def test_stale_structural_paths_scoped_to_repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """load_stale_structural_file_paths filters by repository_id in a shared database."""
+ import git as gitpython
+
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_page,
+ upsert_repository,
+ )
+
+ db_file = tmp_path / "shared_wiki.db"
+ db_url = f"sqlite+aiosqlite:///{db_file}"
+ monkeypatch.setenv("REPOWISE_DB_URL", db_url)
+
+ repo_a = (tmp_path / "repo_a").resolve()
+ repo_b = (tmp_path / "repo_b").resolve()
+ repo_a.mkdir()
+ repo_b.mkdir()
+ gitpython.Repo.init(repo_a)
+ gitpython.Repo.init(repo_b)
+
+ async def _setup_shared_db() -> None:
+ engine = create_engine(db_url)
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ r_a = await upsert_repository(session, name="repo_a", local_path=str(repo_a))
+ r_b = await upsert_repository(session, name="repo_b", local_path=str(repo_b))
+
+ # Add stale page for Repo A
+ await upsert_page(
+ session,
+ page_id="file_page:a.py",
+ repository_id=r_a.id,
+ page_type="file_page",
+ title="File: a.py",
+ content="code",
+ summary="",
+ target_path="a.py",
+ source_hash="",
+ model_name="mock",
+ provider_name="mock",
+ freshness_status="stale",
+ )
+ # Add stale page for Repo B
+ await upsert_page(
+ session,
+ page_id="file_page:b.py",
+ repository_id=r_b.id,
+ page_type="file_page",
+ title="File: b.py",
+ content="code",
+ summary="",
+ target_path="b.py",
+ source_hash="",
+ model_name="mock",
+ provider_name="mock",
+ freshness_status="stale",
+ )
+ await session.commit()
+ await engine.dispose()
+
+ asyncio.run(_setup_shared_db())
+
+ # Query repo A: must only return a.py
+ stale_a = load_stale_structural_file_paths(repo_a)
+ assert stale_a == ["a.py"]
+
+ # Query repo B: must only return b.py
+ stale_b = load_stale_structural_file_paths(repo_b)
+ assert stale_b == ["b.py"]