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.

feat(init): install the post-commit hook by default, with the guards that make it safe (#2143)

Raghav Chamadiya7791e6401fa9
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index fd74a6247..289df2b74 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -19,7 +19,7 @@ crashes or blocks your agent.
| Hook | Family | Installed by | Fires on | What it does |
|------|--------|--------------|----------|--------------|
-| **Post-commit auto-sync** | git | `repowise hook install` (or the `repowise init` prompt) | every `git commit` | Runs `repowise update` in the background so the wiki tracks your code |
+| **Post-commit auto-sync** | git | `repowise init` by default (`--no-hook` skips it), or `repowise hook install` | every `git commit` | Runs `repowise update` in the background so the wiki tracks your code |
| **SessionStart context** | Claude Code | `repowise init` | session `startup` / `resume` / `clear` | Live index-freshness line, core-tool trust rule, and the standing decisions relevant to this session |
| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / repowise MCP calls | Graph context on searches, read-intelligence notices, and edit-time "governed by" decision notices |
| **Wrong-path rescue** | Claude Code | `repowise init` | a `Read` / `Edit` / `Write` / `Grep` / `Glob` / `NotebookEdit` that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise |
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 7f1b93547..af2dc8b50 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -156,6 +156,7 @@ Resolve refs with `repowise expand <ref>` from a shell, or
| `index_behind` | Whenever the live-vs-indexed comparison ran: `true` if HEAD has moved (alongside `stale_warning` when served content actually changed), `false` if the commits match. Absent means the comparison could not run (no git, or a repo-level tool that serves no file content) |
| `embedder_degraded` | Whenever an embedder is resolved, `true` or `false`. Absent means none was initialised |
| `embedder`, `embedder_warning` | Only when the embedder fell back to a mock/degraded mode |
+| `newer_release` | Once per server process, in the first response after the background check sees a newer repowise on PyPI: the available version, the running one, and that the MCP server needs a restart after upgrading. Repeats only for a later, newer version |
| `response_budget` | Always: `limit_chars` (the ceiling that applied), `tier` (`default` or `expanded`, chosen by whether the call passed an expansion argument), `serialized_chars` (the size delivered) |
| `scope_hint` | `get_context` and `get_answer`, when knowledge-graph layers exist that contain none of the served paths: one sentence naming up to three of them with file counts, so an agent knows which areas the answer did not touch |
| `complete` | When the response served whole units: how many symbol bodies (bounds verified against the live file) or whole files, and that they need not be re-opened. Sliced bodies and partial ranges are never counted |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index fdaa94f28..09a618d5a 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -172,7 +172,8 @@ All three reach the indexing knobs; the LLM-only knobs appear only when model-wr
| `--agents` / `--no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. |
| `--codex` / `--no-codex` | Generate or skip project-local Codex MCP/hooks setup. Interactive runs prompt when Codex CLI is installed and logged in; non-interactive runs require `--codex`. |
| `--distill-hook` / `--no-distill-hook` | Install or skip the Distill command-rewrite hook (Claude Code PreToolUse). Strictly opt-in: interactive runs prompt (default No); `--no-distill-hook` also gates the repo off in config so a globally installed hook stays inert here. In workspace mode the verdict applies to every selected repo. See [DISTILL.md](../agent/DISTILL.md). |
-| `--editor-setup` / `--no-editor-setup` | Wire repowise into your editors, both halves at once. Machine-wide: the Claude Code (`~/.claude/settings.json`) and Claude Desktop MCP server entry, plus the Claude Code PostToolUse/SessionStart hooks. Project-local: `.mcp.json`, `.claude/CLAUDE.md`, `.vscode/mcp.json`, `.vscode/extensions.json`. Default: on. `--no-editor-setup` indexes the repo writing nothing into it and nothing outside it — only `.repowise/` is touched — which is what you want for a scratch checkout, a throwaway venv, a git worktree, or a CI run: each config holds a single `repowise` MCP key, so a second `init` repoints it at the newest repo instead of adding a second entry. `repowise mcp .` still prints the config to connect a client by hand. It also skips the `--distill-hook` offer, which installs a user-level hook; `--no-distill-hook`, `--no-claude-md` and `--no-agents-md` still record their opt-outs in this repo's config, because those flags mean "never", not "not this run". `REPOWISE_SKIP_EDITOR_SETUP=1` is the same switch for CI and sandboxes, and it wins: with it set, an explicit `--editor-setup` does not turn setup back on. |
+| `--hook` / `--no-hook` | Install or skip the post-commit hook that runs `repowise update` after each commit. Default: on. Interactive runs ask; `--yes` and non-interactive runs install it and print how to undo it (`repowise hook uninstall`). `--no-editor-setup` skips it too, since a git hook is a write outside `.repowise/`. In workspace mode the choice applies to every selected repo. |
+| `--editor-setup` / `--no-editor-setup` | Wire repowise into your editors, both halves at once. Machine-wide: the Claude Code (`~/.claude/settings.json`) and Claude Desktop MCP server entry, plus the Claude Code PostToolUse/SessionStart hooks. Project-local: `.mcp.json`, `.claude/CLAUDE.md`, `.vscode/mcp.json`, `.vscode/extensions.json`. Default: on. `--no-editor-setup` indexes the repo writing nothing into it and nothing outside it — only `.repowise/` is touched — which is what you want for a scratch checkout, a throwaway venv, a git worktree, or a CI run: each config holds a single `repowise` MCP key, so a second `init` repoints it at the newest repo instead of adding a second entry. `repowise mcp .` still prints the config to connect a client by hand. It also skips the post-commit auto-sync hook (a write into the git hooks directory) and the `--distill-hook` offer, which installs a user-level hook; `--no-distill-hook`, `--no-claude-md` and `--no-agents-md` still record their opt-outs in this repo's config, because those flags mean "never", not "not this run". `REPOWISE_SKIP_EDITOR_SETUP=1` is the same switch for CI and sandboxes, and it wins: with it set, an explicit `--editor-setup` does not turn setup back on. |
| `--save-key` / `--no-save-key` | Save the provider API key this run authenticated with into `.repowise/.env` (git-ignored, owner-only). Default: on, because a scripted `init` that succeeds must leave a repo whose MCP server can actually answer, and a key supplied through the environment would otherwise vanish with the shell that set it. The file is what `repowise mcp`, `serve` and `update` read back; without it `get_answer` degrades to `no-llm-provider` and returns retrieval-only output. Use `--no-save-key` when the key is injected per-process (CI secrets, a shared machine) and must not reach disk; `REPOWISE_NO_SAVE_KEY=1` is the same switch for CI and sandboxes. Answering No to the interactive key prompt also wins over the default. Note this writes one line to the repo's `.gitignore`, so pair it with `--no-save-key` when you need `--no-editor-setup`'s "nothing written into the repo" guarantee. |
| `--seed-from` | Seed the index from an explicit base checkout instead of the auto-detected one. Rarely needed: inside a linked git worktree the base is detected and seeded automatically. See [WORKTREES.md](../scale/WORKTREES.md). |
| `--no-seed` | Disable worktree auto-seeding and run a full init even inside a linked worktree. |
diff --git a/docs/scale/AUTO_SYNC.md b/docs/scale/AUTO_SYNC.md
index 81ad3f442..338c26ce9 100644
--- a/docs/scale/AUTO_SYNC.md
+++ b/docs/scale/AUTO_SYNC.md
@@ -21,7 +21,7 @@ local development.
### Setup
-`repowise init` will offer to install the hook automatically at the end
+`repowise init` installs the hook by default (interactive runs ask first; `--no-hook` skips it) at the end
of the setup wizard. You can also install or manage it manually:
```bash
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.py
index cea7cb2f5..a2cc51c57 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
@@ -155,6 +155,44 @@ def _provider_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:
return checks
+def _repowise_dir_check(repowise_dir: _DoctorPath) -> DoctorCheck:
+ """Exists and writable, probed with a real file: os.access lies on Windows."""
+ if not repowise_dir.exists():
+ return _check(".repowise/ directory", False, f"{repowise_dir} (run 'repowise init')")
+ probe = repowise_dir / ".doctor-write-probe"
+ try:
+ probe.write_text("", encoding="utf-8")
+ probe.unlink()
+ except OSError as exc:
+ return _check(
+ ".repowise/ directory",
+ False,
+ f"{repowise_dir} is not writable ({exc.strerror or exc}); fix its permissions",
+ )
+ return _check(".repowise/ directory", True, str(repowise_dir))
+
+
+def _autosync_hook_check(repo_path: _DoctorPath) -> DoctorCheck:
+ """Report the post-commit hook through hooks.status, which asks git for the
+ real hooks directory, so worktrees and core.hooksPath read correctly."""
+ try:
+ from repowise.cli.hooks import status as _hook_status
+
+ state = _hook_status(repo_path)
+ except Exception as exc:
+ return _check("Post-commit hook", True, f"could not read hook state ({exc})")
+ if state.startswith("installed"):
+ return _check("Post-commit hook", True, state)
+ if state == "not installed":
+ return _check(
+ "Post-commit hook",
+ True,
+ "not installed; the index updates only when you run 'repowise update' "
+ "('repowise hook install' turns auto-sync on)",
+ )
+ return _check("Post-commit hook", True, state)
+
+
def _run_repo_checks(
repo_path: _DoctorPath, repair: bool, *, fmt: str = "table"
) -> tuple[bool, list[DoctorCheck]]:
@@ -177,9 +215,15 @@ def _run_repo_checks(
except Exception:
checks.append(_check("Git repository", False, "Not a git repo"))
- # 2. .repowise/ exists?
+ # 2. .repowise/ exists and takes a write? The MCP server refuses to start
+ # on a directory it cannot write, so an existence-only row would say OK
+ # for the one state that makes every tool call fail.
repowise_dir = get_repowise_dir(repo_path)
- checks.append(_check(".repowise/ directory", repowise_dir.exists(), str(repowise_dir)))
+ checks.append(_repowise_dir_check(repowise_dir))
+
+ # 2b. Post-commit auto-sync hook. init installs it by default; not having
+ # it is a choice (--no-hook), so its absence is informational, not a fail.
+ checks.append(_autosync_hook_check(repo_path))
# 3. Database connectable?
db_path = repowise_dir / "wiki.db"
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/workspace_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/workspace_checks.py
index a6a27c19f..ab022976d 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/workspace_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/workspace_checks.py
@@ -158,5 +158,5 @@ def _check_mcp_registered(ws_root: _DoctorPath) -> None:
else:
console.print(
" [dim]MCP: no claude_desktop_config.json entry found — run "
- "`repowise hook install` to register.[/dim]"
+ "`repowise init` to register.[/dim]"
)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
index 724e4df2d..de535ee03 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/_interactive.py
@@ -167,30 +167,87 @@ def offer_hook_install(
repo_paths: list[Path],
aliases: list[str] | None = None,
*,
+ flag: bool | None = None,
yes: bool = False,
+ no_editor_setup: bool = False,
) -> None:
- """Interactively offer to install post-commit hooks for auto-sync.
-
- For a single repo, asks yes/no. For multiple repos (workspace), lets the
- user pick which repos to install hooks for. When ``yes`` is True all
- interactive prompts are skipped (no hook is installed silently).
+ """Install the post-commit auto-sync hook, asking only when someone can answer.
+
+ ``flag`` is the resolved ``--hook/--no-hook`` value. ``True`` installs
+ without a prompt; ``False`` skips and says how to install later; ``None``
+ prompts when interactive and otherwise installs and prints one line naming
+ ``repowise hook uninstall``, which is the consent pattern for a default
+ that is on. ``--yes`` and a missing terminal both take that install path:
+ they are the routes the product recommends, and a hook they silently
+ skipped is why most indexes went stale.
+
+ A git hook is a write outside ``.repowise/``, so ``--no-editor-setup`` (or
+ ``REPOWISE_SKIP_EDITOR_SETUP``) keeps it off, the way it keeps the distill
+ rewrite hook off; only an explicit ``--hook`` is told why nothing happened.
+ A failed install is reported and never fails the run: the index and wiki
+ are already written by the time this runs.
"""
- if yes:
- return # --yes: skip all interactive prompts
- if not sys.stdin.isatty():
- return # Non-interactive — skip
+ from repowise.cli.editor_setup import is_editor_setup_disabled
- try:
- _offer_hook_install_prompts(console_obj, repo_paths, aliases)
- except (click.Abort, EOFError):
- # isatty() claimed a terminal that cannot answer (Windows Git Bash
- # ``< /dev/null``, pty wrappers, ``docker run -t`` without -i). This is
- # the last step of a run whose index and wiki are already written, and
- # an optional hook is not worth failing it over: decline and exit
- # clean. Ctrl-C lands here too, which asks for the same outcome.
+ if not repo_paths:
+ return
+
+ if is_editor_setup_disabled(no_editor_setup):
+ if flag:
+ console_obj.print(
+ " [dim]Post-commit hook not installed: editor setup is off for this "
+ "run. Run 'repowise hook install' to set it up.[/dim]"
+ )
+ return
+
+ if flag is False:
console_obj.print(
- "\n [dim]Skipped the hook. Run 'repowise hook install' later to set it up.[/dim]"
+ " [dim]Skipped the post-commit hook. Run 'repowise hook install' later "
+ "to set it up.[/dim]"
)
+ return
+
+ if flag is None and not yes and sys.stdin.isatty():
+ try:
+ _offer_hook_install_prompts(console_obj, repo_paths, aliases)
+ except (click.Abort, EOFError):
+ # isatty() claimed a terminal that cannot answer (Windows Git Bash
+ # ``< /dev/null``, pty wrappers, ``docker run -t`` without -i). This
+ # is the last step of a run whose index and wiki are already
+ # written, and an optional hook is not worth failing it over:
+ # decline and exit clean. Ctrl-C lands here too.
+ console_obj.print(
+ "\n [dim]Skipped the hook. Run 'repowise hook install' later to set it up.[/dim]"
+ )
+ return
+
+ installed = 0
+ for i, rp in enumerate(repo_paths):
+ label = aliases[i] if aliases else rp.name
+ if _install_hook(console_obj, rp, label):
+ installed += 1
+ if installed:
+ undo = "repowise hook uninstall" + (" --workspace" if len(repo_paths) > 1 else "")
+ console_obj.print(
+ f" [dim]Auto-sync is on: repowise update runs after each commit. "
+ f"Run '{undo}' to turn it off.[/dim]"
+ )
+
+
+def _install_hook(console_obj: Any, repo_path: Path, label: str) -> bool:
+ """Install one repo's hook and report it. Returns whether it is in place."""
+ from repowise.cli.hooks import install
+
+ try:
+ result = install(repo_path)
+ except Exception as exc: # a hook is not worth failing a finished init over
+ console_obj.print(f" [{WARN}]{label}: post-commit hook not installed ({exc})[/]")
+ return False
+ if result.startswith("not "):
+ console_obj.print(f" [dim]{label}: no post-commit hook, {result}.[/dim]")
+ return False
+ console_obj.print(f" [{OK}]✓[/] {label}: post-commit hook {result}")
+ return True
def _offer_hook_install_prompts(
@@ -199,7 +256,7 @@ def _offer_hook_install_prompts(
aliases: list[str] | None,
) -> None:
"""Ask which repos get a post-commit hook, and install it. Prompts."""
- from repowise.cli.hooks import install, status
+ from repowise.cli.hooks import status
# Filter to repos that don't already have the hook
candidates: list[tuple[Path, str]] = []
@@ -220,8 +277,7 @@ def _offer_hook_install_prompts(
if len(candidates) == 1:
rp, label = candidates[0]
if click.confirm(f" Install post-commit hook for {label}?", default=True):
- result = install(rp)
- console_obj.print(f" [{OK}]✓[/] {label}: {result}")
+ _install_hook(console_obj, rp, label)
else:
console_obj.print(" [dim]Skipped. Run 'repowise hook install' later to set up.[/dim]")
else:
@@ -249,9 +305,8 @@ def _offer_hook_install_prompts(
for idx in selected_indices:
if 0 <= idx < len(candidates):
rp, label = candidates[idx]
- result = install(rp)
- console_obj.print(f" [{OK}]✓[/] {label}: {result}")
- installed += 1
+ if _install_hook(console_obj, rp, label):
+ installed += 1
if installed == 0:
console_obj.print(
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index cc1e5a308..fb3ecce61 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -620,6 +620,19 @@ def _run_generation_phase(
"applies to every selected repo."
),
)
+ "--hook/--no-hook",
+ "hook",
+ default=None,
+ help=(
+ "Install the post-commit hook that runs `repowise update` after each "
+ "commit, so the index stays current without anyone typing it. Default: "
+ "on. Interactive runs ask; --yes and non-interactive runs install it and "
+ "print how to undo it (`repowise hook uninstall`). --no-hook skips it. "
+ "--no-editor-setup skips it too, since a git hook is a write outside "
+ ".repowise/. In workspace mode the choice applies to every selected repo."
+ ),
+)
@click.option(
"--editor-setup/--no-editor-setup",
"editor_setup",
@@ -799,6 +812,7 @@ def init_command(
agents_md: bool | None,
codex_setup: bool | None,
distill_hook: bool | None,
+ hook: bool | None,
editor_setup: bool,
save_key: bool,
include_submodules: bool,
@@ -962,6 +976,7 @@ def init_command(
agents_md=agents_md,
codex_setup=codex_setup,
distill_hook=distill_hook,
+ hook=hook,
editor_setup=editor_setup,
save_key=save_key,
include_submodules=include_submodules,
@@ -1793,8 +1808,14 @@ def init_command(
embedder_name_resolved=embedder_name_resolved,
)
- # Offer to install post-commit hook (both index-only and full modes)
- offer_hook_install(console, [repo_path], yes=yes)
+ # Post-commit auto-sync hook (both index-only and full modes)
+ offer_hook_install(
+ console,
+ [repo_path],
+ flag=hook,
+ yes=yes,
+ no_editor_setup=not editor_setup,
+ )
# Opt-in distill command-rewrite hook for Claude Code. The workspace flow
# runs its own offer across all selected repos inside _workspace_init.
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index 7dcc44b35..51aea4f30 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -584,6 +584,7 @@ def _workspace_init(
agents_md: bool | None,
codex_setup: bool | None,
distill_hook: bool | None,
+ hook: bool | None,
editor_setup: bool,
save_key: bool,
include_submodules: bool,
@@ -871,15 +872,17 @@ def _workspace_init(
docs_outcomes=docs_outcomes,
)
- # Offer to install post-commit hooks. Skipped on a dry run, which must
- # not write anything.
+ # Post-commit auto-sync hooks, the same default for every indexed repo.
+ # Skipped on a dry run, which must not write anything.
indexed_repos = [repo for repo in selected if repo.alias not in [e[0] for e in errors]]
if indexed_repos and not dry_run:
offer_hook_install(
console,
[r.path for r in indexed_repos],
aliases=[r.alias for r in indexed_repos],
+ flag=hook,
yes=yes,
+ no_editor_setup=not editor_setup,
)
# Opt-in distill command-rewrite hook for Claude Code: one user-level
# install, with the verdict recorded per repo. Applied to *all* selected
diff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
index 231b6fd40..6ce3d0f08 100644
--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
@@ -188,14 +188,19 @@ def mcp_command(
pass
from repowise.server.mcp_server import run_mcp
+ from repowise.server.mcp_server._server import StoreUnavailableError
tools_override: str | None = "all" if all_tools else tools
- run_mcp(
- transport=transport,
- repo_path=str(repo_path),
- host=resolved_host,
- port=port,
- tools=tools_override,
- workspace_mode=not no_workspace,
- )
+ try:
+ run_mcp(
+ transport=transport,
+ repo_path=str(repo_path),
+ host=resolved_host,
+ port=port,
+ tools=tools_override,
+ workspace_mode=not no_workspace,
+ )
+ except StoreUnavailableError as exc:
+ # One line on stderr and exit 1, not a traceback the host respawns on.
+ raise click.ClickException(str(exc)) from exc
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.py
index 93879e7e9..35c0dd425 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py
@@ -23,6 +23,41 @@ _GLOBAL_CONFIG_DIR = Path.home() / ".repowise"
_SERVE_LOCK_NAME = "serve.lock.json"
+#: How often a running ``serve`` re-reads release currency. The PyPI fetch is
+#: TTL-cached on disk for a day, so this bounds the print, not the network.
+_UPDATE_ADVISORY_INTERVAL_S = 6 * 3600
+
+
+def _update_advisory_tick(announced: set[str]) -> bool:
+ """Print the advisory for a release not yet announced. Never raises."""
+ try:
+ from repowise.cli.update_check import get_cli_update_check_cached
+ from repowise.cli.whats_new import render_update_advisory
+
+ check = get_cli_update_check_cached()
+ if not check.update_available or check.latest_version in announced:
+ return False
+ if render_update_advisory(console, check):
+ announced.add(check.latest_version)
+ return True
+ except Exception:
+ pass
+ return False
+
+
+def _start_update_advisory_loop(announced: set[str]) -> None:
+ """Re-run the advisory tick on a daemon thread; it dies with the process."""
+ import threading
+ import time
+
+ def _loop() -> None:
+ while True:
+ time.sleep(_UPDATE_ADVISORY_INTERVAL_S)
+ _update_advisory_tick(announced)
+
+ threading.Thread(target=_loop, name="update-advisory", daemon=True).start()
+
+
def _serve_lock_path(cwd: Path | None = None) -> Path | None:
"""Return where the serve lockfile belongs for this directory, if anywhere.
@@ -570,17 +605,14 @@ def serve_command(
console.print("[red]uvicorn is not installed. Install it with: pip install repowise[/red]")
raise SystemExit(1) from None
- # One-line, non-blocking "newer release available" advisory at startup.
- # Best-effort and interactive-only; the cached check keeps it off the network
- # on most launches.
+ # One-line, non-blocking "newer release available" advisory at startup and
+ # then once per interval for as long as the server runs. Best-effort and
+ # interactive-only; the cached check keeps it off the network on most
+ # passes.
if console.is_terminal:
- try:
- from repowise.cli.update_check import get_cli_update_check_cached
- from repowise.cli.whats_new import render_update_advisory
-
- render_update_advisory(console, get_cli_update_check_cached())
- except Exception:
- pass
+ announced: set[str] = set()
+ _update_advisory_tick(announced)
+ _start_update_advisory_loop(announced)
# Load the local .repowise/.env (API keys written by `repowise init`) and
# seed the chat/search provider + embedder from .repowise/config.yaml. This
diff --git a/packages/cli/src/repowise/cli/hook_ledger.py b/packages/cli/src/repowise/cli/hook_ledger.py
index 5b55eda97..75de7f10d 100644
--- a/packages/cli/src/repowise/cli/hook_ledger.py
+++ b/packages/cli/src/repowise/cli/hook_ledger.py
@@ -173,6 +173,7 @@ def _open_injections(repo_path: Path | str) -> sqlite3.Connection | None:
key = str(repo_path)
if key in _CONN:
return _CONN[key]
+ import contextlib
import sqlite3
db_dir = os.path.join(key, ".repowise", "sessions")
@@ -180,8 +181,12 @@ def _open_injections(repo_path: Path | str) -> sqlite3.Connection | None:
try:
os.makedirs(db_dir, exist_ok=True)
conn = sqlite3.connect(db_path, timeout=1)
- conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=1000")
+ # The same tolerance as core.sqlite_pragmas, inline because this
+ # module may not import repowise.core. A switch that loses the lock
+ # race must not turn the ledger off for the whole process.
+ with contextlib.suppress(sqlite3.OperationalError):
+ conn.execute("PRAGMA journal_mode=WAL")
conn.execute(_INJECTIONS_TABLE_SQL)
conn.execute(_HOOK_RUNS_TABLE_SQL)
conn.execute(_REWRITE_RUNS_TABLE_SQL)
diff --git a/packages/cli/src/repowise/cli/hooks.py b/packages/cli/src/repowise/cli/hooks.py
index 65458a65b..32f18357d 100644
--- a/packages/cli/src/repowise/cli/hooks.py
+++ b/packages/cli/src/repowise/cli/hooks.py
@@ -57,13 +57,21 @@ _LEGACY_HOOK_FINGERPRINTS = (
# The outer ``{ ... } &`` brace group ensures the queued marker is written
# synchronously (so the augment hook sees it on the *next* tool call after
# the commit) before the heavy update spawns into the background.
+#
+# Two gates keep a default-on hook boring. It fires only when
+# ``.repowise/state.json`` exists, which is the precondition ``repowise
+# update`` itself checks, so a dry-run directory or a deleted store does not
+# fail on every commit forever. And when ``repowise`` is not on PATH it looks
+# only in the repo's own ``.venv``; the old ``uv run`` fallback resolved
+# whatever project ``uv`` found above the repo, on every commit, in repos
+# that were not Python projects at all.
_HOOK_SCRIPT = """\
# repowise-hook-start
# Auto-syncs repowise wiki after each commit (background, non-blocking).
# Installed by: repowise hook install
{
ROOT=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0
- [ -d "$ROOT/.repowise" ] || exit 0
+ [ -f "$ROOT/.repowise/state.json" ] || exit 0
HEAD=$(git rev-parse HEAD 2>/dev/null) || HEAD=""
TS=$(date +%s 2>/dev/null) || TS=""
if [ -n "$TS" ]; then
@@ -79,8 +87,10 @@ _HOOK_SCRIPT = """\
cd "$ROOT" || exit 1
if command -v repowise >/dev/null 2>&1; then
repowise update >> "$LOG" 2>&1
- elif command -v uv >/dev/null 2>&1; then
- uv run repowise update >> "$LOG" 2>&1
+ elif [ -x "$ROOT/.venv/bin/repowise" ]; then
+ "$ROOT/.venv/bin/repowise" update >> "$LOG" 2>&1
+ elif [ -x "$ROOT/.venv/Scripts/repowise.exe" ]; then
+ "$ROOT/.venv/Scripts/repowise.exe" update >> "$LOG" 2>&1
fi
) &
} >/dev/null 2>&1
@@ -137,6 +147,19 @@ def _hooks_dir(repo_path: Path) -> Path | None:
return root / ".git" / "hooks"
+def _is_shell_hook(content: str) -> bool:
+ """Whether an existing hook file can take an appended POSIX sh block.
+
+ A hook with no shebang, or a sh, bash, dash, zsh or ksh one, can. A hook
+ written for node or python cannot, and appending shell to it would break
+ the user's own hook on every commit after this one.
+ """
+ first = content.split("\n", 1)[0].strip()
+ if not first.startswith("#!"):
+ return True
+ return re.search(r"\b(sh|bash|dash|zsh|ksh)\b", first) is not None
+
+
def _husky_user_hook_dir(hooks_dir: Path) -> Path:
"""Redirect husky's generated shim directory to its user-hook directory.
@@ -294,6 +317,8 @@ def install(repo_path: Path) -> str:
migrated_legacy = False
if hook_path.exists():
content = hook_path.read_text(encoding="utf-8")
+ if not _is_shell_hook(content):
+ return "not installed: the existing post-commit hook is not a shell script"
content, migrated_legacy = _strip_legacy_block(content)
if migrated_legacy:
hook_path.write_text(content, encoding="utf-8")
diff --git a/packages/core/src/repowise/core/distill/store.py b/packages/core/src/repowise/core/distill/store.py
index b36ba3412..34a176869 100644
--- a/packages/core/src/repowise/core/distill/store.py
+++ b/packages/core/src/repowise/core/distill/store.py
@@ -21,6 +21,7 @@ import structlog
from repowise.core.distill import tracking
from repowise.core.distill.markers import REF_LENGTH, is_valid_ref
+from repowise.core.sqlite_pragmas import apply_sqlite_pragmas
logger = structlog.get_logger(__name__)
@@ -32,6 +33,9 @@ DEFAULT_TTL_DAYS = 7
#: Compressed-content size cap; oldest rows pruned first when exceeded.
DEFAULT_MAX_MB = 50
+#: Retry window for a contended open, in milliseconds.
+_BUSY_TIMEOUT_MS = 5000
+
_SCHEMA = """
CREATE TABLE IF NOT EXISTS omissions (
ref TEXT PRIMARY KEY,
@@ -104,9 +108,7 @@ class OmissionStore:
self.max_mb = max_mb
db_path.parent.mkdir(parents=True, exist_ok=True)
self._conn = sqlite3.connect(db_path)
- self._conn.execute("PRAGMA journal_mode=WAL")
- self._conn.execute("PRAGMA synchronous=NORMAL")
- self._conn.execute("PRAGMA busy_timeout=5000")
+ apply_sqlite_pragmas(self._conn, _BUSY_TIMEOUT_MS)
self._conn.executescript(_SCHEMA)
self._conn.commit()
diff --git a/packages/core/src/repowise/core/precedent/store.py b/packages/core/src/repowise/core/precedent/store.py
index a9daa4e7e..c01ae580e 100644
--- a/packages/core/src/repowise/core/precedent/store.py
+++ b/packages/core/src/repowise/core/precedent/store.py
@@ -29,6 +29,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from repowise.core.fts_query import build_fts5_query, meaningful_terms
+from repowise.core.sqlite_pragmas import apply_sqlite_pragmas
_log = logging.getLogger(__name__)
@@ -77,6 +78,9 @@ _RERANK_WINDOW_MAX = 50
#: the pointer was only ever provenance.
SOURCE_GONE_NOTE = " (source no longer on disk)"
+#: Retry window for a contended open, in milliseconds.
+_BUSY_TIMEOUT_MS = 5000
+
_SCHEMA = """
CREATE TABLE IF NOT EXISTS episodes (
id TEXT PRIMARY KEY,
@@ -228,9 +232,7 @@ class EpisodeStore:
self.max_rows = max_rows
db_path.parent.mkdir(parents=True, exist_ok=True)
self._conn = sqlite3.connect(db_path)
- self._conn.execute("PRAGMA journal_mode=WAL")
- self._conn.execute("PRAGMA synchronous=NORMAL")
- self._conn.execute("PRAGMA busy_timeout=5000")
+ apply_sqlite_pragmas(self._conn, _BUSY_TIMEOUT_MS)
self._conn.executescript(_SCHEMA)
self._conn.commit()
self.fts_enabled = self._ensure_fts()
diff --git a/packages/core/src/repowise/core/sessions/staging.py b/packages/core/src/repowise/core/sessions/staging.py
index 2cb27e8dc..f147aaabf 100644
--- a/packages/core/src/repowise/core/sessions/staging.py
+++ b/packages/core/src/repowise/core/sessions/staging.py
@@ -33,6 +33,8 @@ import time
from pathlib import Path
from typing import Any
+from repowise.core.sqlite_pragmas import apply_sqlite_pragmas
+
SESSIONS_DIRNAME = "sessions"
SESSIONS_DB_FILENAME = "sessions.db"
@@ -61,6 +63,9 @@ MAX_SPAN_ATTEMPTS = 3
#: enough to promote; beyond a handful the extra ids only pad evidence.
_MAX_SESSIONS_TRACKED = 20
+#: Retry window for a contended open, in milliseconds.
+_BUSY_TIMEOUT_MS = 5000
+
_SCHEMA = """
CREATE TABLE IF NOT EXISTS raw_candidates (
hash TEXT PRIMARY KEY,
@@ -231,9 +236,7 @@ class SessionStagingStore:
self.db_path = db_path
db_path.parent.mkdir(parents=True, exist_ok=True)
self._conn = sqlite3.connect(db_path)
- self._conn.execute("PRAGMA journal_mode=WAL")
- self._conn.execute("PRAGMA synchronous=NORMAL")
- self._conn.execute("PRAGMA busy_timeout=5000")
+ apply_sqlite_pragmas(self._conn, _BUSY_TIMEOUT_MS)
self._conn.executescript(_SCHEMA)
_migrate_injections_columns(self._conn)
self._conn.commit()
diff --git a/packages/core/src/repowise/core/sqlite_pragmas.py b/packages/core/src/repowise/core/sqlite_pragmas.py
new file mode 100644
index 000000000..6a74afeb9
--- /dev/null
+++ b/packages/core/src/repowise/core/sqlite_pragmas.py
@@ -0,0 +1,40 @@
+"""Connection setup shared by the synchronous SQLite sidecar stores.
+
+The distill omissions, precedent and staged-decision stores, and the CLI hook
+ledger, all open plain :mod:`sqlite3` connections. This module holds the one
+pragma sequence they apply, in the order ``persistence/database.py`` applies
+it to the async engine. It stays on stdlib only because two of those stores
+sit on command paths where importing the engine module costs more than a
+second.
+"""
+
+from __future__ import annotations
+
+import logging
+import sqlite3
+
+log = logging.getLogger(__name__)
+
+
+def apply_sqlite_pragmas(conn: sqlite3.Connection, busy_timeout_ms: int) -> bool:
+ """Apply ``busy_timeout``, WAL and ``synchronous=NORMAL``. Never raises on WAL.
+
+ The stores used to issue the WAL switch bare, before any busy timeout.
+ The switch needs a short exclusive lock, so a concurrent reader or writer
+ on the same file made the constructor raise ``database is locked`` and
+ took the whole store down, at exactly the moment a post-commit update and
+ an editor hook were most likely to overlap. The timeout goes first so the
+ switch inherits its retry window; a switch that still fails is logged and
+ left alone. The store keeps the journal mode it has and every statement
+ still runs, so only readers concurrent with a writer lose out until a
+ later open succeeds. Returns whether the switch took.
+ """
+ conn.execute(f"PRAGMA busy_timeout={int(busy_timeout_ms)}")
+ switched = True
+ try:
+ conn.execute("PRAGMA journal_mode=WAL")
+ except sqlite3.OperationalError as exc:
+ switched = False
+ log.debug("sqlite: could not switch to WAL, keeping the current journal mode: %s", exc)
+ conn.execute("PRAGMA synchronous=NORMAL")
+ return switched
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index ecc803a4d..69a37042b 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -24,6 +24,7 @@ Usage:
from __future__ import annotations
import importlib
+import logging
import sys
from typing import Any
@@ -177,7 +178,17 @@ def ensure_full_surface() -> Any:
return _mcp
for module in dict.fromkeys(_TOOL_MODULES.values()):
- importlib.import_module(f"{__name__}.{module}")
+ try:
+ importlib.import_module(f"{__name__}.{module}")
+ except ImportError as exc:
+ # One tool's optional dependency must not take the whole surface
+ # down: a host respawns a server that dies at import, forever.
+ logging.getLogger("repowise.mcp").warning(
+ "repowise MCP: skipping tool module %s, cannot import %s: %s",
+ module,
+ exc.name or "a dependency",
+ exc,
+ )
from repowise.core.registry import mcp_tool_registry
from repowise.server.mcp_server._tool_selection import snapshot_full_surface
@@ -218,6 +229,8 @@ _STATE_NAMES = frozenset(
"_workspace_root",
"_cross_repo_enricher",
"_embedder_status",
+ "_release_check",
+ "_release_announced",
}
)
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 15a38a85e..2f413e2a2 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -348,6 +348,7 @@ def build_meta(
if repository is not None:
out.update(freshness_from_repo(repository, targets=targets))
out.update(_embedder_meta())
+ out.update(_release_meta())
if extra:
out.update(extra)
return out
@@ -484,6 +485,32 @@ def _embedder_meta() -> dict[str, Any]:
return out
+def _release_meta() -> dict[str, Any]:
+ """Name a newer repowise release once per process, in the first response
+ after the lifespan's poller sees it.
+
+ The stdio server never re-checks its own currency otherwise, and a client
+ that spawned it weeks ago keeps talking to that version until something
+ says so. One key, one time: repeating it on every call would charge the
+ caller's token budget for a fact it already has. A newer version seen
+ later in the same process is announced again, once.
+ """
+ from repowise.server.mcp_server import _state
+
+ check = getattr(_state, "_release_check", None)
+ if check is None or not check.update_available or not check.latest_version:
+ return {}
+ if check.latest_version == _state._release_announced:
+ return {}
+ _state._release_announced = check.latest_version
+ return {
+ "newer_release": (
+ f"repowise {check.latest_version} is available, this server runs "
+ f"{check.current_version}; upgrade and restart the MCP server"
+ )
+ }
+
+
def context_hint(targets: list[str], compact: bool, include: set[str] | None = None) -> str | None:
"""Hint for `get_context` callers.
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index e68f4ff72..10a584512 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -11,6 +11,7 @@ from typing import Any
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
+from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from repowise.core.persistence.database import (
@@ -29,6 +30,36 @@ from repowise.server.mcp_server import _state
_log = __import__("logging").getLogger("repowise.mcp")
+class StoreUnavailableError(RuntimeError):
+ """The repo-local index store cannot be created or opened.
+
+ Raised out of the lifespan so the process exits once with a message that
+ names the path and the fix. Before this the same failure escaped as a
+ bare traceback, and an MCP host treats a server that dies at startup as
+ one to respawn, so an unwritable .repowise became a crash loop. Click-free
+ because the server does not depend on the CLI; the mcp command turns it
+ into a clean non-zero exit.
+ """
+
+
+def _store_unavailable(
+ where: str | None, repo_path: str | None, exc: BaseException
+) -> StoreUnavailableError:
+ """``where`` is the repo-local directory, or None when an env URL is in use;
+ a configured database gets its own remedy, not the directory one."""
+ if where is None:
+ return StoreUnavailableError(
+ f"repowise MCP: cannot open the configured database: {exc}. "
+ "Check REPOWISE_DB_URL and that the database server is reachable."
+ )
+ repo = repo_path or "the repository"
+ return StoreUnavailableError(
+ f"repowise MCP: cannot open the index store at {where}: {exc}. "
+ f"Run 'repowise init' in {repo} to create it, or fix the permissions "
+ "on that directory."
+ )
+
+
# Per-embedder remediation hints, appended to the ERROR log and the `_meta`
# warning so a misconfiguration is actionable without grepping SDK tracebacks.
# Keyed by built-in embedder name; unknown/custom embedders fall back to the
@@ -258,6 +289,34 @@ def _resolve_embedder():
return KeylessEmbedder()
+#: How often the running server re-reads release currency. The PyPI fetch
+#: itself is TTL-cached on disk for a day and shared with the CLI advisory, so
+#: this bounds only the in-process refresh, never the network.
+_RELEASE_RECHECK_S = 6 * 3600
+
+
+async def _poll_release_check() -> None:
+ """Keep ``_state._release_check`` current for the life of the server.
+
+ Runs off the event loop thread because the miss path does a network
+ fetch; a tool call never waits on it. Never raises: a failed check is
+ recorded as unknown and retried on the next pass.
+ """
+ from repowise.core.upgrade.release import check_latest_version_cached
+ from repowise.server import __version__
+
+ while True:
+ try:
+ _state._release_check = await asyncio.to_thread(
+ check_latest_version_cached, __version__
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ _log.debug("repowise MCP: release check failed", exc_info=True)
+ await asyncio.sleep(_RELEASE_RECHECK_S)
+
+
async def _cancel_task(task: asyncio.Task) -> None:
"""Cancel a lifespan background task and swallow its unwind."""
task.cancel()
@@ -265,6 +324,19 @@ async def _cancel_task(task: asyncio.Task) -> None:
await task
+async def _abort_startup(*tasks: asyncio.Task) -> None:
+ """Undo the startup a lifespan raised out of, before it reached its teardown.
+
+ The success paths cancel the background tasks and clear the warmup event on
+ the way out; a startup failure has to leave the same state behind, or the
+ next lifespan in this process inherits a set-but-never-signalled event bound
+ to a loop that is gone.
+ """
+ for task in tasks:
+ await _cancel_task(task)
+ _state._lancedb_ready = None
+
+
async def _warm_lancedb() -> None:
"""Import lancedb once, off the event loop, and signal when it is done.
@@ -418,6 +490,7 @@ async def _lifespan(server: FastMCP):
# call can otherwise land mid-import and wedge the loop.
_state._lancedb_ready = asyncio.Event()
_warm_task = asyncio.create_task(_warm_lancedb(), name="lancedb-warmup")
+ _release_task = asyncio.create_task(_poll_release_check(), name="release-check")
# --- Workspace detection ------------------------------------------------
if _state._force_single_repo:
@@ -440,8 +513,17 @@ async def _lifespan(server: FastMCP):
embedder_factory=lambda: _resolve_embedder(),
)
- # Eagerly load the default repo so tools work immediately
- default_ctx = await registry.get_default()
+ # Eagerly load the default repo so tools work immediately. A failure
+ # here leaves the lifespan before its teardown, so the background
+ # tasks are cancelled by hand or they outlive the loop.
+ try:
+ default_ctx = await registry.get_default()
+ except (OSError, OperationalError) as exc:
+ await _abort_startup(_release_task, _warm_task)
+ raise _store_unavailable(str(ws_root), str(ws_root), exc) from exc
+ except BaseException:
+ await _abort_startup(_release_task, _warm_task)
+ raise
_state._registry = registry
_state._workspace_root = str(ws_root)
@@ -493,6 +575,7 @@ async def _lifespan(server: FastMCP):
yield
+ await _cancel_task(_release_task)
await _cancel_task(_warm_task)
_state._lancedb_ready = None
_state._cross_repo_enricher = None
@@ -509,26 +592,37 @@ async def _lifespan(server: FastMCP):
configured_db_url = get_configured_db_url()
# When repo path is set and no env override, prefer repo-local DB.
- if _state._repo_path and configured_db_url is None:
- db_path = get_repo_db_path(_state._repo_path)
- repowise_dir = db_path.parent
- if not repowise_dir.exists():
- _log.warning(
- "No .repowise directory at %s — run 'repowise init' first",
- _state._repo_path,
- )
- repowise_dir.mkdir(parents=True, exist_ok=True)
- elif not db_path.exists():
- _log.warning(
- "No wiki.db in %s — run 'repowise init' to generate the wiki",
- repowise_dir,
- )
+ store_location: str | None = None
+ try:
+ if _state._repo_path and configured_db_url is None:
+ db_path = get_repo_db_path(_state._repo_path)
+ repowise_dir = db_path.parent
+ store_location = str(repowise_dir)
+ if not repowise_dir.exists():
+ _log.warning(
+ "No .repowise directory at %s — run 'repowise init' first",
+ _state._repo_path,
+ )
+ repowise_dir.mkdir(parents=True, exist_ok=True)
+ elif not db_path.exists():
+ _log.warning(
+ "No wiki.db in %s — run 'repowise init' to generate the wiki",
+ repowise_dir,
+ )
- db_url = resolve_db_url(_state._repo_path)
+ db_url = resolve_db_url(_state._repo_path)
- _log.info("repowise MCP: initialising database…")
- engine = create_engine(db_url)
- await init_db(engine)
+ _log.info("repowise MCP: initialising database…")
+ engine = create_engine(db_url)
+ try:
+ await init_db(engine)
+ except (OSError, OperationalError):
+ await engine.dispose()
+ raise
+ except (OSError, OperationalError) as exc:
+ # A read-only or missing directory, or a .repowise that is a file.
+ await _abort_startup(_release_task, _warm_task)
+ raise _store_unavailable(store_location, _state._repo_path, exc) from exc
_state._session_factory = async_sessionmaker(
engine, expire_on_commit=False, class_=AsyncSession
@@ -559,6 +653,7 @@ async def _lifespan(server: FastMCP):
yield
+ await _cancel_task(_release_task)
await _cancel_task(_bg_task)
await _cancel_task(_warm_task)
_state._lancedb_ready = None
diff --git a/packages/server/src/repowise/server/mcp_server/_state.py b/packages/server/src/repowise/server/mcp_server/_state.py
index f83d232dc..be60de3b7 100644
--- a/packages/server/src/repowise/server/mcp_server/_state.py
+++ b/packages/server/src/repowise/server/mcp_server/_state.py
@@ -57,3 +57,12 @@ _test_impact_lock: tuple[Any, asyncio.Lock] | None = None
# (issue #306). Shape: {"active": str, "requested": str | None,
# "degraded": bool, "reason": str (only when degraded)}.
_embedder_status: dict[str, Any] | None = None
+
+# Release currency. The stdio server is the longest-lived process the product
+# runs and was the one path that never checked PyPI, so a client could sit on
+# an old release for weeks with no signal. ``_release_check`` is the latest
+# ``ReleaseCheck`` from the lifespan's poller (``None`` until the first pass);
+# ``_release_announced`` is the newest version ``_meta`` has already named, so
+# each newer release is surfaced once per process rather than on every call.
+_release_check: Any = None
+_release_announced: str | None = None
diff --git a/tests/unit/cli/test_doctor_autosync_hook.py b/tests/unit/cli/test_doctor_autosync_hook.py
new file mode 100644
index 000000000..ce3ed1803
--- /dev/null
+++ b/tests/unit/cli/test_doctor_autosync_hook.py
@@ -0,0 +1,79 @@
+"""Doctor reports the post-commit hook and probes that .repowise takes a write.
+
+init installs the hook by default, so doctor is where a hook that silently
+failed to install, or was deleted, becomes visible. The hook row goes
+through hooks.status, which asks git for the real hooks directory. The
+directory row used to test existence only, which read OK for the one state
+that stops the MCP server from starting at all.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+from repowise.cli import hooks
+from repowise.cli.commands.doctor_cmd import repo_checks
+
+
+def _git_repo(path: Path) -> Path:
+ subprocess.run(["git", "init", "-q"], cwd=path, check=True)
+ return path
+
+
+def test_hook_row_reads_installed_through_hooks_status(tmp_path: Path) -> None:
+ repo = _git_repo(tmp_path)
+ hooks.install(repo)
+ row = repo_checks._autosync_hook_check(repo)
+ assert row.ok
+ assert row.detail.startswith("installed")
+
+
+def test_hook_row_names_the_install_command_when_absent(tmp_path: Path) -> None:
+ repo = _git_repo(tmp_path)
+ row = repo_checks._autosync_hook_check(repo)
+ assert row.ok
+ assert "not installed" in row.detail
+ assert "repowise hook install" in row.detail
+
+
+def test_hook_row_follows_core_hooks_path(tmp_path: Path) -> None:
+ repo = _git_repo(tmp_path)
+ subprocess.run(["git", "config", "core.hooksPath", "my-hooks"], cwd=repo, check=True)
+ hooks.install(repo)
+ assert (repo / "my-hooks" / "post-commit").exists()
+ assert repo_checks._autosync_hook_check(repo).detail.startswith("installed")
+
+
+def test_hook_row_never_fails_doctor(tmp_path: Path, monkeypatch) -> None:
+ def _boom(_p: Path) -> str:
+ raise RuntimeError("git exploded")
+
+ monkeypatch.setattr(hooks, "status", _boom)
+ row = repo_checks._autosync_hook_check(tmp_path)
+ assert row.ok
+ assert "git exploded" in row.detail
+
+
+def test_directory_row_fails_when_missing(tmp_path: Path) -> None:
+ row = repo_checks._repowise_dir_check(tmp_path / ".repowise")
+ assert not row.ok
+ assert "repowise init" in row.detail
+
+
+def test_directory_row_fails_when_it_is_not_a_directory(tmp_path: Path) -> None:
+ target = tmp_path / ".repowise"
+ target.write_text("not a directory\n")
+ row = repo_checks._repowise_dir_check(target)
+ assert not row.ok
+ assert "not writable" in row.detail
+ assert "permissions" in row.detail
+
+
+def test_directory_row_passes_and_leaves_no_probe_behind(tmp_path: Path) -> None:
+ target = tmp_path / ".repowise"
+ target.mkdir()
+ row = repo_checks._repowise_dir_check(target)
+ assert row.ok
+ assert row.detail == str(target)
+ assert list(target.iterdir()) == []
diff --git a/tests/unit/cli/test_hook_default_on.py b/tests/unit/cli/test_hook_default_on.py
new file mode 100644
index 000000000..04a49126f
--- /dev/null
+++ b/tests/unit/cli/test_hook_default_on.py
@@ -0,0 +1,200 @@
+"""The post-commit auto-sync hook is on by default and undone with one command.
+
+``init --yes`` and non-interactive runs used to skip the hook offer with no
+message and no opt-out flag, so the paths the product recommends left the
+index stale after the first commit. The offer now installs on those paths
+and prints how to undo it; ``--no-hook`` skips; ``--no-editor-setup`` keeps
+it off because a git hook is a write outside ``.repowise/``; an interactive
+run still asks.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import click
+import pytest
+
+from repowise.cli import hooks
+from repowise.cli.commands.init_cmd._interactive import offer_hook_install
+
+
+class _Console:
+ def __init__(self) -> None:
+ self.lines: list[str] = []
+
+ def print(self, *args, **_kwargs) -> None:
+ self.lines.append(" ".join(str(a) for a in args))
+
+ @property
+ def text(self) -> str:
+ return "\n".join(self.lines)
+
+
+def repo(tmp_path: Path) -> Path:
+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)
+ return tmp_path
+
+
+def editor_setup_on(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("REPOWISE_SKIP_EDITOR_SETUP", raising=False)
+
+
+def test_yes_installs_and_names_the_undo(repo: Path, editor_setup_on) -> None:
+ console = _Console()
+ offer_hook_install(console, [repo], yes=True)
+ assert hooks.status(repo) == "installed"
+ assert "repowise hook uninstall" in console.text
+
+
+def test_non_tty_installs_and_names_the_undo(repo: Path, editor_setup_on, monkeypatch) -> None:
+ monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False)
+ console = _Console()
+ offer_hook_install(console, [repo])
+ assert hooks.status(repo) == "installed"
+ assert "repowise hook uninstall" in console.text
+
+
+def test_no_hook_skips_and_says_how_to_install(repo: Path, editor_setup_on) -> None:
+ console = _Console()
+ offer_hook_install(console, [repo], flag=False, yes=True)
+ assert hooks.status(repo) == "not installed"
+ assert "repowise hook install" in console.text
+
+
+def test_editor_setup_off_keeps_the_hook_off(repo: Path, monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ quiet = _Console()
+ offer_hook_install(quiet, [repo], yes=True)
+ assert hooks.status(repo) == "not installed"
+ assert quiet.lines == []
+
+ told = _Console()
+ offer_hook_install(told, [repo], flag=True, yes=True)
+ assert hooks.status(repo) == "not installed"
+ assert "editor setup is off" in told.text
+
+
+def test_no_editor_setup_flag_keeps_the_hook_off(repo: Path, editor_setup_on) -> None:
+ console = _Console()
+ offer_hook_install(console, [repo], flag=True, yes=True, no_editor_setup=True)
+ assert hooks.status(repo) == "not installed"
+
+
+def test_interactive_run_still_asks(repo: Path, editor_setup_on, monkeypatch) -> None:
+ monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False)
+ monkeypatch.setattr(click, "confirm", lambda *_a, **_k: False)
+ console = _Console()
+ offer_hook_install(console, [repo])
+ assert hooks.status(repo) == "not installed"
+
+ monkeypatch.setattr(click, "confirm", lambda *_a, **_k: True)
+ offer_hook_install(console, [repo])
+ assert hooks.status(repo) == "installed"
+
+
+def test_workspace_applies_the_default_to_every_repo(tmp_path: Path, editor_setup_on) -> None:
+ repos = []
+ for name in ("a", "b"):
+ rp = tmp_path / name
+ rp.mkdir()
+ subprocess.run(["git", "init", "-q"], cwd=rp, check=True)
+ repos.append(rp)
+ console = _Console()
+ offer_hook_install(console, repos, ["a", "b"], yes=True)
+ assert all(hooks.status(rp) == "installed" for rp in repos)
+ assert "repowise hook uninstall --workspace" in console.text
+
+
+def test_a_failed_install_is_reported_and_does_not_raise(
+ repo: Path, editor_setup_on, monkeypatch
+) -> None:
+ def _boom(_p: Path) -> str:
+ raise OSError("read-only hooks dir")
+
+ monkeypatch.setattr(hooks, "install", _boom)
+ console = _Console()
+ offer_hook_install(console, [repo], yes=True)
+ assert "not installed" in console.text
+ assert "repowise hook uninstall" not in console.text
+
+
+def test_uninstall_removes_what_the_default_installed(repo: Path, editor_setup_on) -> None:
+ offer_hook_install(_Console(), [repo], yes=True)
+ assert hooks.uninstall(repo) == "removed"
+ assert hooks.status(repo) == "not installed"
+
+
+def test_a_repo_that_is_not_git_gets_no_hook_and_no_consent_line(tmp_path: Path, editor_setup_on) -> None:
+ plain = tmp_path / "plain"
+ plain.mkdir()
+ console = _Console()
+ offer_hook_install(console, [plain], yes=True)
+ assert "not a git repository" in console.text
+ assert "repowise hook uninstall" not in console.text
+
+
+def test_a_hook_for_another_interpreter_is_refused_not_corrupted(repo: Path, editor_setup_on) -> None:
+ hooks_dir = repo / ".git" / "hooks"
+ hooks_dir.mkdir(parents=True, exist_ok=True)
+ original = "#!/usr/bin/env node\nconsole.log('mine')\n"
+ (hooks_dir / "post-commit").write_text(original)
+ console = _Console()
+ offer_hook_install(console, [repo], yes=True)
+ assert (hooks_dir / "post-commit").read_text() == original
+ assert "not a shell script" in console.text
+ assert "repowise hook uninstall" not in console.text
+ assert hooks.status(repo) == "not installed"
+
+
+def test_a_shell_hook_keeps_its_content_and_gains_the_block(repo: Path, editor_setup_on) -> None:
+ hooks_dir = repo / ".git" / "hooks"
+ hooks_dir.mkdir(parents=True, exist_ok=True)
+ (hooks_dir / "post-commit").write_text("#!/bin/bash\necho mine\n")
+ offer_hook_install(_Console(), [repo], yes=True)
+ content = (hooks_dir / "post-commit").read_text()
+ assert content.startswith("#!/bin/bash\necho mine\n")
+ assert hooks.status(repo) == "installed"
+
+
+def _run_hook(repo: Path) -> None:
+ sh = shutil.which("sh") or shutil.which("bash")
+ if sh is None:
+ pytest.skip("no POSIX shell to run the hook under")
+ git = shutil.which("git")
+ assert git is not None
+ # Only the shell and git are reachable, so the hook can find no repowise
+ # and the test observes the queued marker, never a real update.
+ path = os.pathsep.join({str(Path(sh).parent): None, str(Path(git).parent): None})
+ env = {"PATH": path, "SYSTEMROOT": os.environ.get("SYSTEMROOT", "")}
+ subprocess.run([sh, str(repo / ".git" / "hooks" / "post-commit")], cwd=repo, env=env, check=True, timeout=30)
+
+
+def test_the_hook_is_inert_without_a_store(repo: Path, editor_setup_on) -> None:
+ hooks.install(repo)
+ (repo / ".repowise").mkdir()
+ _run_hook(repo)
+ assert not (repo / ".repowise" / ".update.queued").exists()
+
+
+def test_the_hook_queues_an_update_when_a_store_exists(repo: Path, editor_setup_on) -> None:
+ hooks.install(repo)
+ (repo / "seed.txt").write_text("seed\n")
+ subprocess.run(["git", "add", "seed.txt"], cwd=repo, check=True)
+ subprocess.run(
+ ["git", "-c", "[email protected]", "-c", "user.name=T", "commit", "-qm", "seed"],
+ cwd=repo,
+ check=True,
+ )
+ (repo / ".repowise").mkdir()
+ (repo / ".repowise" / "state.json").write_text("{}")
+ _run_hook(repo)
+ queued = repo / ".repowise" / ".update.queued"
+ assert queued.exists()
+ assert "target_commit" in queued.read_text()
diff --git a/tests/unit/cli/test_hook_ledger_wal_guard.py b/tests/unit/cli/test_hook_ledger_wal_guard.py
new file mode 100644
index 000000000..739e57dc9
--- /dev/null
+++ b/tests/unit/cli/test_hook_ledger_wal_guard.py
@@ -0,0 +1,38 @@
+"""The hook ledger degrades to the file's journal mode, not to being off.
+
+``_open_injections`` already swallowed every ``sqlite3.Error`` and cached
+``None`` for the process, so a WAL switch that lost a lock race silently
+turned the ledger off for every hook fire that followed. The switch failing
+must leave the connection usable.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+
+from repowise.cli import hook_ledger
+
+
+def test_open_injections_survives_a_contended_wal_switch(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(hook_ledger, "_CONN", {})
+ first = hook_ledger._open_injections(tmp_path)
+ assert first is not None
+ first.close()
+ monkeypatch.setattr(hook_ledger, "_CONN", {})
+
+ db_path = tmp_path / ".repowise" / "sessions" / "sessions.db"
+ reset = sqlite3.connect(db_path)
+ reset.execute("PRAGMA journal_mode=DELETE")
+ reset.close()
+ holder = sqlite3.connect(db_path, isolation_level=None)
+ holder.execute("BEGIN")
+ holder.execute("SELECT count(*) FROM sqlite_master")
+ try:
+ conn = hook_ledger._open_injections(tmp_path)
+ finally:
+ holder.close()
+ assert conn is not None
+ assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "delete"
+ assert conn.execute("SELECT count(*) FROM injections").fetchone()[0] == 0
+ conn.close()
diff --git a/tests/unit/cli/test_init_noninteractive.py b/tests/unit/cli/test_init_noninteractive.py
index 6186069eb..a89d63768 100644
--- a/tests/unit/cli/test_init_noninteractive.py
+++ b/tests/unit/cli/test_init_noninteractive.py
@@ -115,6 +115,7 @@ class TestCostGateBlocks:
class TestHookOfferDegrades:
def test_eof_on_hook_offer_does_not_raise(self, monkeypatch, tmp_path):
"""A finished run must not fail on an optional trailing question."""
+ monkeypatch.delenv("REPOWISE_SKIP_EDITOR_SETUP", raising=False)
monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False)
monkeypatch.setattr(
"repowise.cli.commands.init_cmd._interactive.click.confirm",
diff --git a/tests/unit/cli/test_mcp_store_unavailable.py b/tests/unit/cli/test_mcp_store_unavailable.py
new file mode 100644
index 000000000..4b83532ba
--- /dev/null
+++ b/tests/unit/cli/test_mcp_store_unavailable.py
@@ -0,0 +1,24 @@
+"""``repowise mcp`` turns an unopenable store into one line and exit 1."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from click.testing import CliRunner
+
+from repowise.cli.main import cli
+from repowise.server.mcp_server._server import StoreUnavailableError
+
+
+def test_store_unavailable_exits_cleanly_with_the_message(monkeypatch, tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+
+ def _boom(**_kw):
+ raise StoreUnavailableError("repowise MCP: cannot open the index store at X: denied")
+
+ monkeypatch.setattr("repowise.server.mcp_server.run_mcp", _boom)
+ result = CliRunner().invoke(cli, ["mcp", str(tmp_path)])
+
+ assert result.exit_code == 1
+ assert "cannot open the index store at X" in result.output
+ assert "Traceback" not in result.output
diff --git a/tests/unit/cli/test_serve_update_advisory.py b/tests/unit/cli/test_serve_update_advisory.py
new file mode 100644
index 000000000..ea2a5a5d1
--- /dev/null
+++ b/tests/unit/cli/test_serve_update_advisory.py
@@ -0,0 +1,50 @@
+"""``serve`` re-checks release currency while it runs, announcing each once."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.cli.commands import serve_cmd
+from repowise.cli.update_check import UpdateCheck
+
+
+def _check(latest: str | None, current: str = "0.48.0") -> UpdateCheck:
+ available = None if latest is None else latest != current
+ return UpdateCheck(
+ current_version=current,
+ latest_version=latest,
+ resolved_executable=None,
+ running_executable="repowise",
+ python="python",
+ update_available=available,
+ suggested_command="pip install -U repowise",
+ install_hint="pip",
+ )
+
+
+def test_tick_announces_a_newer_release_once(monkeypatch: pytest.MonkeyPatch, capsys) -> None:
+ monkeypatch.setattr(
+ "repowise.cli.update_check.get_cli_update_check_cached", lambda: _check("9.9.9")
+ )
+ announced: set[str] = set()
+ assert serve_cmd._update_advisory_tick(announced) is True
+ assert "9.9.9" in capsys.readouterr().out
+ assert serve_cmd._update_advisory_tick(announced) is False
+ assert capsys.readouterr().out == ""
+
+
+def test_tick_is_quiet_when_current_or_unknown(monkeypatch: pytest.MonkeyPatch, capsys) -> None:
+ for latest in ("0.48.0", None):
+ monkeypatch.setattr(
+ "repowise.cli.update_check.get_cli_update_check_cached", lambda latest=latest: _check(latest)
+ )
+ assert serve_cmd._update_advisory_tick(set()) is False
+ assert capsys.readouterr().out == ""
+
+
+def test_tick_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:
+ def _boom():
+ raise RuntimeError("network")
+
+ monkeypatch.setattr("repowise.cli.update_check.get_cli_update_check_cached", _boom)
+ assert serve_cmd._update_advisory_tick(set()) is False
diff --git a/tests/unit/persistence/test_sidecar_store_pragmas.py b/tests/unit/persistence/test_sidecar_store_pragmas.py
new file mode 100644
index 000000000..e9c26a189
--- /dev/null
+++ b/tests/unit/persistence/test_sidecar_store_pragmas.py
@@ -0,0 +1,88 @@
+"""The synchronous sidecar stores must open under a contended WAL switch.
+
+Each store used to issue ``PRAGMA journal_mode=WAL`` bare, before any busy
+timeout. The switch needs a short exclusive lock, so a reader holding an open
+transaction on the same file made every constructor raise ``database is
+locked``. That is the shape a post-commit update overlapping an editor hook
+produces, and it is why the hook could not default on until these were
+guarded.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+
+import pytest
+
+from repowise.core.distill import store as distill_store
+from repowise.core.precedent import store as precedent_store
+from repowise.core.sessions import staging
+from repowise.core.sqlite_pragmas import apply_sqlite_pragmas
+
+
+def _hold_read_lock(db_path: Path) -> sqlite3.Connection:
+ """Open a transaction that holds a shared lock until the connection closes.
+
+ In rollback-journal mode a shared lock is enough to make the WAL switch
+ fail, so the store is first forced back out of WAL.
+ """
+ reset = sqlite3.connect(db_path)
+ reset.execute("PRAGMA journal_mode=DELETE")
+ reset.close()
+ holder = sqlite3.connect(db_path, isolation_level=None)
+ holder.execute("BEGIN")
+ holder.execute("SELECT count(*) FROM sqlite_master")
+ return holder
+
+
+def test_helper_swallows_the_failed_switch_and_keeps_the_connection(tmp_path: Path) -> None:
+ db_path = tmp_path / "t.db"
+ seed = sqlite3.connect(db_path)
+ seed.execute("CREATE TABLE t (x)")
+ seed.commit()
+ seed.close()
+ holder = _hold_read_lock(db_path)
+ try:
+ conn = sqlite3.connect(db_path)
+ assert apply_sqlite_pragmas(conn, 50) is False
+ assert conn.execute("PRAGMA busy_timeout").fetchone()[0] == 50
+ assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "delete"
+ assert conn.execute("SELECT count(*) FROM t").fetchone()[0] == 0
+ conn.close()
+ finally:
+ holder.close()
+
+
+def test_helper_switches_to_wal_when_uncontended(tmp_path: Path) -> None:
+ conn = sqlite3.connect(tmp_path / "t.db")
+ assert apply_sqlite_pragmas(conn, 50) is True
+ assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "wal"
+ conn.close()
+
+
+ ("module", "open_store"),
+ [
+ (distill_store, lambda p: distill_store.OmissionStore(p)),
+ (precedent_store, lambda p: precedent_store.EpisodeStore(p)),
+ (staging, lambda p: staging.SessionStagingStore(p)),
+ ],
+ ids=["distill", "precedent", "staging"],
+)
+def test_store_opens_while_another_connection_holds_the_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, module, open_store
+) -> None:
+ monkeypatch.setattr(module, "_BUSY_TIMEOUT_MS", 50)
+ db_path = tmp_path / "store.db"
+ first = open_store(db_path)
+ first._conn.close()
+
+ holder = _hold_read_lock(db_path)
+ try:
+ store = open_store(db_path)
+ finally:
+ holder.close()
+ assert store._conn.execute("PRAGMA busy_timeout").fetchone()[0] == 50
+ assert store._conn.execute("SELECT count(*) FROM sqlite_master").fetchone()[0] > 0
+ store._conn.close()
diff --git a/tests/unit/server/mcp/conftest.py b/tests/unit/server/mcp/conftest.py
index 7a9260e13..571a0e2fd 100644
--- a/tests/unit/server/mcp/conftest.py
+++ b/tests/unit/server/mcp/conftest.py
@@ -591,6 +591,8 @@ async def setup_mcp(factory, fts, vector_store, populated_db):
mcp_mod._registry = None
mcp_mod._workspace_root = None
mcp_mod._embedder_status = None
+ mcp_mod._release_check = None
+ mcp_mod._release_announced = None
@pytest.fixture
diff --git a/tests/unit/server/mcp/test_meta_release.py b/tests/unit/server/mcp/test_meta_release.py
new file mode 100644
index 000000000..053c23915
--- /dev/null
+++ b/tests/unit/server/mcp/test_meta_release.py
@@ -0,0 +1,100 @@
+"""A newer release is named once per process in ``_meta``, never per call.
+
+The stdio server was the one long-lived process that never checked its own
+currency. The lifespan now polls the TTL-cached PyPI check off the loop
+thread, and ``build_meta`` names a newer version in the first response after
+the poller sees it, then stays quiet for that version.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from repowise.core.upgrade.release import ReleaseCheck
+from repowise.server.mcp_server import _meta, _server, _state
+
+
[email protected](autouse=True)
+def _clean_release_state(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(_state, "_release_check", None)
+ monkeypatch.setattr(_state, "_release_announced", None)
+
+
+def _check(latest: str | None, current: str = "0.48.0") -> ReleaseCheck:
+ available = None if latest is None else latest != current
+ return ReleaseCheck(current_version=current, latest_version=latest, update_available=available)
+
+
+def test_newer_release_is_named_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(_state, "_release_check", _check("9.9.9"))
+ first = _meta.build_meta()
+ assert "9.9.9" in first["newer_release"]
+ assert "0.48.0" in first["newer_release"]
+ assert "newer_release" not in _meta.build_meta()
+
+
+def test_current_or_unknown_release_says_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(_state, "_release_check", _check("0.48.0"))
+ assert "newer_release" not in _meta.build_meta()
+ monkeypatch.setattr(_state, "_release_check", _check(None))
+ assert "newer_release" not in _meta.build_meta()
+ assert "newer_release" not in _meta.build_meta()
+
+
+def test_a_later_newer_release_is_named_again_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(_state, "_release_check", _check("9.9.9"))
+ assert "newer_release" in _meta.build_meta()
+ monkeypatch.setattr(_state, "_release_check", _check("10.0.0"))
+ assert "10.0.0" in _meta.build_meta()["newer_release"]
+ assert "newer_release" not in _meta.build_meta()
+
+
+async def test_poller_records_the_check_off_the_loop_thread(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[str] = []
+
+ def _fake_check(current_version: str, **_kw) -> ReleaseCheck:
+ calls.append(current_version)
+ return _check("9.9.9", current=current_version)
+
+ monkeypatch.setattr(
+ "repowise.core.upgrade.release.check_latest_version_cached", _fake_check
+ )
+
+ async def _stop_after_first(_seconds: float) -> None:
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(_server.asyncio, "sleep", _stop_after_first)
+ with pytest.raises(asyncio.CancelledError):
+ await _server._poll_release_check()
+ from repowise.server import __version__
+
+ assert calls == [__version__]
+ assert _state._release_check.latest_version == "9.9.9"
+
+
+async def test_poller_survives_a_failing_check(monkeypatch: pytest.MonkeyPatch) -> None:
+ def _boom(_current: str, **_kw) -> ReleaseCheck:
+ raise RuntimeError("pypi down")
+
+ monkeypatch.setattr("repowise.core.upgrade.release.check_latest_version_cached", _boom)
+
+ async def _stop_after_first(_seconds: float) -> None:
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(_server.asyncio, "sleep", _stop_after_first)
+ with pytest.raises(asyncio.CancelledError):
+ await _server._poll_release_check()
+ assert _state._release_check is None
+
+
+def test_release_state_is_reachable_through_the_package_proxy() -> None:
+ import repowise.server.mcp_server as mcp_mod
+
+ mcp_mod._release_announced = "1.2.3"
+ assert _state._release_announced == "1.2.3"
+ mcp_mod._release_announced = None
+ assert mcp_mod._release_check is None
diff --git a/tests/unit/server/mcp/test_startup_guards.py b/tests/unit/server/mcp/test_startup_guards.py
new file mode 100644
index 000000000..a799ed0f7
--- /dev/null
+++ b/tests/unit/server/mcp/test_startup_guards.py
@@ -0,0 +1,136 @@
+"""Startup failures exit once with a named cause instead of respawning.
+
+An MCP host restarts a stdio server that dies at startup. Two failures used
+to escape as bare tracebacks and loop that way: an index directory the
+process cannot create or open, and a tool module whose optional dependency
+is missing. The first now raises a message naming the path and the fix; the
+second is skipped so the rest of the surface still serves.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import logging
+from pathlib import Path
+from typing import ClassVar
+
+import pytest
+
+import repowise.server.mcp_server as mcp_pkg
+from repowise.server.mcp_server import _server, _state
+from repowise.server.mcp_server._server import StoreUnavailableError
+
+
+async def test_lifespan_names_the_path_when_the_store_cannot_be_opened(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ (tmp_path / ".repowise").write_text("not a directory\n")
+ for name in ("REPOWISE_DB_URL", "REPOWISE_DATABASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setattr(_state, "_repo_path", str(tmp_path))
+
+ async def _no_warm() -> None:
+ return None
+
+ monkeypatch.setattr(_server, "_warm_lancedb", _no_warm)
+ monkeypatch.setattr(_server, "_detect_workspace", lambda _p: (None, None, None))
+
+ with pytest.raises(StoreUnavailableError) as raised:
+ async with _server._lifespan(_server.mcp):
+ pass
+ message = str(raised.value)
+ assert str(tmp_path / ".repowise") in message
+ assert "repowise init" in message
+ # The failure path never reaches the teardown, so it has to leave the
+ # warmup event cleared itself. A leaked event stays bound to this test's
+ # loop and makes every later tool call raise inside the failure shield.
+ assert _state._lancedb_ready is None
+
+
+def test_missing_tool_dependency_skips_that_tool_and_keeps_the_rest(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ real_import = importlib.import_module
+ victim = f"{mcp_pkg.__name__}.tool_flows"
+
+ def _import(name: str, package: str | None = None):
+ if name == victim:
+ raise ModuleNotFoundError("No module named 'lancedb'", name="lancedb")
+ return real_import(name, package)
+
+ monkeypatch.setattr(mcp_pkg, "_surface_applied", False)
+ monkeypatch.setattr(importlib, "import_module", _import)
+
+ with caplog.at_level(logging.WARNING, logger="repowise.mcp"):
+ server = mcp_pkg.ensure_full_surface()
+
+ assert server is _server.mcp
+ record = next(r for r in caplog.records if "skipping tool module" in r.getMessage())
+ assert "tool_flows" in record.getMessage()
+ assert "lancedb" in record.getMessage()
+
+
+async def test_configured_database_failure_names_the_url_not_the_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite:///{(tmp_path / 'elsewhere.db').as_posix()}")
+ monkeypatch.setattr(_state, "_repo_path", str(tmp_path))
+
+ async def _no_warm() -> None:
+ return None
+
+ async def _refuse(_engine) -> None:
+ raise OSError("connection refused")
+
+ monkeypatch.setattr(_server, "_warm_lancedb", _no_warm)
+ monkeypatch.setattr(_server, "_detect_workspace", lambda _p: (None, None, None))
+ monkeypatch.setattr(_server, "init_db", _refuse)
+
+ with pytest.raises(StoreUnavailableError) as raised:
+ async with _server._lifespan(_server.mcp):
+ pass
+ message = str(raised.value)
+ assert "REPOWISE_DB_URL" in message
+ assert "repowise init" not in message
+
+
+async def test_workspace_startup_failure_cancels_the_background_tasks(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ started: list[asyncio.Task] = []
+ real_create_task = asyncio.create_task
+
+ def _spy(coro, **kw):
+ task = real_create_task(coro, **kw)
+ started.append(task)
+ return task
+
+ async def _no_warm() -> None:
+ await asyncio.sleep(3600)
+
+ class _Registry:
+ def __init__(self, **_kw) -> None:
+ pass
+
+ async def get_default(self):
+ raise RuntimeError("workspace store missing")
+
+ class _Config:
+ repos: ClassVar[list] = []
+
+ def get_repo(self, _alias):
+ return None
+
+ monkeypatch.setattr(_server, "_warm_lancedb", _no_warm)
+ monkeypatch.setattr(_server, "_detect_workspace", lambda _p: (tmp_path, _Config(), None))
+ monkeypatch.setattr("repowise.core.workspace.registry.RepoRegistry", _Registry)
+ monkeypatch.setattr(_server.asyncio, "create_task", _spy)
+
+ with pytest.raises(RuntimeError):
+ async with _server._lifespan(_server.mcp):
+ pass
+ assert started and all(t.done() for t in started)
diff --git a/website/cli-reference.md b/website/cli-reference.md
index 2c599e82a..f522f1776 100644
--- a/website/cli-reference.md
+++ b/website/cli-reference.md
@@ -65,6 +65,7 @@ repowise init [PATH] [OPTIONS]
| `--agents` / `--no-agents` | flag | config | Generate or skip managed `AGENTS.md` for Codex |
| `--codex` / `--no-codex` | flag | prompt/skip | Generate or skip project-local Codex MCP config and hooks |
| `--distill-hook` / `--no-distill-hook` | flag | prompt/skip | Install or skip the Claude Code command-rewrite hook that routes noisy commands through `repowise distill` |
+| `--hook` / `--no-hook` | flag | on | Install or skip the post-commit hook that runs `repowise update` after each commit. Interactive runs ask; `--yes` and non-interactive runs install it and print how to undo it |
| `--editor-setup` / `--no-editor-setup` | flag | true | Register the MCP server and hooks in your global Claude Code / Claude Desktop config. `--no-editor-setup` indexes the repo and leaves everything outside it untouched |
| `--yes` / `-y` | flag | false | Skip the cost confirmation prompt |