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
feat(upgrade): recommend a re-index for wikis predating the subsystem pages (#1035)
Raghav Chamadiya486e403a46b5
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.pyindex 2db3c1f67..8ce9a8bf4 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py@@ -115,6 +115,28 @@ def _run_repo_checks())+ # 4b. Store-format capability: does this store predate a capability the+ # current build offers? A REINDEX_RECOMMENDED migration never auto-runs, so+ # doctor is where an un-upgraded store learns a re-index is available. It is+ # reported OK, not FAIL: the store works degraded, it is not broken, and+ # failing every pre-upgrade store's doctor run would cry wolf. The row+ # carries the exact command so the recommendation is actionable here even+ # when the once-per-store update nag has already been shown and suppressed.+ if state_ok:+ try:+ from repowise.cli.upgrade import assess_store++ verdict = assess_store(repo_path)+ if verdict.reindex_recommended and verdict.reindex_command:+ notice = verdict.user_notice or "A re-index adds new capabilities."+ checks.append(+ _check("Store format", True, f"{notice} Run: {verdict.reindex_command}")+ )+ else:+ checks.append(_check("Store format", True, "Current"))+ except Exception as e:+ checks.append(_check("Store format", True, f"Could not check: {e}"))+# 5. Provider importable?provider_ok = Falsetry:diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex c566f50e8..0b6563dbe 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -1451,7 +1451,11 @@ def init_command()# Fingerprint after config writes so the first update doesn't false-positive.base_state["config_fingerprint"] = config_fingerprint(repo_path)- save_state(repo_path, base_state)+ # Index-only still renders the full concept tree (deterministically, from+ # templates), so the store has the current capability — stamp the terminal+ # version rather than clamping it below the reindex gate and falsely+ # recommending a re-index of a store this run just built.+ save_state(repo_path, base_state, full_index=True)# ---- State + config (full mode only) ----if not effective_index_only and provider:diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.pyindex 7563d017f..c385b4436 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py@@ -261,7 +261,10 @@ def save_full_state_and_config(kg = getattr(result, "knowledge_graph_result", None)if kg is not None:state["knowledge_graph"] = build_kg_state(kg)- save_state(repo_path, state)+ # A full init/index genuinely brings the store to the current store format+ # (its pages are the concept tree), so stamp the terminal version rather+ # than clamping at the reindex gate a routine persist would stop below.+ save_state(repo_path, state, full_index=True)if kg is not None:save_knowledge_graph_json(repo_path, kg)@@ -281,4 +284,4 @@ def save_full_state_and_config(# Re-save state with the fingerprint now that config.yaml is written.state["config_fingerprint"] = config_fingerprint(repo_path)- save_state(repo_path, state)+ save_state(repo_path, state, full_index=True)diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.pyindex a918b555e..d3bbaa635 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py@@ -439,7 +439,9 @@ def _ingest_and_generate_repo(repo: Any, idx: int, total: int, ctx: _WorkspaceCtkg = getattr(result, "knowledge_graph_result", None)if kg is not None:state["knowledge_graph"] = build_kg_state(kg)- save_state(repo.path, state)+ # A workspace repo is fully indexed here (concept tree included), so stamp+ # the terminal store format rather than clamping below the reindex gate.+ save_state(repo.path, state, full_index=True)if kg is not None:save_knowledge_graph_json(repo.path, kg)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 13d75d928..9eeee4249 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -173,6 +173,34 @@ def _surface_release_news(*, written_by: str | None) -> None:render_update_advisory(console, get_cli_update_check_cached())+def _surface_reindex_recommendation(repo_path, verdict, *, emitter: Any, dry_run: bool) -> None:+ """Show the once-per-store reindex recommendation for *verdict*, if any.++ Read-only except for the shown-notice ledger, so it is safe to call on the+ no-op ("already up to date") path as well as the main assessment path. It+ never runs the verdict's auto actions — those stay behind the single-flight+ lock in the main path. Interactive-terminal only, so a background post-commit+ update never burns the one-shot into a log the user never reads; `doctor`+ reports the recommendation on demand regardless.+ """+ from repowise.cli.upgrade import (+ record_reindex_notice_shown,+ reindex_notice_already_shown,+ )++ if not (verdict.reindex_recommended and verdict.reindex_command):+ return+ if not (console.is_terminal and emitter is None):+ return+ if reindex_notice_already_shown(repo_path, verdict):+ return+ console.print(f"[yellow]Reindex recommended:[/yellow] {verdict.reindex_command}")+ if verdict.user_notice:+ console.print(f"[dim]{verdict.user_notice}[/dim]")+ if not dry_run:+ record_reindex_notice_shown(repo_path, verdict)++@click.command("update")@click.argument("path", required=False, default=None)@click.option("--provider", "provider_name", default=None, help="LLM provider name.")@@ -707,6 +735,19 @@ def run_update(# than waiting for the next content-changing update. This is the# quiescent state a stale marker was observed lingering in.consume_update_pending(repo_path, head)+ # Up-to-date code does not mean an up-to-date store: a wiki indexed by an+ # older release may still benefit from a re-index (concept tree, written+ # prose). That is the common upgrade path, so surface the once-per-store+ # recommendation here too rather than only on a content-changing update.+ # Best-effort; a failure here must never turn a clean no-op into an error.+ try:+ from repowise.cli.upgrade import assess_store++ _surface_reindex_recommendation(+ repo_path, assess_store(repo_path), emitter=emitter, dry_run=dry_run+ )+ except Exception as exc:+ log.debug("reindex_notice_skipped", error=str(exc))if emitter is not None:emitter.done(ok=True,@@ -800,10 +841,8 @@ def run_update(verdict = assess_store(repo_path)if not verdict.is_noop:- if verdict.reindex_recommended and verdict.reindex_command:- console.print(f"[yellow]Reindex recommended:[/yellow] {verdict.reindex_command}")- if verdict.user_notice:- console.print(f"[dim]{verdict.user_notice}[/dim]")+ # Reindex is only ever recommended, never forced (see the helper).+ _surface_reindex_recommendation(repo_path, verdict, emitter=emitter, dry_run=dry_run)if verdict.actions and not dry_run:for action in verdict.actions:console.print(f"[dim]Upgrade: {action.reason}[/dim]")diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.pyindex 778764c0e..84bd1d53b 100644--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py@@ -493,7 +493,10 @@ def upgrade_to_full(# as "nothing wrote this wiki" right after a run that did.state["provider"] = provider.provider_namestate["model"] = provider.model_name- save_state(repo_path, state)+ # `update --full` regenerates the whole wiki (concept tree included), so it+ # brings the store to the terminal store format the same way a full init+ # does. Stamp it as such rather than clamping at the reindex gate.+ save_state(repo_path, state, full_index=True)if embedder_name and embedder_name != cfg.get("embedder"):from repowise.cli.helpers import save_config_partialdiff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.pyindex 00b843677..a6a543b78 100644--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py@@ -581,7 +581,11 @@ def _run_index_for_repo(if generate_docs and provider is not None:state["provider"] = provider.provider_namestate["model"] = provider.model_name- save_state(repo_path, state)+ # `workspace add` freshly full-indexes the repo, so this from-scratch state+ # is a current-format store, not one predating the concept tree. Stamp the+ # terminal version rather than clamping to v1 and nagging a repo this run+ # just built to re-index itself.+ save_state(repo_path, state, full_index=True)# Persist provider settings into the added repo's config.yaml so future# `repowise update` runs don't have to re-prompt.diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 544bb520c..e391b5e14 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -194,19 +194,25 @@ def load_state(repo_path: Path) -> dict[str, Any]:return {}-def save_state(repo_path: Path, state: dict[str, Any]) -> None:+def save_state(repo_path: Path, state: dict[str, Any], *, full_index: bool = False) -> None:"""Write *state* to ``.repowise/state.json``.Every persist stamps the store-format markers (``store_format_version`` andthe ``written_by_version`` package version that wrote it) so the upgradelayer always has a current record of the store's shape and provenance.++ ``full_index`` marks a persist that follows a full-repo (re)generation, so+ the store may be stamped to the terminal store-format version. A routine+ incremental persist leaves it False and the version clamps below any+ ``REINDEX_RECOMMENDED`` gate, keeping a reindex recommendation alive until+ an actual re-index clears it."""ensure_repowise_dir(repo_path)try:from repowise.cli import __version__ as _pkg_versionfrom repowise.core.upgrade import stamp as _stamp_store_version- _stamp_store_version(state, package_version=_pkg_version)+ _stamp_store_version(state, package_version=_pkg_version, full_index=full_index)except Exception: # never let stamping block a persistpassfrom repowise.core.fsutils import atomic_write_textdiff --git a/packages/cli/src/repowise/cli/upgrade.py b/packages/cli/src/repowise/cli/upgrade.pyindex 3a844b874..f81f25e93 100644--- a/packages/cli/src/repowise/cli/upgrade.py+++ b/packages/cli/src/repowise/cli/upgrade.py@@ -30,6 +30,36 @@ from .helpers import REPOWISE_DIR, load_config, load_statelog = structlog.get_logger(__name__)+#: state.json key holding the store-format versions whose reindex notice has+#: already been surfaced, so a routine ``update`` shows it once rather than on+#: every run. A full re-index clears the recommendation itself (by advancing the+#: store version past the gate), so this ledger only ever suppresses the nag in+#: the window between an upgrade and the re-index that resolves it.+SHOWN_NOTICES_KEY = "shown_upgrade_notices"+++def reindex_notice_already_shown(repo_path: Path, verdict: UpgradeVerdict) -> bool:+ """True when this store has already been shown the reindex notice for *verdict*."""+ state = load_state(repo_path)+ shown = state.get(SHOWN_NOTICES_KEY)+ return isinstance(shown, list) and verdict.to_store_version in shown+++def record_reindex_notice_shown(repo_path: Path, verdict: UpgradeVerdict) -> None:+ """Record that the reindex notice for *verdict* has been surfaced. Best-effort."""+ from .helpers import save_state++ try:+ state = load_state(repo_path)+ shown = state.get(SHOWN_NOTICES_KEY)+ shown = list(shown) if isinstance(shown, list) else []+ if verdict.to_store_version not in shown:+ shown.append(verdict.to_store_version)+ state[SHOWN_NOTICES_KEY] = shown+ save_state(repo_path, state)+ except Exception as exc: # a notice-ledger write must never break a command+ log.debug("reindex_notice_record_failed", error=str(exc))+class _CliUpgradeContext:"""Concrete :class:`UpgradeContext` backed by the CLI provider stack."""@@ -145,4 +175,9 @@ async def apply_upgrade(repo_path: Path, verdict: UpgradeVerdict) -> None:log.info("upgrade_applied", actions=[str(k) for k in ran])-__all__ = ["apply_upgrade", "assess_store"]+__all__ = [+ "apply_upgrade",+ "assess_store",+ "record_reindex_notice_shown",+ "reindex_notice_already_shown",+]diff --git a/packages/core/src/repowise/core/upgrade/manager.py b/packages/core/src/repowise/core/upgrade/manager.pyindex 68f5bbab2..f236671d0 100644--- a/packages/core/src/repowise/core/upgrade/manager.py+++ b/packages/core/src/repowise/core/upgrade/manager.py@@ -178,14 +178,49 @@ async def apply_auto(verdict: UpgradeVerdict, ctx: UpgradeContext) -> list[Upgrareturn ran-def stamp(state: dict[str, object], *, package_version: str | None) -> dict[str, object]:+def _auto_reachable_version(from_version: int, target: int) -> int:+ """Highest store-format version reachable without an un-run reindex.++ A routine persist advances the recorded version only across migrations it+ can satisfy automatically (``COMPATIBLE`` / ``AUTO`` / ``RE_PARSE``). A+ ``REINDEX_RECOMMENDED`` migration is a hard gate: the store stays just below+ it until a full re-index runs, so :func:`assess` keeps returning the notice+ on every routine ``update`` until the user actually re-indexes. Without this+ clamp the first persist after an upgrade would stamp the store current and+ silence a recommendation the store has not yet earned.+ """+ ceiling = from_version+ for migration in migrations_between(from_version, target):+ if migration.tier >= UpgradeTier.REINDEX_RECOMMENDED:+ break+ ceiling = migration.to_version+ return ceiling+++def stamp(+ state: dict[str, object],+ *,+ package_version: str | None,+ full_index: bool = False,+) -> dict[str, object]:"""Write the current store-format markers into *state* in place and return it.Called on every persist so the store always records the format and the buildthat wrote it. ``embedding_model`` is stamped separately by the persistencelayer that knows the resolved embedder.++ ``full_index`` distinguishes a full-repo (re)generation, which genuinely+ brings the store to :data:`STORE_FORMAT_VERSION`, from a routine incremental+ persist, which does not. Only the former stamps the terminal version; the+ latter clamps at the first ``REINDEX_RECOMMENDED`` gate (see+ :func:`_auto_reachable_version`) so a reindex recommendation is never+ silenced by an ordinary ``update``."""- state[STORE_FORMAT_VERSION_KEY] = STORE_FORMAT_VERSION+ if full_index:+ state[STORE_FORMAT_VERSION_KEY] = STORE_FORMAT_VERSION+ else:+ recorded = _coerce_int(state.get(STORE_FORMAT_VERSION_KEY), default=0)+ state[STORE_FORMAT_VERSION_KEY] = _auto_reachable_version(recorded, STORE_FORMAT_VERSION)if package_version:state[WRITTEN_BY_VERSION_KEY] = package_versionreturn statediff --git a/packages/core/src/repowise/core/upgrade/registry.py b/packages/core/src/repowise/core/upgrade/registry.pyindex 79642f10a..b6a6e68b6 100644--- a/packages/core/src/repowise/core/upgrade/registry.py+++ b/packages/core/src/repowise/core/upgrade/registry.py@@ -52,6 +52,20 @@ MIGRATIONS: tuple[Migration, ...] = (summary="Baseline store format (additive schema reconcile is automatic).",action=None,),+ # v1 -> v2: the derived concept tree. Old stores carry per-directory module+ # pages; the current build groups files into named subsystem pages with+ # written prose and a navigable tree. No reconcile can rebuild that from the+ # old pages, so this is REINDEX_RECOMMENDED: we inform, never auto-run, and+ # `stamp` holds an un-reindexed store at v1 so the notice persists.+ Migration(+ to_version=2,+ tier=UpgradeTier.REINDEX_RECOMMENDED,+ summary=(+ "This wiki predates concept subsystem pages. A re-index builds a "+ "navigable page tree with a written page for each subsystem."+ ),+ action=None,+ ),)diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.pyindex a7e8c6d62..4fea9e4cf 100644--- a/packages/core/src/repowise/core/upgrade/version.py+++ b/packages/core/src/repowise/core/upgrade/version.py@@ -31,7 +31,14 @@ from __future__ import annotations#: Current on-disk store format. Stamped into ``state.json`` as#: ``store_format_version`` on every persist. Legacy stores predating this#: field are treated as version 0.-STORE_FORMAT_VERSION: int = 1+#:+#: v2 introduces the derived concept tree (subsystem pages + written prose in+#: place of per-directory module pages). Unlike v1, it is not reachable by the+#: automatic reconcile: only a full re-index rebuilds an old store's pages into+#: it. Its migration is therefore ``REINDEX_RECOMMENDED``, and :func:`stamp`+#: clamps a routine persist just below it so the notice keeps firing until the+#: user actually re-indexes.+STORE_FORMAT_VERSION: int = 2#: Current parser/extractor schema. Folded into the parse-cache fingerprint in#: place of the package version. See :mod:`repowise.core.ingestion.parse_cache`.diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex 41c753698..f150e8bf9 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -776,7 +776,9 @@ def _persist_initial_index_state(_pkg_version: str | None = _dist_version("repowise")except Exception:_pkg_version = None- _stamp_store_version(state, package_version=_pkg_version)+ # This is the full-index persist (concept tree included), so stamp the+ # terminal store-format version rather than clamping at the reindex gate.+ _stamp_store_version(state, package_version=_pkg_version, full_index=True)except Exception:logger.debug("store_version_stamp_failed", repo_path=str(repo_path), exc_info=True)diff --git a/tests/unit/cli/test_doctor_store_format.py b/tests/unit/cli/test_doctor_store_format.pynew file mode 100644index 000000000..6b03031ac--- /dev/null+++ b/tests/unit/cli/test_doctor_store_format.py@@ -0,0 +1,61 @@+"""Doctor's store-format capability probe.++An un-upgraded store learns from ``doctor`` that a re-index is available, since+the once-per-store update nag may already have been shown and suppressed. The+row is always OK (a pre-upgrade store works degraded, it is not broken) and+carries the exact command.+"""++from __future__ import annotations++import json+import subprocess+from pathlib import Path++from click.testing import CliRunner++from repowise.cli.commands.doctor_cmd import doctor_command+from repowise.core.upgrade import STORE_FORMAT_VERSION+++def _repo_with_store(tmp_path: Path, store_format_version: int) -> Path:+ tmp_path.mkdir(parents=True, exist_ok=True)+ subprocess.run(["git", "init"], cwd=str(tmp_path), capture_output=True)+ repowise_dir = tmp_path / ".repowise"+ repowise_dir.mkdir(parents=True, exist_ok=True)+ (repowise_dir / "state.json").write_text(+ json.dumps(+ {+ "store_format_version": store_format_version,+ "written_by_version": "0.21.0",+ "last_sync_commit": "abc1234",+ }+ ),+ encoding="utf-8",+ )+ return tmp_path+++def _store_format_row(tmp_path: Path) -> dict:+ result = CliRunner().invoke(+ doctor_command, [str(tmp_path), "--no-workspace", "--format", "json"]+ )+ payload = json.loads(result.output[result.output.index("{") :])+ rows = [c for c in payload["checks"] if c["name"] == "Store format"]+ assert rows, "doctor did not emit a Store format row"+ return rows[0]+++def test_doctor_flags_reindex_for_old_store(tmp_path: Path) -> None:+ row = _store_format_row(_repo_with_store(tmp_path, 1))+ # Reported OK (degraded, not broken) with an actionable command.+ assert row["ok"] is True+ assert "repowise init --force" in row["detail"]+ # Plain text only: no Rich markup leaking through the JSON surface.+ assert "[" not in row["detail"] or "]" not in row["detail"]+++def test_doctor_reports_current_store_as_current(tmp_path: Path) -> None:+ row = _store_format_row(_repo_with_store(tmp_path, STORE_FORMAT_VERSION))+ assert row["ok"] is True+ assert row["detail"] == "Current"diff --git a/tests/unit/cli/test_update_reindex_notice.py b/tests/unit/cli/test_update_reindex_notice.pynew file mode 100644index 000000000..a47e31d7a--- /dev/null+++ b/tests/unit/cli/test_update_reindex_notice.py@@ -0,0 +1,121 @@+"""The reindex recommendation on the ``repowise update`` path.++Two guarantees: it is surfaced at most once per store (even across the no-op+"already up to date" path, which is the common upgrade case), and an old-shape+store survives ``update`` / ``status`` without error while the recommendation+stays alive (the routine persist never advances past the reindex gate).+"""++from __future__ import annotations++import asyncio+import json+import subprocess+from pathlib import Path++from click.testing import CliRunner++from repowise.cli import upgrade as cliup+from repowise.cli.commands.update_cmd import command as upd+from repowise.cli.helpers import save_state+from repowise.cli.main import cli+++class _FakeTerminal:+ """A console that reports as a terminal and records what was printed."""++ is_terminal = True++ def __init__(self) -> None:+ self.lines: list[str] = []++ def print(self, *args, **_kwargs) -> None:+ self.lines.append(" ".join(str(a) for a in args))+++def test_reindex_notice_shows_once_then_suppresses(tmp_path: Path, monkeypatch) -> None:+ save_state(tmp_path, {"store_format_version": 1}) # a store predating the concept tree+ verdict = cliup.assess_store(tmp_path)+ assert verdict.reindex_recommended++ fake = _FakeTerminal()+ monkeypatch.setattr(upd, "console", fake)++ upd._surface_reindex_recommendation(tmp_path, verdict, emitter=None, dry_run=False)+ assert any("Reindex recommended" in line for line in fake.lines)++ fake.lines.clear()+ upd._surface_reindex_recommendation(tmp_path, verdict, emitter=None, dry_run=False)+ assert fake.lines == [] # ledger suppresses the second showing+++def test_reindex_notice_silent_when_not_a_terminal(tmp_path: Path, monkeypatch) -> None:+ save_state(tmp_path, {"store_format_version": 1})+ verdict = cliup.assess_store(tmp_path)++ class _NonTerminal(_FakeTerminal):+ is_terminal = False++ fake = _NonTerminal()+ monkeypatch.setattr(upd, "console", fake)+ upd._surface_reindex_recommendation(tmp_path, verdict, emitter=None, dry_run=False)+ assert fake.lines == []+ # And a suppressed showing must not burn the one-shot: nothing was recorded.+ assert not cliup.reindex_notice_already_shown(tmp_path, verdict)+++# --- e2e: an old-shape store survives update/status -----------------------+++def _git(repo: Path, *args: str) -> None:+ subprocess.run(["git", *args], cwd=str(repo), capture_output=True, text=True)+++def _make_repo(tmp_path: Path) -> Path:+ repo = tmp_path / "repo"+ repo.mkdir(parents=True)+ _git(repo, "init")+ _git(repo, "config", "user.email", "[email protected]")+ _git(repo, "config", "user.name", "T")+ (repo / "a.py").write_text("def alpha():\n return 1\n")+ _git(repo, "add", ".")+ _git(repo, "commit", "-m", "initial")+ return repo+++def test_update_survives_old_store_and_keeps_recommendation(tmp_path: Path) -> None:+ from repowise.core.pipeline.full_index import index_repo_full++ repo = _make_repo(tmp_path)+ asyncio.run(index_repo_full(repo)) # real index-only store (wiki.db), keyless++ head = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=str(repo), capture_output=True, text=True+ ).stdout.strip()++ # Author a state.json as a release predating the concept tree would have left+ # it: at store format v1, synced to HEAD so `update` takes the no-op path.+ state_path = repo / ".repowise" / "state.json"+ state_path.write_text(+ json.dumps(+ {+ "store_format_version": 1,+ "written_by_version": "0.21.0",+ "last_sync_commit": head,+ "git_tier": "full",+ "run_mode": "standard",+ }+ ),+ encoding="utf-8",+ )++ res = CliRunner().invoke(cli, ["update", str(repo)])+ assert res.exit_code == 0, res.output++ after = json.loads(state_path.read_text(encoding="utf-8"))+ # The routine update never advances past the reindex gate, so the store+ # stays at v1 and the recommendation is not silenced.+ assert after["store_format_version"] == 1++ res_status = CliRunner().invoke(cli, ["status", str(repo)])+ assert res_status.exit_code == 0, res_status.outputdiff --git a/tests/unit/server/test_meta_api.py b/tests/unit/server/test_meta_api.pyindex 4fb1988a2..7d4bf1ed6 100644--- a/tests/unit/server/test_meta_api.py+++ b/tests/unit/server/test_meta_api.py@@ -62,24 +62,49 @@ async def test_version_endpoint_populates_store_status(client: AsyncClient, tmp_"""A resolvable repo with a state.json fills the store-format fields."""import json+ from repowise.core.upgrade import STORE_FORMAT_VERSIONfrom tests.unit.server.conftest import create_test_reporepo = await create_test_repo(client, tmp_path)repo_dir = tmp_path / "test-repo"(repo_dir / ".repowise").mkdir(parents=True, exist_ok=True)(repo_dir / ".repowise" / "state.json").write_text(- json.dumps({"store_format_version": 1, "written_by_version": "0.21.0"}),+ json.dumps({"store_format_version": STORE_FORMAT_VERSION, "written_by_version": "0.21.0"}),encoding="utf-8",)resp = await client.get("/api/meta/version", params={"repo_id": repo["id"]})assert resp.status_code == 200body = resp.json()- assert body["store_format_version"] == 1+ assert body["store_format_version"] == STORE_FORMAT_VERSIONassert body["store_compatible"] is Trueassert body["reindex_recommended"] is False+async def test_version_endpoint_flags_reindex_for_old_store(client: AsyncClient, tmp_path) -> None:+ """A store predating the concept tree reports reindex-recommended, not forced."""+ import json++ from tests.unit.server.conftest import create_test_repo++ repo = await create_test_repo(client, tmp_path)+ repo_dir = tmp_path / "test-repo"+ (repo_dir / ".repowise").mkdir(parents=True, exist_ok=True)+ (repo_dir / ".repowise" / "state.json").write_text(+ json.dumps({"store_format_version": 1, "written_by_version": "0.21.0"}),+ encoding="utf-8",+ )++ resp = await client.get("/api/meta/version", params={"repo_id": repo["id"]})+ assert resp.status_code == 200+ body = resp.json()+ assert body["store_format_version"] == 1+ assert body["store_compatible"] is False+ assert body["reindex_recommended"] is True+ assert body["reindex_command"]++@pytest.mark.asyncioasync def test_changelog_endpoint(client: AsyncClient) -> None:resp = await client.get("/api/meta/changelog", params={"limit": 3})diff --git a/tests/unit/upgrade/test_cli_executor.py b/tests/unit/upgrade/test_cli_executor.pyindex b5a782ec4..c067baa78 100644--- a/tests/unit/upgrade/test_cli_executor.py+++ b/tests/unit/upgrade/test_cli_executor.py@@ -18,15 +18,16 @@ from repowise.core.upgrade import UpgradeActionKind, UpgradeTierdef test_assess_store_clean_on_fresh_store(tmp_path: Path):- save_state(tmp_path, {"last_sync_commit": "abc"})+ # A fresh store is one a full index wrote, so it stamps the terminal format+ # (a routine persist would clamp below the reindex gate).+ save_state(tmp_path, {"last_sync_commit": "abc"}, full_index=True)verdict = cliup.assess_store(tmp_path)- # save_state stamps the current format, so a freshly written store is a noop.assert verdict.is_noopassert verdict.tier == UpgradeTier.COMPATIBLEdef test_assess_store_detects_embedding_drift(tmp_path: Path, monkeypatch):- save_state(tmp_path, {"last_sync_commit": "abc"})+ save_state(tmp_path, {"last_sync_commit": "abc"}, full_index=True)save_config(tmp_path,"openai",@@ -67,3 +68,31 @@ def test_current_embedding_model_swallows_errors(monkeypatch):async def test_apply_upgrade_noop_when_no_actions(tmp_path: Path):verdict = cliup.assess_store(tmp_path) # empty store -> noop verdictawait cliup.apply_upgrade(tmp_path, verdict) # must not raise / do nothing+++# --- shown-once reindex-notice ledger -------------------------------------+++def test_reindex_notice_ledger_records_and_suppresses(tmp_path: Path):+ """The ledger reports unshown first, then shown after recording."""+ save_state(tmp_path, {"store_format_version": 1}) # a store that predates v2+ verdict = cliup.assess_store(tmp_path)+ assert verdict.reindex_recommended++ assert not cliup.reindex_notice_already_shown(tmp_path, verdict)+ cliup.record_reindex_notice_shown(tmp_path, verdict)+ assert cliup.reindex_notice_already_shown(tmp_path, verdict)++ # The recorded version survives a routine persist (which clamps at v1), so the+ # nag stays suppressed while the recommendation itself stays live.+ save_state(tmp_path, {**cliup.load_state(tmp_path)})+ assert cliup.reindex_notice_already_shown(tmp_path, verdict)+++def test_reindex_notice_record_is_idempotent(tmp_path: Path):+ save_state(tmp_path, {"store_format_version": 1})+ verdict = cliup.assess_store(tmp_path)+ cliup.record_reindex_notice_shown(tmp_path, verdict)+ cliup.record_reindex_notice_shown(tmp_path, verdict)+ shown = cliup.load_state(tmp_path).get("shown_upgrade_notices")+ assert shown == [verdict.to_store_version]diff --git a/tests/unit/upgrade/test_manager.py b/tests/unit/upgrade/test_manager.pyindex fea4b51c7..f2db00b5b 100644--- a/tests/unit/upgrade/test_manager.py+++ b/tests/unit/upgrade/test_manager.py@@ -26,14 +26,21 @@ from repowise.core.upgrade.registry import Migration, migrations_between# --- assess: version-span tiers -------------------------------------------def test_legacy_store_is_compatible_noop():- """A store with no version fields (version 0) reaching v1 needs nothing."""+def test_legacy_store_recommends_reindex():+ """A store with no version fields (version 0) predates the concept tree.++ The v0->v1 step is a compatible reconcile, but the span also crosses the+ v1->v2 concept-tree migration, which is REINDEX_RECOMMENDED. The overall+ tier is the max, so a legacy store is told (never forced) to re-index, and+ the recommendation carries a command but no auto action.+ """verdict = assess({})assert verdict.from_store_version == 0assert verdict.to_store_version == STORE_FORMAT_VERSION- assert verdict.tier == UpgradeTier.COMPATIBLE- assert verdict.is_noop- assert not verdict.actions+ assert verdict.tier == UpgradeTier.REINDEX_RECOMMENDED+ assert verdict.reindex_recommended+ assert verdict.reindex_command+ assert not verdict.actions # informed, never auto-rundef test_current_store_is_noop():@@ -136,16 +143,30 @@ def test_migrations_between_is_exclusive_inclusive(monkeypatch):# --- stamp -----------------------------------------------------------------def test_stamp_writes_version_markers():+def test_stamp_full_index_writes_terminal_version():+ """A full-index persist stamps the terminal store-format version."""state: dict[str, object] = {}- stamp(state, package_version="9.9.9")+ stamp(state, package_version="9.9.9", full_index=True)assert state["store_format_version"] == STORE_FORMAT_VERSIONassert state["written_by_version"] == "9.9.9"+def test_stamp_routine_persist_clamps_below_reindex_gate():+ """A routine (non-full) persist never advances past a REINDEX_RECOMMENDED gate.++ Empty state is version 0; the auto-reachable ceiling is v1 (the compatible+ baseline), because v2 is reindex-gated. Clamping here is what keeps the+ reindex recommendation alive across ordinary updates until a real re-index.+ """+ state: dict[str, object] = {}+ stamp(state, package_version="9.9.9")+ assert state["store_format_version"] == 1+ assert state["written_by_version"] == "9.9.9"++def test_stamp_without_package_version_omits_written_by():state: dict[str, object] = {}- stamp(state, package_version=None)+ stamp(state, package_version=None, full_index=True)assert state["store_format_version"] == STORE_FORMAT_VERSIONassert "written_by_version" not in state