Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(change-risk): read the indexed commit through one resolver and stamp it from one head (#3708)
Swati Ahujab19feedda986
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.pyindex bf6e7aebd..89aca9fcb 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py@@ -86,6 +86,7 @@ def _workspace_update(reconcile_repo_head_commit,update_workspace,)+ from repowise.core.workspace.update import sync_workspace_state_from_diskfrom .mode import _resolve_index_only_mode@@ -103,6 +104,11 @@ def _workspace_update(console.print(f"[bold]repowise update[/bold] \u2014 workspace: {ws_root.name}")console.print()+ # Staleness reads the workspace config, and an "up to date" repo has its DB+ # row stamped from live HEAD below. Read each repo's state.json first, as+ # update_workspace does, so a config ahead of state.json cannot stamp the+ # row past the commit state.json names.+ sync_workspace_state_from_disk(ws_root, ws_config)stale_count = 0up_to_date_count = 0up_to_date_repos: list[tuple[Path, str]] = []diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex fdde04ed3..a5cac39d8 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -490,8 +490,14 @@ def save_state(repo_path: Path, state: dict[str, Any], *, full_index: bool = Falincremental persist leaves it False and the version clamps below any``REINDEX_RECOMMENDED`` gate, keeping a reindex recommendation alive untilan actual re-index clears it.++ A write that changes ``last_sync_commit`` moves the repository row's+ ``head_commit`` to the same commit, so the two stamps never disagree."""+ from repowise.core.workspace.update import read_state_commit, restamp_changed_sync_commit+ensure_repowise_dir(repo_path)+ previous = read_state_commit(Path(repo_path))try:from repowise.cli import __version__ as _pkg_versionfrom repowise.core.upgrade import stamp as _stamp_store_version@@ -505,6 +511,7 @@ def save_state(repo_path: Path, state: dict[str, Any], *, full_index: bool = Fal# every later update would fail to parse it and demand a full re-init.state_path = get_repowise_dir(repo_path) / STATE_FILENAMEatomic_write_text(state_path, json.dumps(state, indent=2))+ restamp_changed_sync_commit(Path(repo_path), previous, state.get("last_sync_commit"))# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/analysis/test_collection.py b/packages/core/src/repowise/core/analysis/test_collection.pyindex aadafad84..1992250aa 100644--- a/packages/core/src/repowise/core/analysis/test_collection.py+++ b/packages/core/src/repowise/core/analysis/test_collection.py@@ -298,21 +298,13 @@ async def _place_tests(session, repo_id: str, out: dict) -> None:def _indexed_commit(repo_path, row_commit: str | None, out: dict) -> None:- """The commit the index describes: ``state.json`` first, then the repository row.+ """The commit the index describes, read by the one resolver the server's freshness uses."""+ from ..workspace.update import resolve_indexed_commit- The same order the server's freshness check reads. When both are recorded- and disagree, the index's own history is in doubt, so the commit is unknown.- """- from ..workspace.update import read_state_commit-- state = read_state_commit(Path(repo_path))- if state and row_commit and state != row_commit:- out["index_problem"] = (- f"The index records two commits ({state[:7]} in state.json, {row_commit[:7]} "- "in its database), so what it describes is unknown; run `repowise update`."- )- return- out["indexed_commit"] = state or row_commit+ resolved = resolve_indexed_commit(Path(repo_path), row_commit)+ if resolved.problem:+ out["index_problem"] = resolved.problem+ out["indexed_commit"] = resolved.shadef _gap_routes(repo_path, change, config, repo_keys: set[str], out: dict) -> list[str]:diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.pyindex 42a0adea4..7818da118 100644--- a/packages/core/src/repowise/core/git_refs.py+++ b/packages/core/src/repowise/core/git_refs.py@@ -28,6 +28,7 @@ __all__ = ["default_base","files_by_ref","find_path_removal",+ "is_ancestor","is_shallow","list_branches","refs_containing",@@ -301,6 +302,18 @@ def ahead_behind(repo_path: str, base: str, head: str) -> tuple[int, int]:return (ahead, behind)+def is_ancestor(repo_path: str, older: str, newer: str) -> bool | None:+ """Whether *older* is *newer* or one of its ancestors; ``None`` when git cannot answer."""+ try:+ _git(["merge-base", "--is-ancestor", "--end-of-options", older, newer], cwd=repo_path)+ except subprocess.CalledProcessError as exc:+ # Exit 1 is git's "no"; anything else is an unknown sha or no repository.+ return False if exc.returncode == 1 else None+ except (subprocess.TimeoutExpired, OSError):+ return None+ return True++@dataclass(frozen=True)class PathRemoval:"""The most recent commit that removed a path, and where it likely went."""diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex 838edc46e..44f7eb137 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -17,7 +17,7 @@ from contextlib import suppressfrom dataclasses import dataclassfrom datetime import UTC, datetimefrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, NamedTupleif TYPE_CHECKING:from repowise.core.workspace.extractors.service_boundary import ServiceBoundary@@ -278,6 +278,66 @@ def read_state_commit(repo_path: Path) -> str | None:return str(sha) if sha else None+class IndexedCommit(NamedTuple):+ """The commit an index describes, or why it cannot be named."""++ sha: str | None+ problem: str | None = None+++def resolve_indexed_commit(repo_path: Path | None, row_commit: str | None) -> IndexedCommit:+ """The commit the index describes, from ``state.json`` and the repository row.++ Every update writes both from one captured head, so they normally agree.+ When one is an ancestor of the other (an update interrupted between the+ two writes, or a row an older build left behind), the index describes the+ older: the files between them then count as changed since the index was+ built, which over-selects rather than misses. Two commits neither of which+ contains the other (a rebase, a restored backup), or a sha git cannot+ read, leave the commit unknown.+ """+ state = read_state_commit(repo_path) if repo_path is not None else None+ if not state or not row_commit or state == row_commit:+ return IndexedCommit(state or row_commit)+ older = _older_commit(str(repo_path), state, row_commit)+ if older is not None:+ return IndexedCommit(older)+ return IndexedCommit(+ None,+ f"The index records two commits ({state[:7]} in state.json, {row_commit[:7]} "+ "in its database) and neither contains the other, so what it describes is "+ "unknown; run `repowise update`.",+ )+++# (repo_path, a, b) -> the older commit, or None when neither contains the+# other. Only definite answers: a timeout or an unknown sha is asked again.+_ancestry_cache: dict[tuple[str, str, str], str | None] = {}+_ANCESTRY_CACHE_MAX = 32+++def _older_commit(repo_path: str, a: str, b: str) -> str | None:+ """The one of *a*, *b* that is an ancestor of the other, else ``None``.++ Cached because the freshness envelope asks on every response while the two+ stamps disagree. Ancestry between two known shas never changes, and the+ next update makes the stamps equal, which ends the asking.+ """+ from ..git_refs import is_ancestor++ key = (repo_path, a, b)+ if key in _ancestry_cache:+ return _ancestry_cache[key]+ a_first = is_ancestor(repo_path, a, b)+ b_first = None if a_first else is_ancestor(repo_path, b, a)+ older = a if a_first else b if b_first else None+ if older is not None or (a_first is False and b_first is False):+ if len(_ancestry_cache) >= _ANCESTRY_CACHE_MAX:+ _ancestry_cache.clear()+ _ancestry_cache[key] = older+ return older++def sync_workspace_state_from_disk(workspace_root: Path,ws_config: WorkspaceConfig,@@ -345,6 +405,34 @@ def check_repo_staleness(return True, current_head, behind+def restamp_changed_sync_commit(repo_path: Path, previous: str | None, current: str | None) -> None:+ """Move the repository row to a ``last_sync_commit`` a state write just changed.++ The CLI and server state writers call this (the workspace updater awaits+ :func:`reconcile_repo_head_commit` itself), so a path that advances the+ sync commit leaves the row on the same commit, whatever HEAD its persist+ step read (a pull during a long run moves it). An unchanged commit is left+ alone: the "up to date" paths stamp it themselves. The state file is+ already written, so a failure here is logged, not raised.+ """+ if not current or current == previous:+ return++ try:+ asyncio.get_running_loop()+ except RuntimeError:+ pass+ else:+ # Ceiling: callers must be off-loop; skipped here, the resolver still+ # reads the ancestor pair this leaves correctly.+ _log.warning("Skipped the repository row restamp for %s: called on an event loop", repo_path)+ return+ try:+ asyncio.run(reconcile_repo_head_commit(repo_path, current))+ except Exception:+ _log.warning("Could not restamp the repository row for %s", repo_path, exc_info=True)++async def reconcile_repo_head_commit(repo_path: Path, head: str | None) -> None:"""Advance the DB freshness for *repo_path* after a sync-check to *head*.diff --git a/packages/server/src/repowise/server/job_state.py b/packages/server/src/repowise/server/job_state.pyindex 417ce85f6..a07616c21 100644--- a/packages/server/src/repowise/server/job_state.py+++ b/packages/server/src/repowise/server/job_state.py@@ -42,9 +42,14 @@ def _load_state(repo_path: Path) -> dict:def _save_state(repo_path: Path, state: dict) -> None:+ from repowise.core.workspace.update import read_state_commit, restamp_changed_sync_commit++ previous = read_state_commit(repo_path)state_path = repo_path / ".repowise" / "state.json"state_path.parent.mkdir(parents=True, exist_ok=True)state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")+ # The job's persist never moves the row's head_commit; keep it on the sync commit.+ restamp_changed_sync_commit(repo_path, previous, state.get("last_sync_commit"))def _stamp_last_sync_commit(repo_path: Path) -> None:diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex b516b5fff..95fc20a2c 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -119,29 +119,6 @@ def read_live_head(local_path: str | None) -> str | None:return read_head_commit(local_path)-def read_state_sync_commit(local_path: str | None) -> str | None:- """Return ``last_sync_commit`` from ``<local_path>/.repowise/state.json``.-- This is the commit the most recent sync advanced to — written by every- ``repowise update`` path, including the fast paths ("already up to date",- "no changed files") that don't rebuild the DB. It is the authoritative- freshness marker; the ``repositories`` row can lag it when an older build's- fast path skipped the DB stamp. Returns ``None`` for hosted/ephemeral- indexes with no state file.- """- if not local_path:- return None- try:- import json-- state_path = Path(local_path) / ".repowise" / "state.json"- data = json.loads(state_path.read_text(encoding="utf-8"))- except (OSError, ValueError):- return None- commit = data.get("last_sync_commit")- return commit if isinstance(commit, str) and commit else None--def read_index_scope(local_path: str | None) -> dict[str, Any] | None:"""Read the canonical persisted scope, or a conservative legacy projection."""if not local_path:@@ -187,17 +164,17 @@ def index_scope_for_response(local_path: str | None) -> dict[str, Any] | None:def resolve_indexed_commit(head_commit: str | None, local_path: str | None) -> str | None:- """Best available "commit the index reflects" for a repo.-- Prefers the on-disk ``state.json`` ``last_sync_commit`` over the DB- ``head_commit`` so the freshness signal stays honest even when an older- build left the ``repositories`` row un-stamped — a read-time self-heal that- needs no ``repowise update`` first. The row is repaired for good on the next- update; until then this keeps ``/api/repos`` and the MCP ``_meta`` staleness- check from falsely reporting "index behind checkout". Falls back to the DB- value when there is no state file (hosted indexes).+ """The commit the index reflects, from ``state.json`` and the DB ``head_commit``.++ One resolver with impacted-test selection (see+ :func:`repowise.core.workspace.update.resolve_indexed_commit`), so a+ response never names an indexed commit in ``_meta`` while its selection+ calls the same index unknown. ``None`` when the two stamps diverge. Hosted+ indexes have no state file and keep the DB value."""- return read_state_sync_commit(local_path) or head_commit+ from repowise.core.workspace.update import resolve_indexed_commit as _resolve++ return _resolve(Path(local_path) if local_path else None, head_commit).sha# (local_path, indexed_sha, live_sha) -> files changed between the two commits,@@ -536,8 +513,7 @@ def freshness_from_repo(# ``root``: the served checkout (see served_root), resolved here when omitted.local_path = root or served_root(repository)- # Prefer state.json's last_sync_commit over a possibly-stale DB head_commit- # so freshness self-heals on read (see resolve_indexed_commit).+ # state.json and the DB row reconciled by the shared resolver.indexed_full = resolve_indexed_commit(getattr(repository, "head_commit", None) or None, local_path)diff --git a/packages/server/src/repowise/server/routers/_repo_listing.py b/packages/server/src/repowise/server/routers/_repo_listing.pyindex 87b28d040..96a188488 100644--- a/packages/server/src/repowise/server/routers/_repo_listing.py+++ b/packages/server/src/repowise/server/routers/_repo_listing.py@@ -73,10 +73,12 @@ async def load_repositories(def heal_indexed_commits(responses: list[RepoResponse]) -> None:- # Prefer state.json's last_sync_commit over a possibly stale DB head_commit.+ # The resolved indexed commit; diverged stamps keep the row's own value.for resp in responses:if resp.local_path:- resp.head_commit = resolve_indexed_commit(resp.head_commit, resp.local_path)+ resp.head_commit = (+ resolve_indexed_commit(resp.head_commit, resp.local_path) or resp.head_commit+ )def flag_unindexed(responses: list[RepoResponse], indexed_repo_ids: set[str]) -> None:diff --git a/packages/server/src/repowise/server/routers/code_health/overview_routes.py b/packages/server/src/repowise/server/routers/code_health/overview_routes.pyindex ffcc853fc..2d5a4b352 100644--- a/packages/server/src/repowise/server/routers/code_health/overview_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/overview_routes.py@@ -170,10 +170,11 @@ async def health_overview(),"meta": {"last_indexed_at": last_indexed_at,- # Prefer state.json's last_sync_commit over a possibly-stale DB row- # so the freshness signal self-heals on read (see the /api/repos- # overlay). This is the extension's primary indexed-commit source.- "head_commit": resolve_indexed_commit(repo.head_commit, repo.local_path),+ # The /api/repos overlay's indexed commit (state.json and the row+ # reconciled). This is the extension's primary indexed-commit source.+ "head_commit": (+ resolve_indexed_commit(repo.head_commit, repo.local_path) or repo.head_commit+ ),"snapshot_count": snapshot.snapshot_count,},}diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.pyindex 21b68300e..b3212e9f9 100644--- a/packages/server/src/repowise/server/routers/overview.py+++ b/packages/server/src/repowise/server/routers/overview.py@@ -469,14 +469,11 @@ async def overview_summary(savings = await _savings_headline(repo.local_path)repowise_dir = Path(repo.local_path) / ".repowise" if repo.local_path else Path(".repowise")- # Serve the same read-time self-healed "indexed commit" as /api/repos and- # /health/overview: prefer state.json's last_sync_commit over a possibly- # stale DB row so the dashboard's indexed-commit display (and any freshness- # signal derived from it) doesn't read "behind" after a no-op update left- # the repositories row un-restamped.+ # The same indexed commit as /api/repos and /health/overview: state.json+ # and the row reconciled, the row's own value when the two diverge.from repowise.server.mcp_server._meta import resolve_indexed_commit- indexed_commit = resolve_indexed_commit(repo.head_commit, repo.local_path)+ indexed_commit = resolve_indexed_commit(repo.head_commit, repo.local_path) or repo.head_commitreturn {"repo": {diff --git a/tests/unit/cli/test_freshness_stamp_fixes.py b/tests/unit/cli/test_freshness_stamp_fixes.pyindex 1ff47bfba..9aa73562d 100644--- a/tests/unit/cli/test_freshness_stamp_fixes.py+++ b/tests/unit/cli/test_freshness_stamp_fixes.py@@ -146,10 +146,11 @@ def test_advise_stamp_skips_when_claude_md_disabled(tmp_path, monkeypatch):# ----------------------------------------------------------------------------# Read-time freshness self-heal: prefer state.json's last_sync_commit over a-# DB repositories.head_commit that an older build left un-stamped, so the+# Read-time freshness: state.json's last_sync_commit stands in for a DB+# repositories.head_commit that an older build left un-stamped, so the# extension badge / MCP staleness signal is correct on the first read without-# requiring a `repowise update` first.+# requiring a `repowise update` first. Disagreeing stamps are covered in+# tests/unit/workspace/test_indexed_commit.py.# ---------------------------------------------------------------------------@@ -162,13 +163,12 @@ def _write_state(repo_path: Path, last_sync_commit: str | None) -> None:(dot / "state.json").write_text(json.dumps(payload), encoding="utf-8")-def test_resolve_indexed_commit_prefers_state_json(tmp_path):+def test_resolve_indexed_commit_uses_state_json_without_a_row_stamp(tmp_path):from repowise.server.mcp_server._meta import resolve_indexed_commitfresh = "8092ebf" + "0" * 33_write_state(tmp_path, fresh)- # DB row lags (a pre-fix "no changed files" run bumped only state.json).- assert resolve_indexed_commit("deadbeef" + "0" * 32, str(tmp_path)) == fresh+ assert resolve_indexed_commit(None, str(tmp_path)) == freshdef test_resolve_indexed_commit_falls_back_to_db_without_state(tmp_path):@@ -195,14 +195,14 @@ def test_freshness_self_heals_and_silences_false_stale(tmp_path):head = "8092ebf" + "0" * 33# Live checkout is at ``head``; state.json says the index synced to ``head``;- # but the DB row still holds the last full-index commit.+ # but the DB row was never stamped.git_dir = tmp_path / ".git"git_dir.mkdir()(git_dir / "HEAD").write_text(head + "\n", encoding="utf-8")_write_state(tmp_path, head)repo = types.SimpleNamespace(- head_commit="deadbeef" + "0" * 32,+ head_commit=None,local_path=str(tmp_path),updated_at=None,)diff --git a/tests/unit/cli/test_impacted_tests_cmd.py b/tests/unit/cli/test_impacted_tests_cmd.pyindex bdb669687..eb551ae49 100644--- a/tests/unit/cli/test_impacted_tests_cmd.py+++ b/tests/unit/cli/test_impacted_tests_cmd.py@@ -236,11 +236,28 @@ def test_list_prints_one_test_per_line(repo) -> None:assert result.stdout == "tests/test_a.py\n"-def test_an_index_that_disagrees_about_its_commit_runs_everything(repo) -> None:+def test_stamps_one_commit_apart_select_from_the_older(repo) -> None:+ # The database row says main; state.json says feat, one commit later.(repo / ".repowise" / "state.json").write_text(json.dumps({"last_sync_commit": _git(repo, "rev-parse", "feat")}), encoding="utf-8")result = _run(repo, "main...feat", "--format", "args")+ assert result.exit_code == 0, result.output+ assert result.stdout == "tests/test_a.py\n"+++def test_an_index_whose_stamps_diverge_runs_everything(repo) -> None:+ _git(repo, "switch", "-q", "--orphan", "other")+ _write(repo, {"src/b.py": "B = 2\n"})+ _git(repo, "add", "src/b.py")+ _git(repo, "commit", "-qm", "other")+ other = _git(repo, "rev-parse", "HEAD")+ _git(repo, "switch", "-qf", "feat")+ # The row says main, and other shares no history with it: the index is in doubt.+ (repo / ".repowise" / "state.json").write_text(+ json.dumps({"last_sync_commit": other}), encoding="utf-8"+ )+ result = _run(repo, "main...feat", "--format", "args")assert result.stdout == ":all\n"assert "The index records two commits" in _err(result)diff --git a/tests/unit/cli/test_sync_commit_restamp.py b/tests/unit/cli/test_sync_commit_restamp.pynew file mode 100644index 000000000..8cac0c25a--- /dev/null+++ b/tests/unit/cli/test_sync_commit_restamp.py@@ -0,0 +1,136 @@+"""Every state.json writer leaves the repository row on the sync commit it wrote."""++from __future__ import annotations++import asyncio+import json+import subprocess+import types+from pathlib import Path++import pytest+from sqlalchemy import select+++def _git(cwd: Path, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True+ ).stdout.strip()+++async def _seed_row(repo: Path, head: str) -> None:+ from sqlalchemy.ext.asyncio import async_sessionmaker++ from repowise.core.persistence import create_engine, init_db+ from repowise.core.persistence.database import resolve_db_url+ from repowise.core.persistence.models import Repository++ engine = create_engine(resolve_db_url(repo))+ try:+ await init_db(engine)+ async with async_sessionmaker(engine, expire_on_commit=False)() as session:+ session.add(Repository(id="r1", name="r", local_path=str(repo), head_commit=head))+ await session.commit()+ finally:+ await engine.dispose()+++async def _row_commit(repo: Path) -> str | None:+ from sqlalchemy.ext.asyncio import async_sessionmaker++ from repowise.core.persistence import create_engine+ from repowise.core.persistence.database import resolve_db_url+ from repowise.core.persistence.models import Repository++ engine = create_engine(resolve_db_url(repo))+ try:+ async with async_sessionmaker(engine)() as session:+ return await session.scalar(select(Repository.head_commit))+ finally:+ await engine.dispose()+++def repo(tmp_path):+ """A checkout at ``new`` whose state.json and row both name its parent ``old``."""+ _git(tmp_path, "init", "-q")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ for name in ("old", "new"):+ (tmp_path / name).write_text(name, encoding="utf-8")+ _git(tmp_path, "add", name)+ _git(tmp_path, "commit", "-qm", name)+ old = _git(tmp_path, "rev-parse", "HEAD~1")+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / "state.json").write_text(+ json.dumps({"last_sync_commit": old}), encoding="utf-8"+ )+ asyncio.run(_seed_row(tmp_path, old))+ return tmp_path, old, _git(tmp_path, "rev-parse", "HEAD")+++def _state_commit(repo: Path) -> str:+ return json.loads((repo / ".repowise" / "state.json").read_text())["last_sync_commit"]+++def test_generate_leaves_both_stamps_on_one_commit(repo) -> None:+ from repowise.cli.commands.generate_cmd.command import _write_state++ path, _old, new = repo+ _write_state(+ path,+ {"last_sync_commit": _old},+ types.SimpleNamespace(provider_name="mock", model_name="m"),+ types.SimpleNamespace(total_pages=1, remaining_template_pages=1),+ )+ assert _state_commit(path) == new+ assert asyncio.run(_row_commit(path)) == new+++def test_a_server_job_leaves_both_stamps_on_one_commit(repo) -> None:+ from repowise.server.job_state import _stamp_last_sync_commit++ path, _old, new = repo+ _stamp_last_sync_commit(path)+ assert _state_commit(path) == new+ assert asyncio.run(_row_commit(path)) == new+++def test_a_write_that_keeps_the_sync_commit_leaves_the_row_alone(repo, monkeypatch) -> None:+ from repowise.cli.helpers import save_state+ from repowise.core.workspace import update++ path, old, _new = repo+ stamped: list[str] = []+ monkeypatch.setattr(+ update, "reconcile_repo_head_commit", lambda _p, head: stamped.append(head)+ )+ save_state(path, {"last_sync_commit": old, "total_pages": 3})+ assert stamped == []+++def test_a_save_on_a_running_loop_skips_the_restamp_without_raising(repo) -> None:+ from repowise.cli.helpers import save_state++ path, old, new = repo++ async def _save() -> None:+ save_state(path, {"last_sync_commit": new})++ asyncio.run(asyncio.wait_for(_save(), timeout=10))+ assert _state_commit(path) == new+ assert asyncio.run(_row_commit(path)) == old+++async def test_a_server_index_job_restamps_the_row_off_the_loop(repo) -> None:+ """The job executor writes state.json through asyncio.to_thread, so the+ restamp runs with no event loop of its own and is not skipped."""+ from repowise.server.job_executor import _write_index_state++ path, _old, new = repo+ run = types.SimpleNamespace(+ spec=types.SimpleNamespace(is_initial_index=False, repo_path=str(path), job_id="j")+ )+ await _write_index_state(run, types.SimpleNamespace(), total_pages=0)+ assert _state_commit(path) == new+ assert await _row_commit(path) == newdiff --git a/tests/unit/cli/test_update_e2e.py b/tests/unit/cli/test_update_e2e.pyindex 3225e6a4a..f611d3c00 100644--- a/tests/unit/cli/test_update_e2e.py+++ b/tests/unit/cli/test_update_e2e.py@@ -279,3 +279,39 @@ def test_update_degrades_visibly_when_a_step_fails(tmp_path: Path, monkeypatch)assert result.exit_code == 0, result.outputassert "degraded step(s)" in result.outputassert "Graph nodes persist" in result.output+++def test_a_pull_during_the_update_leaves_both_stamps_on_one_commit(+ tmp_path: Path, monkeypatch+) -> None:+ """state.json and the repository row name the head the update started from,+ even when HEAD moves while it runs (a pull or commit mid-update)."""+ repo = _make_git_repo(tmp_path)+ _index_full(repo)+ from repowise.cli.helpers import save_state++ save_state(repo, {"last_sync_commit": _git(repo, "rev-parse", "HEAD"), "docs_enabled": False})+ (repo / "c.py").write_text("def gamma():\n return 3\n")+ _git(repo, "add", ".")+ _git(repo, "commit", "-m", "add c.py")+ started_at = _git(repo, "rev-parse", "HEAD")++ import repowise.core.pipeline.incremental as incremental_mod++ persist = incremental_mod.persist_incremental_index++ async def _pull_then_persist(*args, **kwargs):+ (repo / "d.py").write_text("def delta():\n return 4\n")+ _git(repo, "add", ".")+ _git(repo, "commit", "-m", "landed mid-update")+ return await persist(*args, **kwargs)++ monkeypatch.setattr(incremental_mod, "persist_incremental_index", _pull_then_persist)++ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])+ assert result.exit_code == 0, result.output+ assert _git(repo, "rev-parse", "HEAD") != started_at++ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))+ assert state["last_sync_commit"] == started_at+ assert asyncio.run(_db_snapshot(repo))["head_commit"] == started_atdiff --git a/tests/unit/server/test_overview_sync.py b/tests/unit/server/test_overview_sync.pyindex 25cd23d7a..877fd1c26 100644--- a/tests/unit/server/test_overview_sync.py+++ b/tests/unit/server/test_overview_sync.py@@ -82,14 +82,12 @@ async def test_completed_sync_job_wins_over_fallback(client: AsyncClient, app) -@pytest.mark.asyncioasync def test_head_commit_heals_from_state_json(client: AsyncClient, app, tmp_path) -> None:- """overview-summary serves state.json's last_sync_commit over a stale DB- head_commit, matching /api/repos and /health/overview so the dashboard's- indexed-commit display never reads "behind" after a no-op update left the- repositories row un-restamped.+ """overview-summary serves state.json's last_sync_commit when the DB row was+ never stamped, matching /api/repos and /health/overview. Rows that disagree+ with state.json are resolved by the shared indexed-commit resolver."""from repowise.core.persistence.models import Repository- stale = "a" * 40current = "c" * 40repo = await create_test_repo(client, tmp_path)@@ -97,12 +95,11 @@ async def test_head_commit_heals_from_state_json(client: AsyncClient, app, tmp_prepowise.mkdir(exist_ok=True)(repowise / "state.json").write_text(f'{{"last_sync_commit": "{current}"}}', encoding="utf-8")- # DB row left at an older commit (the un-restamped case the heal repairs).async with get_session(app.state.session_factory) as session:row = (await session.execute(select(Repository).where(Repository.id == repo["id"]))).scalar_one()- row.head_commit = stale+ row.head_commit = Noneresp = await client.get(f"/api/repos/{repo['id']}/overview-summary")assert resp.status_code == 200diff --git a/tests/unit/server/test_repos_router_paths.py b/tests/unit/server/test_repos_router_paths.pyindex 65d589f57..6c2ab4bf7 100644--- a/tests/unit/server/test_repos_router_paths.py+++ b/tests/unit/server/test_repos_router_paths.py@@ -212,6 +212,9 @@ async def test_summary_freshness_when_one_side_is_unknown(json.dumps({"last_sync_commit": "d" * 40}), encoding="utf-8")behind = await crud.upsert_repository(session, name="behind", local_path=str(behind_dir))+ # Only state.json records the indexed commit (stamps that disagree are the+ # resolver's to reconcile, see tests/unit/workspace/test_indexed_commit.py).+ behind.head_commit = Noneawait session.commit()resp = await client.get("/api/repos/summary")diff --git a/tests/unit/workspace/test_indexed_commit.py b/tests/unit/workspace/test_indexed_commit.pynew file mode 100644index 000000000..e535e53ed--- /dev/null+++ b/tests/unit/workspace/test_indexed_commit.py@@ -0,0 +1,115 @@+"""One resolver names the commit an index describes from state.json and the DB row."""++from __future__ import annotations++import json+import subprocess+from pathlib import Path++import pytest++from repowise.core.workspace.update import resolve_indexed_commit+++def _git(cwd: Path, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True+ ).stdout.strip()+++def _commit(repo: Path, name: str) -> str:+ (repo / name).write_text(name, encoding="utf-8")+ _git(repo, "add", name)+ _git(repo, "commit", "-q", "-m", name)+ return _git(repo, "rev-parse", "HEAD")+++def _state(repo: Path, sha: str | None) -> None:+ (repo / ".repowise").mkdir(exist_ok=True)+ payload = {} if sha is None else {"last_sync_commit": sha}+ (repo / ".repowise" / "state.json").write_text(json.dumps(payload), encoding="utf-8")+++def repo(tmp_path):+ """``old`` and its child ``new`` on main, and ``side`` on a branch cut from root."""+ _git(tmp_path, "init", "-q", "-b", "main")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "t")+ root = _commit(tmp_path, "root")+ old = _commit(tmp_path, "old")+ new = _commit(tmp_path, "new")+ _git(tmp_path, "checkout", "-q", "-b", "side", root)+ side = _commit(tmp_path, "side")+ _git(tmp_path, "checkout", "-q", "main")+ return tmp_path, {"old": old, "new": new, "side": side}+++def test_equal_stamps_name_their_commit(repo) -> None:+ path, c = repo+ _state(path, c["new"])+ assert resolve_indexed_commit(path, c["new"]) == (c["new"], None)++[email protected](("state", "row"), [("old", "new"), ("new", "old")])+def test_when_one_contains_the_other_the_older_wins(repo, state, row) -> None:+ path, c = repo+ _state(path, c[state])+ assert resolve_indexed_commit(path, c[row]) == (c["old"], None)+++def test_unrelated_stamps_leave_the_commit_unknown(repo) -> None:+ path, c = repo+ _state(path, c["new"])+ resolved = resolve_indexed_commit(path, c["side"])+ assert resolved.sha is None+ assert "neither contains the other" in resolved.problem+++def test_an_unreadable_sha_leaves_the_commit_unknown(repo) -> None:+ path, c = repo+ _state(path, c["new"])+ resolved = resolve_indexed_commit(path, "f" * 40)+ assert resolved.sha is None+ assert resolved.problem+++def test_a_missing_stamp_defers_to_the_other(repo) -> None:+ path, c = repo+ assert resolve_indexed_commit(path, c["new"]) == (c["new"], None)+ _state(path, None)+ assert resolve_indexed_commit(path, c["new"]) == (c["new"], None)+ _state(path, c["old"])+ assert resolve_indexed_commit(path, None) == (c["old"], None)+ assert resolve_indexed_commit(None, c["new"]) == (c["new"], None)+ assert resolve_indexed_commit(path / "absent", None) == (None, None)+++def test_the_server_freshness_reads_the_same_commit(repo) -> None:+ from repowise.server.mcp_server._meta import resolve_indexed_commit as meta_resolve++ path, c = repo+ _state(path, c["new"])+ assert meta_resolve(c["old"], str(path)) == c["old"]+ assert meta_resolve(c["side"], str(path)) is None+ # Hosted: no checkout, so the row is all there is.+ assert meta_resolve(c["side"], None) == c["side"]+++def test_only_a_definite_ancestry_answer_is_cached(monkeypatch) -> None:+ from repowise.core import git_refs+ from repowise.core.workspace import update++ monkeypatch.setattr(update, "_ancestry_cache", {})+ answers = iter([None, None, True]) # a timeout both ways, then git answers+ calls: list[tuple[str, str]] = []++ def _is_ancestor(_repo, older, newer):+ calls.append((older, newer))+ return next(answers)++ monkeypatch.setattr(git_refs, "is_ancestor", _is_ancestor)+ assert update._older_commit("r", "a", "b") is None+ assert update._older_commit("r", "a", "b") == "a"+ assert update._older_commit("r", "a", "b") == "a"+ assert len(calls) == 3