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(update): persist init mode + lock-file suppression for stale-wiki hook (#155)

Raghav Chamadiya73cab71d4944
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd.py b/packages/cli/src/repowise/cli/commands/augment_cmd.py
index 3915b0571..413b6cba5 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd.py
@@ -362,13 +362,83 @@ def _handle_post_tool_use(tool_input: dict, tool_output: dict, cwd: str) -> str
if head == last_sync:
return None
+ # Suppress while a `repowise update` is in flight — the post-commit
+ # hook typically kicks one off in the background, and warning the
+ # agent that the wiki is stale right after the commit is just noise.
+ if _update_in_flight(repo_path, head):
+ return None
+
+ # Once-per-HEAD dedupe: every tool call after a commit would otherwise
+ # repeat the same staleness warning until an update completes (which
+ # may never happen if the user's hook is misconfigured). Cache the
+ # already-warned HEAD so the message fires once per stale state.
+ if _already_warned(repo_path, head):
+ return None
+ _record_warning(repo_path, head)
+
+ docs_enabled = state.get("docs_enabled", True)
+ artifact = "Wiki" if docs_enabled else "Index"
return (
- "[repowise] Wiki is stale — last indexed at commit "
+ f"[repowise] {artifact} is stale — last indexed at commit "
f"{last_sync[:8]}, HEAD is now {head[:8]}. "
"Run `repowise update` to refresh documentation and graph context."
)
+def _update_in_flight(repo_path: "Path", head: str) -> bool:
+ """Return True if a recent `repowise update` is still running.
+
+ Reads ``.repowise/.update.lock`` written by ``update_command``. A lock
+ is considered live if it was written within the last 30 minutes; older
+ entries are treated as crashed runs and ignored. If the lock's target
+ commit matches HEAD, the update will land us in sync — suppress the
+ warning either way.
+ """
+ import time
+
+ lock_path = repo_path / ".repowise" / ".update.lock"
+ if not lock_path.exists():
+ return False
+ try:
+ payload = json.loads(lock_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ return False
+
+ started = payload.get("started_at")
+ if not isinstance(started, (int, float)):
+ return False
+ if time.time() - started > 30 * 60:
+ return False
+
+ target = payload.get("target_commit")
+ if target and target == head:
+ return True
+ # Lock is live but for a different (presumably older) commit. The
+ # in-flight update will at least narrow the gap; one more tool call
+ # later will re-evaluate. Suppress for now.
+ return True
+
+
+def _already_warned(repo_path: "Path", head: str) -> bool:
+ """Check the per-HEAD warning marker, written by ``_record_warning``."""
+ marker = repo_path / ".repowise" / ".augment-warned"
+ if not marker.exists():
+ return False
+ try:
+ return marker.read_text(encoding="utf-8").strip() == head
+ except OSError:
+ return False
+
+
+def _record_warning(repo_path: "Path", head: str) -> None:
+ """Persist that we have warned about staleness at *head*. Best-effort."""
+ marker = repo_path / ".repowise" / ".augment-warned"
+ try:
+ marker.write_text(head, encoding="utf-8")
+ except OSError:
+ pass
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.py
index 71f29d8ee..41680711c 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py
@@ -664,6 +664,7 @@ def _workspace_init(
state: dict[str, Any] = {
"last_sync_commit": head,
"total_pages": pages_count,
+ "docs_enabled": not index_only and provider is not None,
}
if not index_only and provider is not None:
state["provider"] = provider.provider_name
@@ -1357,6 +1358,18 @@ def init_command(
_maybe_generate_claude_md(console, repo_path, no_claude_md=no_claude_md)
+ # ---- State (always) ----
+ # Even in index-only mode we persist `last_sync_commit` so that a
+ # subsequent `repowise update` (e.g. fired by the post-commit hook) has
+ # a baseline to diff against. Without this, index-only users hit
+ # "No previous sync found" on every update.
+ head = get_head_commit(repo_path)
+ base_state = load_state(repo_path)
+ base_state["last_sync_commit"] = head
+ base_state["docs_enabled"] = not index_only and provider is not None
+ if index_only or provider is None:
+ save_state(repo_path, base_state)
+
# ---- State + config (full mode only) ----
if not index_only and provider:
@@ -1394,6 +1407,7 @@ def init_command(
state["total_pages"] = run_async(_count_db_pages())
state["provider"] = provider.provider_name
state["model"] = provider.model_name
+ state["docs_enabled"] = True
total_tokens = sum(p.total_tokens for p in (result.generated_pages or []))
state["total_tokens"] = total_tokens
save_state(repo_path, state)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index 2b1e6d60c..f7d878395 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -8,12 +8,14 @@ import click
from rich.table import Table
from repowise.cli.helpers import (
+ acquire_update_lock,
console,
ensure_repowise_dir,
find_workspace_root,
get_head_commit,
load_config,
load_state,
+ release_update_lock,
resolve_provider,
resolve_repo_path,
run_async,
@@ -21,6 +23,34 @@ from repowise.cli.helpers import (
)
+# ---------------------------------------------------------------------------
+# Mode resolution
+# ---------------------------------------------------------------------------
+
+
+def _resolve_index_only_mode(
+ *,
+ index_only: bool,
+ docs_flag: bool | None,
+ state: dict,
+) -> bool:
+ """Decide whether this update should skip LLM regeneration.
+
+ Priority: explicit ``--index-only`` flag > ``--docs/--no-docs`` >
+ ``state.docs_enabled`` (default: True for backward compatibility with
+ state files written before the field existed). Encapsulated as a pure
+ function so the post-commit hook does the right thing without needing
+ any extra knobs at install time.
+ """
+ if index_only:
+ return True
+ if docs_flag is False:
+ return True
+ if docs_flag is None and state.get("docs_enabled", True) is False:
+ return True
+ return False
+
+
# ---------------------------------------------------------------------------
# Workspace update flow
# ---------------------------------------------------------------------------
@@ -154,6 +184,18 @@ def _workspace_update(
"iteration on extractors / resolvers without spending tokens."
),
)
+ "--docs/--no-docs",
+ "docs_flag",
+ default=None,
+ help=(
+ "Override the persisted init mode for this run. --no-docs is "
+ "equivalent to --index-only; --docs forces LLM page regeneration "
+ "even when the repo was indexed without docs. Without either flag, "
+ "the value of `docs_enabled` from .repowise/state.json is used "
+ "(set during `repowise init`)."
+ ),
+)
def update_command(
path: str | None,
provider_name: str | None,
@@ -164,6 +206,7 @@ def update_command(
workspace: bool,
repo_alias: str | None,
index_only: bool = False,
+ docs_flag: bool | None = None,
concurrency: int = 5,
) -> None:
"""Incrementally update wiki pages for files changed since last sync."""
@@ -195,6 +238,20 @@ def update_command(
console.print("[green]Already up to date.[/green]")
return
+ # --- Resolve effective mode (index-only vs full LLM regen) ---
+ index_only = _resolve_index_only_mode(
+ index_only=index_only, docs_flag=docs_flag, state=state
+ )
+
+ # --- Acquire update lock so the augment hook can suppress its
+ # stale-wiki warning while this run is in flight (typical case: the
+ # post-commit hook fires `repowise update` in the background, then a
+ # follow-on tool call would otherwise warn that HEAD has moved). ---
+ import atexit
+
+ acquire_update_lock(repo_path, head)
+ atexit.register(release_update_lock, repo_path)
+
console.print(f"[bold]repowise update[/bold] — {repo_path}")
console.print(f"Diffing [cyan]{base_ref[:8]}..{(head or 'HEAD')[:8]}[/cyan]")
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index d985b7336..b717afe22 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -126,6 +126,76 @@ def save_state(repo_path: Path, state: dict[str, Any]) -> None:
state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")
+# ---------------------------------------------------------------------------
+# Update lock — coordinates concurrent `repowise update` invocations and
+# lets the augment hook suppress stale-wiki warnings while a refresh is in
+# flight (post-commit hook firing → tool-call warning would be spurious).
+# ---------------------------------------------------------------------------
+
+UPDATE_LOCK_FILENAME = ".update.lock"
+
+# Locks older than this are considered stale (a crashed update); the hook
+# will ignore them and the next update will overwrite. Generous enough to
+# cover a slow full-update on a large repo.
+UPDATE_LOCK_STALE_AFTER_SECONDS = 30 * 60
+
+
+def _update_lock_path(repo_path: Path) -> Path:
+ return get_repowise_dir(repo_path) / UPDATE_LOCK_FILENAME
+
+
+def acquire_update_lock(repo_path: Path, target_commit: str | None) -> Path:
+ """Write the update lock file. Returns its path.
+
+ The lock contains the PID and target commit so the augment hook can
+ decide whether a stale-wiki warning is redundant. Best-effort: if write
+ fails (read-only fs, permissions), returns the path anyway — callers
+ must still call ``release_update_lock`` in a finally block.
+ """
+ import time
+
+ ensure_repowise_dir(repo_path)
+ lock_path = _update_lock_path(repo_path)
+ payload = {
+ "pid": os.getpid(),
+ "target_commit": target_commit,
+ "started_at": time.time(),
+ }
+ try:
+ lock_path.write_text(json.dumps(payload), encoding="utf-8")
+ except OSError:
+ pass
+ return lock_path
+
+
+def release_update_lock(repo_path: Path) -> None:
+ """Remove the update lock file. Safe to call if it doesn't exist."""
+ try:
+ _update_lock_path(repo_path).unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def read_update_lock(repo_path: Path) -> dict[str, Any] | None:
+ """Return the lock payload if present and not stale, else ``None``."""
+ import time
+
+ lock_path = _update_lock_path(repo_path)
+ if not lock_path.exists():
+ return None
+ try:
+ payload = json.loads(lock_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ return None
+
+ started = payload.get("started_at")
+ if not isinstance(started, (int, float)):
+ return None
+ if time.time() - started > UPDATE_LOCK_STALE_AFTER_SECONDS:
+ return None
+ return payload
+
+
# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/hooks.py b/packages/cli/src/repowise/cli/hooks.py
index 6998cbc13..0c6001260 100644
--- a/packages/cli/src/repowise/cli/hooks.py
+++ b/packages/cli/src/repowise/cli/hooks.py
@@ -18,6 +18,16 @@ from pathlib import Path
_HOOK_MARKER = "# repowise-hook-start"
_HOOK_MARKER_END = "# repowise-hook-end"
+# Fingerprints of legacy hook bodies (pre-marker era). When ``install`` is
+# called over the top of a file containing these, we strip the legacy block
+# rather than appending a second copy. The legacy block was unreachable due
+# to a trailing ``exit 0`` and on Windows would fail every commit because
+# ``uv run repowise update`` rebuilt the venv from a fresh resolve.
+_LEGACY_HOOK_FINGERPRINTS = (
+ "[repowise] Triggering incremental wiki update",
+ "/tmp/repowise-update.log",
+)
+
# The hook script detects the platform and runs repowise update in the
# background so the commit is never blocked.
_HOOK_SCRIPT = """\
@@ -50,11 +60,61 @@ def _git_root(path: Path) -> Path | None:
return None
+def _strip_legacy_block(content: str) -> tuple[str, bool]:
+ """Remove a pre-marker repowise hook body from *content*.
+
+ Older versions of repowise wrote a hook body without start/end markers
+ that ended in ``exit 0``, which made the marker block (when later
+ appended) unreachable. We detect those by fingerprint and excise the
+ surrounding shell block. Returns the cleaned content and whether
+ anything was stripped.
+ """
+ if not any(fp in content for fp in _LEGACY_HOOK_FINGERPRINTS):
+ return content, False
+
+ lines = content.splitlines()
+ # The legacy block always starts with a shell comment that mentions the
+ # hook's purpose and ends at the explicit ``exit 0`` line below the
+ # backgrounded subshell. Walk forward until we see ``exit 0`` and drop
+ # everything from the first fingerprint line up to and including it.
+ start = None
+ for i, line in enumerate(lines):
+ if any(fp in line for fp in _LEGACY_HOOK_FINGERPRINTS):
+ # Walk back to the nearest comment header so we drop the whole
+ # block, not just the inner echo line.
+ start = i
+ for j in range(i - 1, -1, -1):
+ stripped = lines[j].strip()
+ if stripped.startswith("# post-commit hook") or stripped.startswith(
+ "# Auto-syncs"
+ ):
+ start = j
+ break
+ if not stripped or stripped.startswith("#!"):
+ break
+ break
+
+ if start is None:
+ return content, False
+
+ end = start
+ for k in range(start, len(lines)):
+ if lines[k].strip() == "exit 0":
+ end = k
+ break
+ end = k
+
+ cleaned = "\n".join(lines[:start] + lines[end + 1:]).rstrip() + "\n"
+ return cleaned, True
+
+
def install(repo_path: Path) -> str:
"""Install a repowise post-commit hook in the repo's .git/hooks/.
Appends to an existing post-commit hook if one exists (preserving
- other tools' hooks). Returns a human-readable status message.
+ other tools' hooks). If a legacy (pre-marker) repowise body is found,
+ it is removed first to avoid an unreachable marker block. Returns a
+ human-readable status message.
"""
root = _git_root(repo_path)
if root is None:
@@ -64,10 +124,15 @@ def install(repo_path: Path) -> str:
hooks_dir.mkdir(exist_ok=True)
hook_path = hooks_dir / "post-commit"
+ migrated_legacy = False
if hook_path.exists():
content = hook_path.read_text(encoding="utf-8")
+ content, migrated_legacy = _strip_legacy_block(content)
+ if migrated_legacy:
+ hook_path.write_text(content, encoding="utf-8")
+
if _HOOK_MARKER in content:
- return "already installed"
+ return "migrated legacy hook" if migrated_legacy else "already installed"
# Append to existing hook
hook_path.write_text(
content.rstrip() + "\n\n" + _HOOK_SCRIPT,
diff --git a/tests/unit/cli/test_augment_staleness.py b/tests/unit/cli/test_augment_staleness.py
new file mode 100644
index 000000000..265075790
--- /dev/null
+++ b/tests/unit/cli/test_augment_staleness.py
@@ -0,0 +1,200 @@
+"""Tests for the PostToolUse staleness-warning suppression in `repowise augment`.
+
+Covers the noise-reduction behaviors added alongside the docs_enabled work:
+1. While `repowise update` holds the update lock, the warning is suppressed.
+2. After warning once for a given HEAD, subsequent tool calls don't repeat
+ the warning until HEAD moves or the marker is cleared.
+3. The warning message reflects whether the repo was indexed with docs.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.augment_cmd import _handle_post_tool_use
+
+
+def repo(tmp_path):
+ """A minimal git repo with a `.repowise/state.json`."""
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t",
+ "commit", "--allow-empty", "-m", "init", "-q"],
+ cwd=tmp_path,
+ check=True,
+ )
+ head = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=tmp_path,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+ (tmp_path / ".repowise").mkdir()
+ return tmp_path, head
+
+
+def _state(repo_path: Path, **fields) -> None:
+ (repo_path / ".repowise" / "state.json").write_text(
+ json.dumps(fields), encoding="utf-8"
+ )
+
+
+def _commit(repo_path: Path) -> str:
+ """Make an empty commit and return the new HEAD."""
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t",
+ "commit", "--allow-empty", "-m", "next", "-q"],
+ cwd=repo_path,
+ check=True,
+ )
+ return subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=repo_path,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+
+def _post(repo_path: Path):
+ return _handle_post_tool_use(
+ tool_input={"command": "git commit -m 'x'"},
+ tool_output={"exit_code": 0},
+ cwd=str(repo_path),
+ )
+
+
+class TestStaleWarning:
+ def test_warns_when_state_lags_behind_head(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+ new_head = _commit(repo_path)
+
+ msg = _post(repo_path)
+ assert msg is not None
+ assert "Wiki is stale" in msg
+ assert head[:8] in msg
+ assert new_head[:8] in msg
+
+ def test_no_warning_when_in_sync(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+
+ assert _post(repo_path) is None
+
+ def test_no_warning_when_no_state_file(self, repo):
+ repo_path, _ = repo
+ # state.json never written
+ assert _post(repo_path) is None
+
+
+class TestUpdateLockSuppression:
+ def test_lock_suppresses_warning(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+ new_head = _commit(repo_path)
+
+ # Simulate `repowise update` running with target_commit=new_head
+ import time
+
+ (repo_path / ".repowise" / ".update.lock").write_text(
+ json.dumps({
+ "pid": 999999,
+ "target_commit": new_head,
+ "started_at": time.time(),
+ }),
+ encoding="utf-8",
+ )
+
+ assert _post(repo_path) is None
+
+ def test_stale_lock_does_not_suppress(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+ _commit(repo_path)
+
+ # Lock from 2 hours ago — beyond the 30-min stale window
+ (repo_path / ".repowise" / ".update.lock").write_text(
+ json.dumps({"pid": 1, "target_commit": "x", "started_at": 0}),
+ encoding="utf-8",
+ )
+
+ assert _post(repo_path) is not None
+
+ def test_lock_for_different_commit_still_suppresses(self, repo):
+ # An update is running but its target predates HEAD. We still
+ # suppress: the in-flight run will at least narrow the gap, and
+ # the next tool call will re-evaluate.
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+ _commit(repo_path)
+
+ import time
+
+ (repo_path / ".repowise" / ".update.lock").write_text(
+ json.dumps({
+ "pid": 1,
+ "target_commit": head, # old HEAD, not the current one
+ "started_at": time.time(),
+ }),
+ encoding="utf-8",
+ )
+
+ assert _post(repo_path) is None
+
+
+class TestPerHeadDedupe:
+ def test_warns_once_per_head(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+ _commit(repo_path)
+
+ first = _post(repo_path)
+ second = _post(repo_path)
+
+ assert first is not None
+ assert second is None # Suppressed by per-HEAD marker
+
+ def test_warning_re_fires_on_new_commit(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+ _commit(repo_path)
+ _post(repo_path) # First warning, marker written
+
+ _commit(repo_path) # New HEAD invalidates marker
+ msg = _post(repo_path)
+ assert msg is not None
+
+
+class TestDocsEnabledWording:
+ def test_says_index_when_docs_disabled(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=False)
+ _commit(repo_path)
+
+ msg = _post(repo_path)
+ assert msg is not None
+ assert "Index is stale" in msg
+ assert "Wiki is stale" not in msg
+
+ def test_says_wiki_when_docs_enabled(self, repo):
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head, docs_enabled=True)
+ _commit(repo_path)
+
+ msg = _post(repo_path)
+ assert "Wiki is stale" in msg
+
+ def test_defaults_to_wiki_when_field_missing(self, repo):
+ # Backward compat: pre-existing state.json files without
+ # docs_enabled should keep the old wording.
+ repo_path, head = repo
+ _state(repo_path, last_sync_commit=head)
+ _commit(repo_path)
+
+ msg = _post(repo_path)
+ assert "Wiki is stale" in msg
diff --git a/tests/unit/cli/test_helpers.py b/tests/unit/cli/test_helpers.py
index 89a8522b3..7b5984492 100644
--- a/tests/unit/cli/test_helpers.py
+++ b/tests/unit/cli/test_helpers.py
@@ -122,6 +122,72 @@ class TestStateFile:
assert (tmp_path / ".repowise" / "state.json").exists()
+# ---------------------------------------------------------------------------
+# Update lock
+# ---------------------------------------------------------------------------
+
+
+class TestUpdateLock:
+ def test_acquire_writes_payload(self, tmp_path):
+ from repowise.cli.helpers import acquire_update_lock, read_update_lock
+
+ acquire_update_lock(tmp_path, "abc123def")
+ payload = read_update_lock(tmp_path)
+ assert payload is not None
+ assert payload["target_commit"] == "abc123def"
+ assert isinstance(payload["pid"], int)
+ assert isinstance(payload["started_at"], (int, float))
+
+ def test_release_removes_lock(self, tmp_path):
+ from repowise.cli.helpers import (
+ acquire_update_lock,
+ read_update_lock,
+ release_update_lock,
+ )
+
+ acquire_update_lock(tmp_path, "abc")
+ release_update_lock(tmp_path)
+ assert read_update_lock(tmp_path) is None
+
+ def test_release_is_idempotent(self, tmp_path):
+ from repowise.cli.helpers import release_update_lock
+
+ # Should not raise even when no lock exists.
+ release_update_lock(tmp_path)
+ release_update_lock(tmp_path)
+
+ def test_read_returns_none_when_stale(self, tmp_path):
+ import json
+
+ from repowise.cli.helpers import (
+ UPDATE_LOCK_FILENAME,
+ ensure_repowise_dir,
+ read_update_lock,
+ )
+
+ ensure_repowise_dir(tmp_path)
+ lock_path = tmp_path / ".repowise" / UPDATE_LOCK_FILENAME
+ # Stale: started 2 hours ago
+ lock_path.write_text(
+ json.dumps({"pid": 1, "target_commit": "x", "started_at": 0}),
+ encoding="utf-8",
+ )
+ assert read_update_lock(tmp_path) is None
+
+ def test_read_handles_corrupt_payload(self, tmp_path):
+ from repowise.cli.helpers import (
+ UPDATE_LOCK_FILENAME,
+ ensure_repowise_dir,
+ read_update_lock,
+ )
+
+ ensure_repowise_dir(tmp_path)
+ (tmp_path / ".repowise" / UPDATE_LOCK_FILENAME).write_text(
+ "not json", encoding="utf-8"
+ )
+ assert read_update_lock(tmp_path) is None
+
+
# ---------------------------------------------------------------------------
# Git HEAD
# ---------------------------------------------------------------------------
diff --git a/tests/unit/cli/test_hooks_legacy_migration.py b/tests/unit/cli/test_hooks_legacy_migration.py
new file mode 100644
index 000000000..47daee188
--- /dev/null
+++ b/tests/unit/cli/test_hooks_legacy_migration.py
@@ -0,0 +1,116 @@
+"""Tests for the post-commit hook installer's legacy-block migration.
+
+Pre-marker repowise versions wrote a hook body without start/end markers
+that ended in `exit 0`, which made any later marker-based block dead code.
+On Windows the legacy invocation also tended to fail every commit because
+`uv run repowise update` would rebuild the venv from scratch. The
+installer must detect those bodies and excise them before appending the
+new marker block.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from repowise.cli.hooks import install, status, _strip_legacy_block
+
+
+def git_repo(tmp_path):
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ return tmp_path
+
+
+_LEGACY_BODY = """\
+#!/bin/sh
+# post-commit hook: auto-update repowise wiki after each commit
+# Runs in the background so it doesn't block your terminal
+
+echo "[repowise] Triggering incremental wiki update..."
+
+(
+ cd "$(git rev-parse --show-toplevel)" || exit 1
+ powershell.exe -Command "uv run repowise update" > /tmp/repowise-update.log 2>&1
+) &
+
+exit 0
+"""
+
+
+def test_strip_legacy_block_removes_only_legacy_section():
+ after_block = "# my own custom hook\necho 'kept'\n"
+ content = _LEGACY_BODY + "\n" + after_block
+
+ cleaned, stripped = _strip_legacy_block(content)
+ assert stripped is True
+ assert "Triggering incremental wiki update" not in cleaned
+ assert "/tmp/repowise-update.log" not in cleaned
+ assert "echo 'kept'" in cleaned
+
+
+def test_strip_legacy_block_noop_for_clean_content():
+ content = "#!/bin/sh\necho 'fine'\n"
+ cleaned, stripped = _strip_legacy_block(content)
+ assert stripped is False
+ assert cleaned == content
+
+
+class TestInstallMigratesLegacyHook:
+ def test_install_over_legacy_replaces_with_marker_block(self, git_repo):
+ hook = git_repo / ".git" / "hooks" / "post-commit"
+ hook.parent.mkdir(parents=True, exist_ok=True)
+ hook.write_text(_LEGACY_BODY, encoding="utf-8")
+
+ result = install(git_repo)
+ assert result == "installed"
+
+ content = hook.read_text(encoding="utf-8")
+ assert "# repowise-hook-start" in content
+ assert "# repowise-hook-end" in content
+ # Legacy fingerprints must be gone
+ assert "Triggering incremental wiki update" not in content
+ assert "/tmp/repowise-update.log" not in content
+ # And there must be no leftover `exit 0` that would shadow the new
+ # marker block.
+ assert "\nexit 0\n" not in content
+
+ def test_install_over_legacy_plus_marker_returns_migrated(self, git_repo):
+ # Existing file already has both: legacy block (unreachable) AND
+ # a marker block. Installer should strip the legacy half and
+ # report the migration.
+ from repowise.cli.hooks import _HOOK_SCRIPT
+
+ hook = git_repo / ".git" / "hooks" / "post-commit"
+ hook.parent.mkdir(parents=True, exist_ok=True)
+ hook.write_text(
+ _LEGACY_BODY + "\n" + _HOOK_SCRIPT, encoding="utf-8"
+ )
+
+ result = install(git_repo)
+ assert result == "migrated legacy hook"
+
+ content = hook.read_text(encoding="utf-8")
+ assert "Triggering incremental wiki update" not in content
+ assert "# repowise-hook-start" in content
+
+ def test_install_already_marker_only_is_idempotent(self, git_repo):
+ install(git_repo) # First install — fresh
+ result = install(git_repo) # Second install — should be a no-op
+ assert result == "already installed"
+ assert status(git_repo) == "installed"
+
+ def test_install_preserves_unrelated_hook_content(self, git_repo):
+ hook = git_repo / ".git" / "hooks" / "post-commit"
+ hook.parent.mkdir(parents=True, exist_ok=True)
+ hook.write_text(
+ "#!/bin/sh\n# my project's lint hook\necho 'lint'\n",
+ encoding="utf-8",
+ )
+
+ install(git_repo)
+
+ content = hook.read_text(encoding="utf-8")
+ assert "echo 'lint'" in content
+ assert "# repowise-hook-start" in content
diff --git a/tests/unit/cli/test_update_mode_resolution.py b/tests/unit/cli/test_update_mode_resolution.py
new file mode 100644
index 000000000..bfc3f7899
--- /dev/null
+++ b/tests/unit/cli/test_update_mode_resolution.py
@@ -0,0 +1,52 @@
+"""Tests for `repowise update`'s mode-resolution from state.
+
+`update_command` decides between full LLM regeneration and index-only mode
+in this priority order:
+
+ 1. Explicit `--index-only` flag → index-only.
+ 2. `--no-docs` → index-only; `--docs` → full.
+ 3. `state.docs_enabled` from `.repowise/state.json` (default: True).
+
+This is what lets the post-commit hook do the right thing without needing
+to know how the user originally indexed the repo.
+"""
+
+from __future__ import annotations
+
+from repowise.cli.commands.update_cmd import _resolve_index_only_mode as _resolve_mode
+
+
+class TestModeResolution:
+ def test_explicit_index_only_wins(self):
+ assert _resolve_mode(
+ index_only=True, docs_flag=True, state={"docs_enabled": True}
+ ) is True
+
+ def test_no_docs_flag_forces_index_only(self):
+ assert _resolve_mode(
+ index_only=False, docs_flag=False, state={"docs_enabled": True}
+ ) is True
+
+ def test_docs_flag_forces_full(self):
+ # User explicitly opts in to LLM regen even though state says no.
+ assert _resolve_mode(
+ index_only=False, docs_flag=True, state={"docs_enabled": False}
+ ) is False
+
+ def test_state_default_index_only(self):
+ # No flags → state value drives behavior.
+ assert _resolve_mode(
+ index_only=False, docs_flag=None, state={"docs_enabled": False}
+ ) is True
+
+ def test_state_default_full(self):
+ assert _resolve_mode(
+ index_only=False, docs_flag=None, state={"docs_enabled": True}
+ ) is False
+
+ def test_missing_field_defaults_to_full(self):
+ # Backward compat: state files written before docs_enabled existed
+ # must continue to behave as full-mode (the original behavior).
+ assert _resolve_mode(
+ index_only=False, docs_flag=None, state={}
+ ) is False