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(freshness): keep CLAUDE.md stamp and indexed commit current (#524)

Raghav Chamadiya8e38219b63a4
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
index c1701558a..21ce29bf1 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
@@ -23,6 +23,61 @@ def _check(name: str, ok: bool, detail: str = "") -> tuple[str, str, str]:
return (name, status, detail)
+def _claude_md_stamp_status(repo_path, state: dict) -> tuple[bool, str] | None:
+ """Compare the managed CLAUDE.md "Last indexed" commit to state.json.
+
+ Returns ``(ok, detail)`` or ``None`` to skip the check (no CLAUDE.md, no
+ stamp, or no synced commit yet). After any index/update the stamp and
+ ``state.json``'s ``last_sync_commit`` should agree; a mismatch means
+ editor-file regeneration stopped (e.g. the workspace-update refresh bug or
+ ``editor_files.claude_md`` disabled), so the injected "Last indexed" line is
+ stale and trains agents to distrust the index. Compared against the synced
+ commit, not live HEAD, so being a few commits behind HEAD is not flagged.
+ """
+ import re
+
+ claude_md = repo_path / ".claude" / "CLAUDE.md"
+ try:
+ text = claude_md.read_text(encoding="utf-8")
+ except OSError:
+ return None
+ m = re.search(r"Last indexed:.*?\(commit\s+([0-9a-fA-F]{7,})\)", text)
+ if not m:
+ # No stamp, or a too-short/abbreviated sha we can't compare safely.
+ return None
+ stamp = m.group(1).lower()
+ synced = ((state or {}).get("last_sync_commit") or "").lower()
+ if not synced:
+ return None
+ if synced.startswith(stamp) or stamp.startswith(synced):
+ return (True, f"in sync at {stamp}")
+ return (
+ False,
+ f"stamp {stamp} != index {synced[:8]} — run `repowise update` "
+ "or `repowise claude-md` to refresh",
+ )
+
+
+def _advise_claude_md_stamp(repo_path, state: dict) -> None:
+ """Print an advisory line when the CLAUDE.md stamp lags the index.
+
+ Advisory only (never flips the doctor's pass/fail): a stamp can briefly lag
+ when a commit lands mid-update, which self-heals on the next sync. Skipped
+ entirely when ``editor_files.claude_md`` is disabled, since there is nothing
+ to refresh and the advice would be un-actionable.
+ """
+ from repowise.cli.editor_integrations.claude import _claude_md_enabled
+
+ if not _claude_md_enabled(repo_path):
+ return
+ status = _claude_md_stamp_status(repo_path, state)
+ if status is None:
+ return
+ ok, detail = status
+ if not ok:
+ console.print(f"[yellow]CLAUDE.md stamp drift:[/yellow] {detail}")
+
+
async def _decision_vector_ids(session, repository_id: str) -> set[str]:
"""Vector-store ids for this repo's decision records.
@@ -182,6 +237,7 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:
config_detail = "All required API keys configured" if config_ok else "; ".join(config_warnings)
checks.append(_check("Provider config", config_ok, config_detail))
+
# 7. Stale page count
stale_count = 0
if db_ok and page_count > 0:
@@ -417,6 +473,12 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:
table.add_row(name, status, detail)
console.print(table)
+ # CLAUDE.md freshness stamp — advisory, never fails the run. The managed
+ # ".claude/CLAUDE.md" block stamps the commit it was generated against; if
+ # editor-file regeneration stops, the stamp freezes while the index moves
+ # on and agents reading the stale "Last indexed" line distrust the tools.
+ _advise_claude_md_stamp(repo_path, state)
+
all_ok = all("[green]OK[/green]" in status for _, status, _ in checks)
if all_ok:
console.print("[bold green]All checks passed![/bold green]")
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
index e3013147a..17eba6911 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py
@@ -161,17 +161,27 @@ def _refresh_workspace_editor_project_files(
repo_filter: str | None,
agents_md: bool | None,
) -> None:
- """Refresh workspace repo editor files for explicit per-run overrides."""
-
- if agents_md is None:
- return
-
+ """Re-stamp each workspace repo's editor files (CLAUDE.md / AGENTS.md).
+
+ Runs on every workspace update so a repo's ``.claude/CLAUDE.md`` "Last
+ indexed" stamp tracks the freshly synced index. Each integration decides
+ whether to write from the repo's own config (CLAUDE.md defaults on), so we
+ pass ``options=None`` for the common case.
+
+ ``agents_md`` is only a per-run override for AGENTS.md generation; when it
+ is ``None`` each integration falls back to config. It must NOT gate the
+ whole refresh: doing so froze the CLAUDE.md stamp for every workspace user
+ who never passed ``--agents-md`` (the default), making the index look stale
+ long after it was current. Mirrors the single-repo update path.
+ """
from repowise.cli.editor_integrations.defaults import get_default_project_file_overrides
from repowise.cli.editor_setup import EditorSetupOptions, refresh_editor_project_files
- options = EditorSetupOptions(
- project_file_overrides=get_default_project_file_overrides(agents_md=agents_md),
- )
+ options: EditorSetupOptions | None = None
+ if agents_md is not None:
+ options = EditorSetupOptions(
+ project_file_overrides=get_default_project_file_overrides(agents_md=agents_md),
+ )
for entry in ws_config.repos:
if repo_filter and entry.alias != repo_filter:
continue
diff --git a/packages/core/src/repowise/core/persistence/crud/repository.py b/packages/core/src/repowise/core/persistence/crud/repository.py
index ef148c908..1d380ec3e 100644
--- a/packages/core/src/repowise/core/persistence/crud/repository.py
+++ b/packages/core/src/repowise/core/persistence/crud/repository.py
@@ -7,6 +7,7 @@ every public name, so existing imports are unaffected.
from __future__ import annotations
import json
+from pathlib import Path
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -34,14 +35,25 @@ async def upsert_repository(
url: str = "",
default_branch: str = "main",
settings: dict | None = None,
+ head_commit: str | None = None,
) -> Repository:
"""Create or update a repository record.
Lookup is by ``local_path`` (the canonical key for local repositories).
+
+ ``head_commit`` records the git commit the index was built against — the
+ value the MCP ``_meta`` freshness check compares to the live HEAD. Callers
+ that already know the synced commit may pass it; otherwise it is read from
+ ``local_path``'s git HEAD via plain file I/O (no ``git`` subprocess). This
+ runs at the start of every index/update, so the stored commit tracks each
+ sync and the MCP staleness signal stays calibrated instead of being NULL
+ forever (which silently disabled the preferred HEAD-vs-index comparison).
"""
result = await session.execute(select(Repository).where(Repository.local_path == local_path))
repo = result.scalar_one_or_none()
+ resolved_head = head_commit or _read_head_commit(local_path)
+
if repo is None:
repo = Repository(
id=_new_uuid(),
@@ -50,6 +62,7 @@ async def upsert_repository(
url=url,
default_branch=default_branch,
settings_json=json.dumps(settings or {}),
+ head_commit=resolved_head,
)
session.add(repo)
else:
@@ -58,12 +71,55 @@ async def upsert_repository(
repo.default_branch = default_branch
if settings is not None:
repo.settings_json = json.dumps(settings)
+ # Only advance the stamp when we could read a real commit; never blank
+ # out a previously recorded one (e.g. a transient non-checkout path).
+ if resolved_head:
+ repo.head_commit = resolved_head
repo.updated_at = _now_utc()
await session.flush()
return repo
+def _read_head_commit(local_path: str) -> str | None:
+ """Return the repo's current git HEAD SHA via plain file I/O, or None.
+
+ Dependency-free (no ``git`` binary, no gitpython): parse ``.git/HEAD`` and
+ follow at most one ref, falling back to ``packed-refs``. Returns ``None``
+ when *local_path* is not a git checkout (hosted/ephemeral indexes) or the
+ ref can't be resolved. Mirrors the MCP ``_meta`` reader so the value we
+ write is read back the same way — keeping freshness comparisons honest.
+ """
+ try:
+ git_dir = Path(local_path) / ".git"
+ # Linked worktrees use a ``.git`` *file* (gitdir pointer), not a dir;
+ # treated as non-git here on purpose so this stays in lockstep with the
+ # MCP ``_meta._read_live_head`` reader (same is_dir() guard), keeping
+ # the written commit and the read-back comparison symmetric.
+ if not git_dir.is_dir():
+ return None
+ head = (git_dir / "HEAD").read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+ if head.startswith("ref: "):
+ ref_rel = head[5:].strip()
+ try:
+ return (git_dir / ref_rel).read_text(encoding="utf-8").strip() or None
+ except OSError:
+ pass
+ try:
+ for raw in (git_dir / "packed-refs").read_text(encoding="utf-8").splitlines():
+ if raw.startswith("#") or raw.startswith("^"):
+ continue
+ sha, _, name = raw.partition(" ")
+ if name.strip() == ref_rel:
+ return sha.strip() or None
+ except OSError:
+ return None
+ return None
+ return head or None
+
+
async def get_repository(session: AsyncSession, repo_id: str) -> Repository | None:
"""Return a Repository by primary key, or None."""
return await session.get(Repository, repo_id)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_repos.py b/packages/server/src/repowise/server/mcp_server/tool_repos.py
index b2c8ed128..15e3672e0 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_repos.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_repos.py
@@ -11,6 +11,23 @@ from repowise.server.mcp_server._meta import build_meta as _build_meta
def _workspace_repos(registry: Any) -> list[dict[str, Any]]:
ws_config = getattr(registry, "ws_config", None)
+ # The registry's ws_config is a snapshot taken when this (long-lived) MCP
+ # server started. A `repowise update` that runs later rewrites the
+ # workspace config's per-repo ``indexed_at`` / ``last_commit_at_index``,
+ # but the in-process copy would keep reporting the startup values, making
+ # the index look stale long after it was synced. Re-read from disk so the
+ # freshness fields track updates without a server restart. Best-effort:
+ # fall back to the cached snapshot if the reload fails.
+ workspace_root = getattr(registry, "workspace_root", None)
+ if workspace_root is not None:
+ try:
+ from repowise.core.workspace import WorkspaceConfig
+
+ fresh = WorkspaceConfig.load(workspace_root)
+ if getattr(fresh, "repos", None):
+ ws_config = fresh
+ except Exception:
+ pass # never fail discovery on a config reload hiccup (missing/locked file)
default_alias = registry.get_default_alias()
if ws_config is None:
diff --git a/tests/unit/cli/test_freshness_stamp_fixes.py b/tests/unit/cli/test_freshness_stamp_fixes.py
new file mode 100644
index 000000000..70bc3a1a5
--- /dev/null
+++ b/tests/unit/cli/test_freshness_stamp_fixes.py
@@ -0,0 +1,144 @@
+"""Regression tests for the index-freshness stamp fixes.
+
+Covers:
+ * F1 - ``repowise update --workspace`` re-stamps editor files even without
+ ``--agents-md`` (the early-return that froze CLAUDE.md for workspace users).
+ * F4 - the doctor CLAUDE.md-stamp drift check.
+"""
+
+from __future__ import annotations
+
+import types
+from pathlib import Path
+
+from repowise.cli.commands.doctor_cmd import _claude_md_stamp_status
+
+# ---------------------------------------------------------------------------
+# F1 - workspace editor refresh runs regardless of the agents_md flag
+# ---------------------------------------------------------------------------
+
+
+def _fake_ws_config(*aliases: str):
+ repos = [types.SimpleNamespace(alias=a, path=a) for a in aliases]
+ return types.SimpleNamespace(repos=repos)
+
+
+def test_workspace_refresh_runs_when_agents_md_none(tmp_path, monkeypatch):
+ from repowise.cli.commands.update_cmd import workspace as ws_mod
+
+ # Two indexed repos + one un-indexed (no .repowise) which must be skipped.
+ for alias in ("api", "web"):
+ (tmp_path / alias / ".repowise").mkdir(parents=True)
+ (tmp_path / "ghost").mkdir()
+
+ refreshed: list[str] = []
+ monkeypatch.setattr(
+ "repowise.cli.editor_setup.refresh_editor_project_files",
+ lambda console, repo_path, *, options=None: refreshed.append(Path(repo_path).name),
+ )
+
+ ws_mod._refresh_workspace_editor_project_files(
+ ws_root=tmp_path,
+ ws_config=_fake_ws_config("api", "web", "ghost"),
+ repo_filter=None,
+ agents_md=None, # the default path that used to early-return and skip all
+ )
+
+ assert sorted(refreshed) == ["api", "web"]
+
+
+def test_workspace_refresh_respects_repo_filter(tmp_path, monkeypatch):
+ from repowise.cli.commands.update_cmd import workspace as ws_mod
+
+ for alias in ("api", "web"):
+ (tmp_path / alias / ".repowise").mkdir(parents=True)
+
+ refreshed: list[str] = []
+ monkeypatch.setattr(
+ "repowise.cli.editor_setup.refresh_editor_project_files",
+ lambda console, repo_path, *, options=None: refreshed.append(Path(repo_path).name),
+ )
+
+ ws_mod._refresh_workspace_editor_project_files(
+ ws_root=tmp_path,
+ ws_config=_fake_ws_config("api", "web"),
+ repo_filter="web",
+ agents_md=None,
+ )
+
+ assert refreshed == ["web"]
+
+
+# ---------------------------------------------------------------------------
+# F4 - doctor CLAUDE.md stamp drift check
+# ---------------------------------------------------------------------------
+
+
+def _write_claude_md(repo_path: Path, commit: str) -> None:
+ dot = repo_path / ".claude"
+ dot.mkdir(parents=True, exist_ok=True)
+ (dot / "CLAUDE.md").write_text(
+ f"# CLAUDE.md\n\nLast indexed: 2026-06-07 (commit {commit}). Confidence: 100%.\n",
+ encoding="utf-8",
+ )
+
+
+def test_stamp_status_in_sync(tmp_path):
+ _write_claude_md(tmp_path, "abc1234")
+ ok, detail = _claude_md_stamp_status(tmp_path, {"last_sync_commit": "abc1234def567"})
+ assert ok is True
+ assert "in sync" in detail
+
+
+def test_stamp_status_drift(tmp_path):
+ _write_claude_md(tmp_path, "1c67e0a9")
+ ok, detail = _claude_md_stamp_status(tmp_path, {"last_sync_commit": "d05bc6e8" + "0" * 32})
+ assert ok is False
+ assert "repowise update" in detail
+
+
+def test_stamp_status_skips_without_claude_md(tmp_path):
+ assert _claude_md_stamp_status(tmp_path, {"last_sync_commit": "abc1234"}) is None
+
+
+def test_stamp_status_skips_without_synced_commit(tmp_path):
+ _write_claude_md(tmp_path, "abc1234")
+ assert _claude_md_stamp_status(tmp_path, {}) is None
+
+
+def test_stamp_status_ignores_abbreviated_stamp(tmp_path):
+ # A too-short (<7) sha can't be compared safely, so skip rather than guess.
+ _write_claude_md(tmp_path, "abc")
+ assert _claude_md_stamp_status(tmp_path, {"last_sync_commit": "abcdef0123456"}) is None
+
+
+def test_advise_stamp_prints_on_drift(tmp_path, monkeypatch):
+ from repowise.cli.commands import doctor_cmd
+
+ _write_claude_md(tmp_path, "1c67e0a9")
+ printed: list[str] = []
+ monkeypatch.setattr(
+ doctor_cmd.console,
+ "print",
+ lambda *a, **k: printed.append(" ".join(str(x) for x in a)),
+ )
+ doctor_cmd._advise_claude_md_stamp(tmp_path, {"last_sync_commit": "d05bc6e8" + "0" * 32})
+ assert any("drift" in p for p in printed)
+
+
+def test_advise_stamp_skips_when_claude_md_disabled(tmp_path, monkeypatch):
+ from repowise.cli.commands import doctor_cmd
+
+ _write_claude_md(tmp_path, "1c67e0a9")
+ (tmp_path / ".repowise").mkdir(parents=True, exist_ok=True)
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "editor_files:\n claude_md: false\n", encoding="utf-8"
+ )
+ printed: list[str] = []
+ monkeypatch.setattr(
+ doctor_cmd.console,
+ "print",
+ lambda *a, **k: printed.append(" ".join(str(x) for x in a)),
+ )
+ doctor_cmd._advise_claude_md_stamp(tmp_path, {"last_sync_commit": "d05bc6e8" + "0" * 32})
+ assert printed == []
diff --git a/tests/unit/persistence/test_repository_head_commit.py b/tests/unit/persistence/test_repository_head_commit.py
new file mode 100644
index 000000000..67dfc09e6
--- /dev/null
+++ b/tests/unit/persistence/test_repository_head_commit.py
@@ -0,0 +1,128 @@
+"""upsert_repository records the git HEAD it was indexed against (freshness).
+
+Regression for the bug where ``Repository.head_commit`` was never written, so
+the MCP ``_meta`` HEAD-vs-index staleness comparison silently never fired and
+agents fell back to the stale CLAUDE.md stamp.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+)
+from repowise.core.persistence.crud import upsert_repository
+from repowise.core.persistence.crud.repository import _read_head_commit
+
+
+def _make_git_checkout(root: Path, sha: str, *, branch: str = "main") -> None:
+ git = root / ".git"
+ (git / "refs" / "heads").mkdir(parents=True, exist_ok=True)
+ (git / "HEAD").write_text(f"ref: refs/heads/{branch}\n", encoding="utf-8")
+ (git / "refs" / "heads" / branch).write_text(sha + "\n", encoding="utf-8")
+
+
+def test_read_head_commit_resolves_ref(tmp_path: Path) -> None:
+ sha = "a" * 40
+ _make_git_checkout(tmp_path, sha)
+ assert _read_head_commit(str(tmp_path)) == sha
+
+
+def test_read_head_commit_detached(tmp_path: Path) -> None:
+ sha = "b" * 40
+ (tmp_path / ".git").mkdir()
+ (tmp_path / ".git" / "HEAD").write_text(sha + "\n", encoding="utf-8")
+ assert _read_head_commit(str(tmp_path)) == sha
+
+
+def test_read_head_commit_packed_refs(tmp_path: Path) -> None:
+ sha = "c" * 40
+ git = tmp_path / ".git"
+ git.mkdir()
+ (git / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
+ (git / "packed-refs").write_text(
+ f"# pack-refs with: peeled fully-peeled sorted\n{sha} refs/heads/main\n",
+ encoding="utf-8",
+ )
+ assert _read_head_commit(str(tmp_path)) == sha
+
+
+def test_read_head_commit_non_git_returns_none(tmp_path: Path) -> None:
+ assert _read_head_commit(str(tmp_path)) is None
+
+
+def test_read_head_commit_unresolvable_ref_returns_none(tmp_path: Path) -> None:
+ # HEAD points at a ref with no loose file and no packed-refs entry.
+ git = tmp_path / ".git"
+ git.mkdir()
+ (git / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")
+ assert _read_head_commit(str(tmp_path)) is None
+
+
+def test_read_head_commit_worktree_gitfile_returns_none(tmp_path: Path) -> None:
+ # Linked worktrees use a .git FILE; intentionally unsupported (mirrors
+ # the MCP _meta reader) so freshness stays symmetric.
+ (tmp_path / ".git").write_text("gitdir: /somewhere/.git/worktrees/wt\n", encoding="utf-8")
+ assert _read_head_commit(str(tmp_path)) is None
+
+
+async def test_upsert_repository_stamps_and_advances_head(tmp_path: Path) -> None:
+ sha1 = "1" * 40
+ _make_git_checkout(tmp_path, sha1)
+
+ engine = create_engine("sqlite+aiosqlite:///:memory:")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ try:
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name=tmp_path.name, local_path=str(tmp_path))
+ assert repo.head_commit == sha1
+
+ # HEAD moves; a re-index advances the stored commit.
+ sha2 = "2" * 40
+ (tmp_path / ".git" / "refs" / "heads" / "main").write_text(sha2 + "\n", encoding="utf-8")
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name=tmp_path.name, local_path=str(tmp_path))
+ assert repo.head_commit == sha2
+
+ # An explicit override wins over the on-disk read.
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session,
+ name=tmp_path.name,
+ local_path=str(tmp_path),
+ head_commit="3" * 40,
+ )
+ assert repo.head_commit == "3" * 40
+ finally:
+ await engine.dispose()
+
+
+async def test_upsert_repository_keeps_head_when_path_not_git(tmp_path: Path) -> None:
+ """A later upsert from a non-checkout path must not blank a known commit."""
+ sha = "d" * 40
+ _make_git_checkout(tmp_path, sha)
+
+ engine = create_engine("sqlite+aiosqlite:///:memory:")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ try:
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name="r", local_path=str(tmp_path))
+ assert repo.head_commit == sha
+
+ # Same DB row keyed by local_path, but pretend the .git vanished.
+ (tmp_path / ".git" / "HEAD").unlink()
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name="r", local_path=str(tmp_path))
+ assert repo.head_commit == sha # preserved, not nulled
+ finally:
+ await engine.dispose()