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(update): keep the index freshness stamp current on no-op syncs (#652)
Raghav Chamadiya2796fb6011a7
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex a3251707c..f9170d76a 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -50,6 +50,7 @@ from .persistence import (_persist_index_only_update,_persist_partial_health,_run_full_health_rescore,+ stamp_head_commit,)from .reporting import (JsonProgressEmitter,@@ -371,6 +372,10 @@ def update_command(console.print("[green]Already up to date.[/green]")if prev_config_fp is None and not dry_run:save_state(repo_path, {**state, "config_fingerprint": curr_config_fp})+ # Self-heal a row a pre-fix run left behind: state.json can already be+ # current here while the DB head_commit is still the last full index.+ if not dry_run:+ stamp_head_commit(repo_path, head)if emitter is not None:emitter.done(ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - start@@ -486,6 +491,9 @@ def update_command(repo_path,{**state, "last_sync_commit": head, "config_fingerprint": curr_config_fp},)+ # Keep the DB freshness stamp in lockstep with state.json: the server's+ # /repos endpoint reads head_commit from the row, not the state file.+ stamp_head_commit(repo_path, head)if emitter is not None:emitter.done(ok=True, pages_generated=0, cost_usd=0.0, duration_s=time.monotonic() - startdiff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 86a43e7fa..fc924d946 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -98,6 +98,46 @@ async def _persist_incremental_commits(session: Any, repo_id: str, repo_path: Anawait persist_incremental_commits(session, repo_id, repo_path)+def stamp_head_commit(repo_path: Any, head: str | None) -> None:+ """Advance the persisted ``repositories.head_commit`` to *head*.++ The "no changed files" and "already up to date" fast paths in+ ``update_command`` write ``state.json`` and return without touching the DB.+ But the server's ``/repos`` endpoint and the MCP ``_meta`` freshness check+ read the indexed commit from the ``repositories`` row, not from+ ``state.json`` — so skipping this write pinned the freshness signal at the+ last full index, keeping "index behind checkout" stuck after a successful+ update. Keep the DB stamp in lockstep with ``state.json``. Also self-heals+ a row left stale by a pre-fix run: any later update re-stamps it.+ """+ if not head:+ return++ async def _stamp() -> None:+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ await upsert_repository(+ session,+ name=Path(repo_path).name,+ local_path=str(repo_path),+ head_commit=head,+ )++ run_async(_stamp())++def _persist_index_only_update(repo_path: Any,graph_builder: Any,diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.pyindex 17eba6911..f872d30a8 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py@@ -23,7 +23,11 @@ def _workspace_update(Takes a resolved :class:`CommandTarget` so the caller has full controlover how the workspace was located (auto-detected vs explicit flag)."""- from repowise.core.workspace import check_repo_staleness, update_workspace+ from repowise.core.workspace import (+ check_repo_staleness,+ reconcile_repo_head_commit,+ update_workspace,+ )start = time.monotonic()ws_root = target.ws_root@@ -40,12 +44,13 @@ def _workspace_update(stale_count = 0up_to_date_count = 0+ up_to_date_repos: list[tuple[Path, str]] = []for entry in ws_config.repos:if repo_alias and entry.alias != repo_alias:continueabs_path = (ws_root / entry.path).resolve()stored = entry.last_commit_at_index- is_stale, _head, behind = check_repo_staleness(abs_path, stored)+ is_stale, head, behind = check_repo_staleness(abs_path, stored)indexed = (abs_path / ".repowise").is_dir()if not indexed:status = "[dim]not indexed[/dim]"@@ -59,6 +64,8 @@ def _workspace_update(stale_count += 1if indexed and not is_stale:up_to_date_count += 1+ if head:+ up_to_date_repos.append((abs_path, head))if not verbose:continueconsole.print(f" {entry.alias:<20} {status}")@@ -68,6 +75,21 @@ def _workspace_update(console.print()+ # Reconcile the DB freshness stamp for up-to-date repos even when nothing+ # needs regenerating. Staleness above is measured against the workspace+ # config's last_commit_at_index, but the server's /api/repos endpoint and+ # the MCP _meta check read repositories.head_commit from each repo's DB — a+ # row left behind by an older build keeps "index behind checkout" stuck+ # here, since the all-up-to-date path returns without calling+ # update_workspace. reconcile_repo_head_commit only writes on drift.+ if not dry_run and up_to_date_repos:++ async def _reconcile_up_to_date() -> None:+ for repo_path, head in up_to_date_repos:+ await reconcile_repo_head_commit(repo_path, head)++ run_async(_reconcile_up_to_date())+if stale_count == 0:console.print("[green]All repos are up to date.[/green]")if not dry_run:diff --git a/packages/core/src/repowise/core/workspace/__init__.py b/packages/core/src/repowise/core/workspace/__init__.pyindex 4c5ec8242..f49d4f8cf 100644--- a/packages/core/src/repowise/core/workspace/__init__.py+++ b/packages/core/src/repowise/core/workspace/__init__.py@@ -27,6 +27,7 @@ from .registry import (from .update import (RepoUpdateResult,check_repo_staleness,+ reconcile_repo_head_commit,run_cross_repo_hooks,update_single_repo_index,update_workspace,@@ -96,6 +97,7 @@ __all__ = [# Update"RepoUpdateResult","check_repo_staleness",+ "reconcile_repo_head_commit","run_cross_repo_hooks","update_single_repo_index","update_workspace",diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex 867924c03..077e9b0c1 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -257,6 +257,50 @@ def check_repo_staleness(return True, current_head, behind+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*.++ The "up to date" skip and the no-relevant-changes incremental path bump+ ``state.json``'s ``last_sync_commit`` but never re-run the DB persistence+ that stamps the ``repositories`` row. The server reads both the indexed+ commit (``/api/repos``, MCP ``_meta``) and the "indexed at" time (the health+ overview's ``last_indexed_at`` fallback) from that row, not from+ ``state.json`` — so an un-reconciled row keeps the "index behind checkout"+ signal stuck and the freshness timestamp frozen at the last full index even+ after a successful update.++ Stamps ``head_commit`` only on drift (avoids needless churn), but always+ advances ``updated_at`` so the freshness time reflects the latest+ sync-check — a routine ``repowise update`` that finds nothing to do still+ counts as "verified current now". A no-op when the repo row is absent.+ """+ if not head or not (repo_path / ".repowise" / "wiki.db").is_file():+ return+ from ..persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ )+ from ..persistence.crud import get_repository_by_path+ from ..persistence.database import resolve_db_url++ url = resolve_db_url(repo_path)+ engine = create_engine(url)+ try:+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is not None:+ if repo.head_commit != head:+ repo.head_commit = head+ repo.updated_at = datetime.now(timezone.utc)+ await session.flush()+ finally:+ await engine.dispose()++# ---------------------------------------------------------------------------# Single-repo update (index-only)# ---------------------------------------------------------------------------@@ -542,6 +586,10 @@ async def update_workspace()if not is_stale:+ # Nothing to regenerate, but the DB freshness stamp can still be+ # behind (e.g. a row left drifted by a pre-fix run). Reconcile it so+ # the server's /api/repos no longer reports "index behind checkout".+ await reconcile_repo_head_commit(abs_path, current_head)results.append(RepoUpdateResult(alias=entry.alias,@@ -641,6 +689,11 @@ async def update_workspace(_json.dumps(state, indent=2),encoding="utf-8",)+ # Keep the DB freshness stamp in lockstep with last_sync_commit.+ # The no-relevant-changes incremental path returns updated=True+ # without re-running DB persistence, so the row would otherwise+ # lag HEAD; a no-op when persistence already stamped it.+ await reconcile_repo_head_commit(path, new_head)# Update workspace config entryif result.updated:diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex d245fd739..4f8ba8b7b 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -76,6 +76,43 @@ def _read_live_head(local_path: str | None) -> str | None:return head or None+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 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).+ """+ return read_state_sync_commit(local_path) or head_commit++def freshness_from_repo(repository: Any | None) -> dict[str, Any]:"""Return a minimal freshness dict for the given Repository row.@@ -112,11 +149,15 @@ def freshness_from_repo(repository: Any | None) -> dict[str, Any]:age_days = max(0, (datetime.now(timezone.utc) - ua).days)out["index_age_days"] = age_days- indexed_full = getattr(repository, "head_commit", None) or None+ local_path = getattr(repository, "local_path", None)+ # Prefer state.json's last_sync_commit over a possibly-stale DB head_commit+ # so freshness self-heals on read (see resolve_indexed_commit).+ indexed_full = resolve_indexed_commit(+ getattr(repository, "head_commit", None) or None, local_path+ )if indexed_full:out["indexed_commit"] = indexed_full[:12] if isinstance(indexed_full, str) else indexed_full- local_path = getattr(repository, "local_path", None)live_full = _read_live_head(local_path)if live_full and indexed_full:diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.pyindex 33d5edecb..560953e10 100644--- a/packages/server/src/repowise/server/routers/code_health.py+++ b/packages/server/src/repowise/server/routers/code_health.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport jsonimport re+from datetime import datetimefrom typing import Anyfrom fastapi import APIRouter, Depends, HTTPException, Query, Response@@ -38,6 +39,7 @@ from repowise.core.analysis.health.trends import (from repowise.core.persistence import crudfrom repowise.core.persistence.models import WikiSymbolfrom repowise.server.deps import get_db_session, verify_api_key+from repowise.server.mcp_server._meta import resolve_indexed_commitrouter = APIRouter(tags=["code-health"],@@ -270,6 +272,25 @@ def _biomarker_breakdown(findings: list[Any]) -> list[dict]:return rows+def _resolve_last_indexed_at(+ snapshot_taken_at: datetime | None, repo_updated_at: datetime | None+) -> str | None:+ """Newest "index brought current" time as an ISO string, or ``None``.++ ``last_indexed_at`` should track the last time the index was synced to the+ checkout, not just the last health snapshot. A no-change ``repowise update``+ advances ``repositories.updated_at`` but takes no new snapshot, so a+ snapshot-only value would report the index as hours stale right after a+ refresh. Prefer whichever timestamp is newer (mirrors the overview router's+ sync fallback). Both inputs come from the same DB, so their tz-awareness+ matches and the comparison is safe.+ """+ newest = snapshot_taken_at+ if repo_updated_at is not None and (newest is None or repo_updated_at > newest):+ newest = repo_updated_at+ return newest.isoformat() if newest else None++@router.get("/api/repos/{repo_id}/health/overview")async def health_overview(repo_id: str,@@ -288,11 +309,13 @@ async def health_overview(# Pull hotspot_health from the latest snapshot (KPIs aren't recomputed# on every overview hit — the snapshot is authoritative).hotspot_health: float | None = None- last_indexed_at: str | None = None+ snapshot_taken_at = Noneif snapshots:latest = snapshots[-1]hotspot_health = round(float(latest.hotspot_health), 2)- last_indexed_at = latest.taken_at.isoformat() if latest.taken_at else None+ snapshot_taken_at = latest.taken_at++ last_indexed_at = _resolve_last_indexed_at(snapshot_taken_at, repo.updated_at)metric_dicts = [_metric_to_dict(m) for m in metrics]@@ -329,7 +352,10 @@ async def health_overview("biomarkers": _biomarker_breakdown(findings),"meta": {"last_indexed_at": last_indexed_at,- "head_commit": repo.head_commit,+ # 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),"snapshot_count": len(snapshots),},}diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex 00ca33fd8..e57729281 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -91,6 +91,16 @@ async def list_repos(repos.sort(key=lambda r: r.updated_at or r.created_at, reverse=True)responses = [RepoResponse.from_orm(r) for r in repos]+ # Self-heal the freshness stamp on read: prefer each repo's state.json+ # last_sync_commit over a possibly-stale DB head_commit, so a row left+ # un-stamped by an older build doesn't make the extension report "index+ # behind checkout". The DB row is repaired for good on the next update.+ from repowise.server.mcp_server._meta import resolve_indexed_commit++ for resp in responses:+ if resp.local_path:+ resp.head_commit = resolve_indexed_commit(resp.head_commit, resp.local_path)+# Augment with workspace metadata. We do this in a second pass (rather# than during from_orm) because the workspace context lives on# app.state, not on the Repository row.diff --git a/tests/unit/cli/test_freshness_stamp_fixes.py b/tests/unit/cli/test_freshness_stamp_fixes.pyindex 70bc3a1a5..a70a22881 100644--- a/tests/unit/cli/test_freshness_stamp_fixes.py+++ b/tests/unit/cli/test_freshness_stamp_fixes.py@@ -9,6 +9,7 @@ Covers:from __future__ import annotationsimport types+from datetime import UTCfrom pathlib import Pathfrom repowise.cli.commands.doctor_cmd import _claude_md_stamp_status@@ -142,3 +143,111 @@ def test_advise_stamp_skips_when_claude_md_disabled(tmp_path, monkeypatch):)doctor_cmd._advise_claude_md_stamp(tmp_path, {"last_sync_commit": "d05bc6e8" + "0" * 32})assert printed == []+++# ---------------------------------------------------------------------------+# 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+# extension badge / MCP staleness signal is correct on the first read without+# requiring a `repowise update` first.+# ---------------------------------------------------------------------------+++def _write_state(repo_path: Path, last_sync_commit: str | None) -> None:+ import json++ dot = repo_path / ".repowise"+ dot.mkdir(parents=True, exist_ok=True)+ payload = {} if last_sync_commit is None else {"last_sync_commit": last_sync_commit}+ (dot / "state.json").write_text(json.dumps(payload), encoding="utf-8")+++def test_resolve_indexed_commit_prefers_state_json(tmp_path):+ from repowise.server.mcp_server._meta import resolve_indexed_commit++ fresh = "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+++def test_resolve_indexed_commit_falls_back_to_db_without_state(tmp_path):+ from repowise.server.mcp_server._meta import resolve_indexed_commit++ stale_db = "abc1234" + "0" * 33+ # No .repowise/state.json (hosted/ephemeral index) — keep the DB value.+ assert resolve_indexed_commit(stale_db, str(tmp_path)) == stale_db+++def test_resolve_indexed_commit_none_when_nothing_known(tmp_path):+ from repowise.server.mcp_server._meta import resolve_indexed_commit++ assert resolve_indexed_commit(None, str(tmp_path)) is None+ # An empty/malformed state.json must not shadow the DB value with "".+ _write_state(tmp_path, None)+ assert resolve_indexed_commit("abc1234" + "0" * 33, str(tmp_path)) == "abc1234" + "0" * 33+++def test_freshness_self_heals_and_silences_false_stale(tmp_path):+ import types++ from repowise.server.mcp_server._meta import freshness_from_repo++ 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.+ 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,+ local_path=str(tmp_path),+ updated_at=None,+ )+ out = freshness_from_repo(repo)++ assert out["indexed_commit"] == head[:12]+ # HEAD matches the (self-healed) indexed commit → no false "behind" warning.+ assert "stale_warning" not in out+ assert "live_head" not in out+++# ---------------------------------------------------------------------------+# "Indexed at" tracks the last sync, not just the last health snapshot: a+# no-change update advances repositories.updated_at without a new snapshot, so+# the freshness time must not read hours-stale right after a refresh.+# ---------------------------------------------------------------------------+++def test_last_indexed_at_prefers_newer_repo_update():+ from datetime import datetime++ from repowise.server.routers.code_health import _resolve_last_indexed_at++ snapshot = datetime(2026, 7, 2, 11, 48, tzinfo=UTC)+ refreshed = datetime(2026, 7, 2, 14, 25, tzinfo=UTC)+ # A no-change `repowise update` bumped updated_at past the last snapshot.+ assert _resolve_last_indexed_at(snapshot, refreshed) == refreshed.isoformat()+++def test_last_indexed_at_keeps_snapshot_when_newer():+ from datetime import datetime++ from repowise.server.routers.code_health import _resolve_last_indexed_at++ snapshot = datetime(2026, 7, 2, 14, 25, tzinfo=UTC)+ older_update = datetime(2026, 7, 2, 11, 48, tzinfo=UTC)+ assert _resolve_last_indexed_at(snapshot, older_update) == snapshot.isoformat()+++def test_last_indexed_at_handles_missing_values():+ from datetime import datetime++ from repowise.server.routers.code_health import _resolve_last_indexed_at++ only_update = datetime(2026, 7, 2, 14, 25, tzinfo=UTC)+ assert _resolve_last_indexed_at(None, only_update) == only_update.isoformat()+ assert _resolve_last_indexed_at(only_update, None) == only_update.isoformat()+ assert _resolve_last_indexed_at(None, None) is None