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): stop a failed HEAD read stranding a store's sync pointer (#2446)
Raghav Chamadiya0a258995d602
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 8ce5d23f5..5c1f2d03a 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -783,10 +783,15 @@ def run_update(resolved_index_only = _resolve_index_only_mode(index_only=index_only, docs_flag=docs_flag, state=state)+ # ``or``, not ``get``'s default: a repo that has never had a docs pass+ # carries ``last_docs_commit`` as an explicit null rather than omitting it,+ # and a default only applies to a missing key. Reading it with a default+ # handed back that null and the update aborted with "No previous sync+ # found" against a store holding a perfectly good ``last_sync_commit``.base_ref = since or (state.get("last_sync_commit")if resolved_index_only- else state.get("last_docs_commit", state.get("last_sync_commit"))+ else state.get("last_docs_commit") or state.get("last_sync_commit"))head = get_head_commit(repo_path)@@ -1603,7 +1608,8 @@ def run_update(decay_paths=affected.decay_only,degraded=degraded,)- state["last_docs_commit"] = head+ if head:+ state["last_docs_commit"] = headconsole.print(f" [green]✓[/green] Re-rendered [bold]{len(det_pages)}[/bold] ""wiki pages from structure"@@ -2376,8 +2382,13 @@ def run_update(console.print(f"[yellow]Knowledge-graph export skipped: {exc}[/yellow]")degraded.append(f"Knowledge-graph export: {exc}")- state["last_sync_commit"] = head- state["last_docs_commit"] = head+ # Never write a null pointer. ``get_head_commit`` returns None whenever+ # ``git rev-parse HEAD`` fails, and erasing a good baseline strands the+ # store: the next update reads the null as its base and refuses to run.+ # #1507 guarded the same write in ``generate``; these are the rest of it.+ if head:+ state["last_sync_commit"] = head+ state["last_docs_commit"] = head# Real DB total, not an accumulation: regeneration upserts existing pages,# so adding len(generated_pages) every run inflated the count forever.state["total_pages"] = db_total_pagesdiff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 002939765..71c3698a1 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -26,6 +26,20 @@ from .incremental import _build_repo_graphlog = structlog.get_logger(__name__)++def backfill_docs_pointer(new_state: dict, state: dict) -> None:+ """Carry ``last_sync_commit`` onto a docs pointer that never got one.++ Falsy, not absent. A store that has never had a docs pass carries+ ``last_docs_commit`` as an explicit null, so a membership test reads it as+ "already set" and the repair never runs -- which is what left such a store+ failing every update with "No previous sync found" (#1507 fixed the same+ confusion on the write side, in ``generate``).+ """+ if not state.get("last_docs_commit") and state.get("last_sync_commit"):+ new_state["last_docs_commit"] = state["last_sync_commit"]++def _repair_module_attribution(repo_path: Path) -> int:"""Re-derive every health row's ``module`` from the repo layout on disk.@@ -500,8 +514,7 @@ def _persist_index_only_update("[yellow]Some data for this commit range was not persisted; ""the next update will re-cover it.[/yellow]")- if "last_docs_commit" not in state and "last_sync_commit" in state:- new_state["last_docs_commit"] = state["last_sync_commit"]+ backfill_docs_pointer(new_state, state)if knowledge_graph_result is not None:try:from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_jsondiff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex a94d88650..78b2834d2 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -939,7 +939,9 @@ async def update_workspace(with suppress(Exception):state = _json.loads(state_path.read_text(encoding="utf-8"))- if "last_docs_commit" not in state and "last_sync_commit" in state:+ # Falsy, not absent: an explicit null survives a+ # membership test and strands the pointer permanently.+ if not state.get("last_docs_commit") and state.get("last_sync_commit"):state["last_docs_commit"] = state["last_sync_commit"]state["last_sync_commit"] = new_headdiff --git a/tests/unit/cli/test_update_null_docs_commit.py b/tests/unit/cli/test_update_null_docs_commit.pynew file mode 100644index 000000000..b20d72288--- /dev/null+++ b/tests/unit/cli/test_update_null_docs_commit.py@@ -0,0 +1,104 @@+"""A null pointer in ``state.json`` must not strand the store.++``get_head_commit`` returns ``None`` whenever ``git rev-parse HEAD`` fails, and+``update`` wrote that straight onto both pointers. The next run then read the+null as its base and refused with "No previous sync found" against a store that+had indexed fine. #1507 guarded the same write in ``generate``; ``update`` kept+it.++The null is also unrecoverable once written, because both readers test for an+absent key rather than a falsy value: the base-ref lookup used ``dict.get``'s+default, which only applies when the key is missing, and the migration that+backfills the docs pointer guarded on ``not in state``.+"""++from __future__ import annotations++import subprocess+from pathlib import Path++import pytest++from repowise.cli.commands.update_cmd import persistence as update_persistence+++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 repo(tmp_path: Path) -> Path:+ path = tmp_path / "repo"+ path.mkdir()+ _git(path, "init", "-q")+ _git(path, "config", "user.email", "[email protected]")+ _git(path, "config", "user.name", "t")+ (path / "a.py").write_text("x = 1\n", encoding="utf-8")+ _git(path, "add", "-A")+ _git(path, "commit", "-qm", "first")+ return path+++def test_a_null_docs_commit_is_backfilled_from_the_sync_pointer() -> None:+ """The real migration repairs a null, not only a missing key.++ This is the path that should have healed a store on its next update and+ instead left it stuck: ``"last_docs_commit" not in state`` is False when+ the key is present and null, so the repair never ran.+ """+ state = {"last_sync_commit": "4b13948", "last_docs_commit": None}+ new_state: dict = {}++ update_persistence.backfill_docs_pointer(new_state, state)++ assert new_state["last_docs_commit"] == "4b13948"+++def test_a_real_docs_commit_is_left_alone() -> None:+ state = {"last_sync_commit": "4b13948", "last_docs_commit": "09b9737"}+ new_state: dict = {}++ update_persistence.backfill_docs_pointer(new_state, state)++ assert "last_docs_commit" not in new_state+++def test_an_unindexed_store_gets_no_pointer() -> None:+ new_state: dict = {}++ update_persistence.backfill_docs_pointer(new_state, {})++ assert new_state == {}+++def test_update_recovers_a_store_whose_docs_pointer_is_null(repo: Path, monkeypatch) -> None:+ """End to end: a store carrying an explicit null still knows its base.++ HEAD has to be ahead of the pointer, or ``update`` short-circuits on+ "Already up to date" long before it reads a base ref.+ """+ from click.testing import CliRunner++ from repowise.cli.helpers import save_state+ from repowise.cli.main import cli++ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")+ (repo / ".repowise").mkdir()+ save_state(+ repo,+ {+ "last_sync_commit": _git(repo, "rev-parse", "HEAD"),+ "last_docs_commit": None,+ "docs_mode": "llm",+ "store_format_version": 2,+ },+ )+ (repo / "b.py").write_text("y = 2", encoding="utf-8")+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", "second")++ result = CliRunner().invoke(cli, ["update", "--no-workspace", "--docs", str(repo)])++ assert "No previous sync found" not in (result.output or "")