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(server): add a setup API for the Setup page and the welcome (#4681)

Raghav Chamadiya4182dfc44d0c
diff --git a/packages/api-client/package.json b/packages/api-client/package.json
index ac45fe042..0e3d30747 100644
--- a/packages/api-client/package.json
+++ b/packages/api-client/package.json
@@ -51,6 +51,7 @@
"./risk": "./src/risk.ts",
"./search": "./src/search.ts",
"./security": "./src/security.ts",
+ "./setup": "./src/setup.ts",
"./stats": "./src/stats.ts",
"./symbols": "./src/symbols.ts",
"./views": "./src/views.ts",
diff --git a/packages/api-client/src/setup.ts b/packages/api-client/src/setup.ts
new file mode 100644
index 000000000..321846e5e
--- /dev/null
+++ b/packages/api-client/src/setup.ts
@@ -0,0 +1,75 @@
+/**
+ * The Setup page and the welcome: what is set up for a repo, and the switches
+ * that change it. Writes run the matching CLI command on the server and are
+ * accepted only from the local web UI of a server with no API key.
+ */
+
+import type {
+ OnboardingPatch,
+ OnboardingState,
+ SetupResponse,
+ SetupWriteResponse,
+} from "@repowise-dev/types/generated/http";
+import { apiDelete, apiGet, apiPatch, apiPost, apiPut } from "./client";
+
+export type { OnboardingPatch, OnboardingState, SetupResponse, SetupWriteResponse };
+
+/** Hooks the Setup page can switch: auto-sync after commits, and distill rewrites. */
+export type SetupHookName = "post-commit" | "rewrite";
+
+/** Index, agents, hooks, coverage, model and doctor checks for one repo. */
+export async function getRepoSetup(repoId: string): Promise<SetupResponse> {
+ return apiGet<SetupResponse>(`/api/repos/${encodeURIComponent(repoId)}/setup`);
+}
+
+/** `repowise agents add --target=<agentId>`; the answer names the files written. */
+export async function connectSetupAgent(
+ repoId: string,
+ agentId: string,
+): Promise<SetupWriteResponse> {
+ return apiPost<SetupWriteResponse>(
+ `/api/repos/${encodeURIComponent(repoId)}/setup/agents/${encodeURIComponent(agentId)}`,
+ );
+}
+
+/** `repowise agents remove --target=<agentId>`. */
+export async function disconnectSetupAgent(
+ repoId: string,
+ agentId: string,
+): Promise<SetupWriteResponse> {
+ return apiDelete<SetupWriteResponse>(
+ `/api/repos/${encodeURIComponent(repoId)}/setup/agents/${encodeURIComponent(agentId)}`,
+ );
+}
+
+/** `repowise hook install|uninstall`, or `repowise hook rewrite install|uninstall`. */
+export async function setSetupHook(
+ repoId: string,
+ name: SetupHookName,
+ enabled: boolean,
+): Promise<SetupWriteResponse> {
+ return apiPut<SetupWriteResponse>(
+ `/api/repos/${encodeURIComponent(repoId)}/setup/hooks/${name}`,
+ { enabled },
+ );
+}
+
+/** `repowise coverage add <path>` for a report file inside the repo. */
+export async function addSetupCoverage(
+ repoId: string,
+ path: string,
+): Promise<SetupWriteResponse> {
+ return apiPost<SetupWriteResponse>(`/api/repos/${encodeURIComponent(repoId)}/setup/coverage`, {
+ path,
+ });
+}
+
+/** Per-machine onboarding state, without running the repo checks. */
+export async function getOnboardingState(): Promise<OnboardingState> {
+ return apiGet<OnboardingState>("/api/setup/onboarding");
+}
+
+/** Mark the welcome seen for a repo, or hide the setup pill or the hosted card. */
+export async function updateOnboardingState(patch: OnboardingPatch): Promise<OnboardingState> {
+ return apiPatch<OnboardingState>("/api/setup/onboarding", patch);
+}
diff --git a/packages/cli/src/repowise/cli/agent_targets/registry.py b/packages/cli/src/repowise/cli/agent_targets/registry.py
index c67e083bd..4a4a67c94 100644
--- a/packages/cli/src/repowise/cli/agent_targets/registry.py
+++ b/packages/cli/src/repowise/cli/agent_targets/registry.py
@@ -122,11 +122,25 @@ def describe_agents(repo_path: Path | None = None) -> list[dict]:
"present": present,
"method": method.id if method is not None else None,
"registrations": [r.as_dict() for r in registrations],
+ "config_files": _config_files(target, repo_path),
}
)
return rows
+def _config_files(target: AgentTarget, repo_path: Path | None) -> dict[str, list[str]]:
+ """The files ``agents add`` writes for *target*, per scope it supports.
+
+ Not best-effort like the probes above: ``supports_scope`` already skips a
+ scope the target lacks, so an error here is a path bug and should surface.
+ """
+ return {
+ scope.value: list(target.describe_paths(scope, repo_path=repo_path))
+ for scope in (Scope.PROJECT, Scope.USER)
+ if target.supports_scope(scope)
+ }
+
+
def default_selection(rows: list[dict]) -> set[str]:
"""Which agents to pre-tick, given :func:`describe_agents` rows.
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/command.py b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
index f5f60db95..0bc247189 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
@@ -72,6 +72,10 @@ def _run_api(
frontend_proc: subprocess.Popen | None,
) -> None:
"""Run uvicorn with the discovery lockfile held; clean up on exit."""
+ if ui_port is not None:
+ # The setup routes accept browser writes only from the UI's own origin,
+ # and the UI proxies /api here, so the API has to be told its port.
+ os.environ["REPOWISE_UI_PORT"] = str(ui_port)
lock_path = _lock._serve_lock_path()
if lock_path:
_lock._write_serve_lock(lock_path, host=host, port=port, ui_port=ui_port)
diff --git a/packages/core/src/repowise/core/platform/onboarding.py b/packages/core/src/repowise/core/platform/onboarding.py
new file mode 100644
index 000000000..b2b5b7c00
--- /dev/null
+++ b/packages/core/src/repowise/core/platform/onboarding.py
@@ -0,0 +1,99 @@
+"""Per-machine onboarding state for the local web UI, in ``~/.repowise/platform.json``.
+
+Held under one ``onboarding`` key so it never collides with what the CLI keeps
+in the same file (install id, telemetry consent, hint schedule). Reads are
+fresh, not the telemetry module's cached copy, so a write is visible on the
+next read. The write merges into the file the way the CLI's store does, keeping
+every key it does not own.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import tempfile
+from datetime import UTC, datetime
+from typing import Any
+
+from repowise.core.platform.telemetry import _platform_json_path
+
+ONBOARDING_KEY = "onboarding"
+
+#: Bounds the welcome map, so a long-lived install cannot grow the file forever.
+_WELCOME_SEEN_LIMIT = 200
+
+
+def _read_platform_json(*, strict: bool = False) -> dict[str, Any]:
+ """The parsed file; ``{}`` when absent. *strict* raises ``OSError`` on a file
+ that exists but does not parse, so a write never replaces keys it could not read."""
+ try:
+ data = json.loads(_platform_json_path().read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return {}
+ except (OSError, ValueError) as exc:
+ if strict:
+ raise OSError(f"platform.json could not be read: {exc}") from exc
+ return {}
+ if not isinstance(data, dict):
+ if strict:
+ raise OSError("platform.json is not a JSON object")
+ return {}
+ return data
+
+
+def load_onboarding() -> dict[str, Any]:
+ """``welcome_seen`` (repo id -> ISO time), ``setup_pill_hidden``, ``hosted_card_hidden``."""
+ raw = _read_platform_json().get(ONBOARDING_KEY)
+ raw = raw if isinstance(raw, dict) else {}
+ seen = raw.get("welcome_seen")
+ return {
+ "welcome_seen": {
+ str(k): str(v) for k, v in (seen.items() if isinstance(seen, dict) else [])
+ },
+ "setup_pill_hidden": raw.get("setup_pill_hidden") is True,
+ "hosted_card_hidden": raw.get("hosted_card_hidden") is True,
+ }
+
+
+def update_onboarding(
+ *,
+ welcome_seen_repo: str | None = None,
+ setup_pill_hidden: bool | None = None,
+ hosted_card_hidden: bool | None = None,
+) -> dict[str, Any]:
+ """Apply the given changes, persist, and return the new state.
+
+ ``welcome_seen_repo`` stamps that repo with the current time. Raises
+ ``OSError`` when the file cannot be written, so the caller can say so.
+ """
+ state = load_onboarding()
+ if welcome_seen_repo is not None:
+ seen = state["welcome_seen"]
+ seen[welcome_seen_repo] = datetime.now(UTC).isoformat()
+ # Oldest stamps go first once the map is full.
+ newest = sorted(seen.items(), key=lambda kv: kv[1])[-_WELCOME_SEEN_LIMIT:]
+ state["welcome_seen"] = dict(newest)
+ if setup_pill_hidden is not None:
+ state["setup_pill_hidden"] = setup_pill_hidden
+ if hosted_card_hidden is not None:
+ state["hosted_card_hidden"] = hosted_card_hidden
+ data = _read_platform_json(strict=True)
+ data[ONBOARDING_KEY] = state
+ _write_atomic(data)
+ return state
+
+
+def _write_atomic(data: dict[str, Any]) -> None:
+ """Replace platform.json in one step, so a reader never sees half a file."""
+ path = _platform_json_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".platform-", suffix=".json")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2)
+ os.replace(tmp, path)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp)
+ raise
diff --git a/packages/core/src/repowise/core/savings/repository.py b/packages/core/src/repowise/core/savings/repository.py
index 041ca2d48..2fe4d9f9e 100644
--- a/packages/core/src/repowise/core/savings/repository.py
+++ b/packages/core/src/repowise/core/savings/repository.py
@@ -94,6 +94,20 @@ class SavingsRepository:
[*params, limit],
).fetchall()
+ def index_call_window(self, repository_id: str) -> list[tuple[Any, ...]]:
+ """``(agent, first, last)`` per agent for calls that read the index, latest first.
+
+ MCP tool calls and VS Code language-model tool calls; distill and hook
+ rows are output an agent ran, not questions it asked. Bounded like
+ every other grouping here.
+ """
+ return self._conn.execute(
+ "SELECT agent, MIN(occurred_at), MAX(occurred_at) FROM savings_events "
+ "WHERE repository_id = ? AND surface IN ('mcp', 'vscode_lm') "
+ "GROUP BY agent ORDER BY 3 DESC LIMIT 100",
+ [repository_id],
+ ).fetchall()
+
def recorded_omission_refs(self, refs: Sequence[str]) -> set[str]:
"""Which of *refs* an event already claims, via ``idx_..._omissions_ref``.
diff --git a/packages/core/src/repowise/core/savings/service.py b/packages/core/src/repowise/core/savings/service.py
index 3bc3a40e2..64a54a7e2 100644
--- a/packages/core/src/repowise/core/savings/service.py
+++ b/packages/core/src/repowise/core/savings/service.py
@@ -1,4 +1,8 @@
-"""The one savings report every first-party surface reads.
+"""The read side of the savings ledger: the one report, and per-agent call times.
+
+``load_agent_calls`` answers a narrower question from the same sidecar (when
+did each agent last read the index), so it shares the read-only handle below
+and adds no second aggregation of savings.
Before this, three consumers each aggregated and priced the ledger themselves:
the costs endpoint, the repository overview headline and ``repowise saved``.
@@ -43,20 +47,10 @@ def load_report(
a CLI command, neither of which should fail because a sidecar is locked,
truncated or written by a newer build.
"""
- if repo_root is None:
- return None
- database = sidecar_path(repo_root)
- if not database.is_file():
+ connection = _open_read_only(repo_root)
+ if connection is None:
return None
moment = as_of or datetime.now(UTC)
- try:
- # A read-only URI handle never contends with the hook and MCP writers,
- # and never runs the schema upgrade a read path has no business doing.
- connection = sqlite3.connect(
- f"file:{database.as_posix()}?mode=ro", uri=True, timeout=1
- )
- except sqlite3.Error:
- return None
try:
return SavingsRepository(connection).report(
# The recorder files events under the path it wrote to, so the
@@ -77,3 +71,37 @@ def load_report(
return None
finally:
connection.close()
+
+
+def load_agent_calls(repo_root: str | Path | None) -> dict[str, tuple[str, str]] | None:
+ """``{agent slug: (first, last)}`` times of the calls that read *repo_root*'s index.
+
+ ``None`` when there is no ledger to read, same contract as
+ :func:`load_report`. ``unknown`` is the slug of calls whose client did not
+ announce a name the identity registry knows.
+ """
+ connection = _open_read_only(repo_root)
+ if connection is None:
+ return None
+ try:
+ rows = SavingsRepository(connection).index_call_window(str(Path(repo_root)))
+ except sqlite3.Error:
+ return None
+ finally:
+ connection.close()
+ return {str(agent): (str(first), str(last)) for agent, first, last in rows}
+
+
+def _open_read_only(repo_root: str | Path | None) -> sqlite3.Connection | None:
+ """A read-only handle on the sidecar, or ``None`` when there is none."""
+ if repo_root is None:
+ return None
+ database = sidecar_path(repo_root)
+ if not database.is_file():
+ return None
+ try:
+ # A read-only URI handle never contends with the hook and MCP writers,
+ # and never runs the schema upgrade a read path has no business doing.
+ return sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True, timeout=1)
+ except sqlite3.Error:
+ return None
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index cc5cd4e90..b0a735cf7 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -73,6 +73,7 @@ from repowise.server.routers import (
repos,
search,
security,
+ setup,
stats,
symbols,
webhooks,
@@ -360,6 +361,7 @@ _ROUTERS = (
feedback,
actions,
platform,
+ setup,
)
diff --git a/packages/server/src/repowise/server/routers/setup.py b/packages/server/src/repowise/server/routers/setup.py
new file mode 100644
index 000000000..192e0149a
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/setup.py
@@ -0,0 +1,459 @@
+"""``/api/repos/{id}/setup`` and ``/api/setup``: what is set up for a repo, and the switches.
+
+Reads follow the usual auth. Writes change files on this machine (agent
+configs, git hooks, the coverage store, ``~/.repowise/platform.json``), so they
+are accepted only when the server has no API key or tokens configured, the
+caller is on loopback, and the browser's ``Origin`` is this server's own UI.
+Every write runs the CLI command a person would type, so the two never differ.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import re
+from pathlib import Path
+from typing import Any, Literal
+from urllib.parse import urlsplit
+
+from fastapi import APIRouter, Depends, HTTPException, Request
+from pydantic import BaseModel, Field
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import Repository
+from repowise.core.platform import account, onboarding
+from repowise.server.auth import get_authenticator
+from repowise.server.deps import auth_is_open, client_is_local, get_db_session, verify_api_key
+from repowise.server.routers._local_git import resolve_local_repo
+from repowise.server.services import setup_cli, setup_status
+
+router = APIRouter(tags=["setup"], dependencies=[Depends(verify_api_key)])
+
+_LOOPBACK_NAMES = frozenset({"localhost", "127.0.0.1", "::1"})
+
+#: An agent id as the registry spells them; ``--target`` keywords are refused
+#: so one click can never mean "every agent".
+_TARGET_RE = re.compile(r"[a-z][a-z0-9-]{0,31}\Z")
+_TARGET_KEYWORDS = frozenset({"all", "auto", "none"})
+_REPO_ID_RE = r"^[A-Za-z0-9:_.-]{1,64}$"
+
+
+# -- models ------------------------------------------------------------------
+
+
+class SetupIndex(BaseModel):
+ state: Literal["up_to_date", "behind", "incomplete"]
+ indexed_commit: str | None = None
+ live_head: str | None = None
+ indexed_at: str | None = None
+ file_count: int = 0
+ #: Files whose parse reported errors, so some symbols may be missing.
+ parse_error_count: int = 0
+ #: The first of them, by path.
+ parse_error_files: list[str] = Field(default_factory=list)
+
+
+class SetupRegistration(BaseModel):
+ method: str
+ scope: str
+ config_path: str
+
+
+class SetupAgent(BaseModel):
+ id: str
+ display_name: str
+ tier: str | None = None
+ docs_url: str | None = None
+ #: The agent is on this machine.
+ installed: bool
+ #: Some config wires it to repowise.
+ connected: bool
+ registrations: list[SetupRegistration] = Field(default_factory=list)
+ #: The files ``repowise agents add`` writes for it, per scope.
+ config_files: dict[str, list[str]] = Field(default_factory=dict)
+ #: This agent's calls to this repo's index, from the local savings ledger.
+ first_call_at: str | None = None
+ last_call_at: str | None = None
+
+
+class SetupCalls(BaseModel):
+ """Every call to this repo's index, whichever agent made it."""
+
+ first_call_at: str | None = None
+ last_call_at: str | None = None
+ #: Some calls came from a client that named no known agent, so they count
+ #: here and on no agent row.
+ unattributed: bool = False
+
+
+class SetupSync(BaseModel):
+ #: ``None`` when doctor could not say.
+ installed: bool | None = None
+ detail: str = ""
+
+
+class SetupRewriteHook(BaseModel):
+ #: ``not_applicable`` when Claude Code is not on this machine.
+ state: Literal["installed", "not_installed", "not_applicable", "unknown"]
+ detail: str = ""
+
+
+class SetupCoverageReport(BaseModel):
+ #: Relative to the repo root.
+ path: str
+ modified_at: str
+ age_days: int
+
+
+class SetupCoverage(BaseModel):
+ #: When coverage was last stored for this repo; ``None`` when never.
+ ingested_at: str | None = None
+ #: ``coverage.paths`` from ``.repowise/config.yaml``.
+ configured_paths: list[str] = Field(default_factory=list)
+ #: Reports found on disk by the same discovery ``coverage add`` uses.
+ discovered: list[SetupCoverageReport] = Field(default_factory=list)
+
+
+class SetupModel(BaseModel):
+ #: ``deterministic`` = built from the index, ``llm`` = written by a model.
+ docs_mode: Literal["none", "deterministic", "llm"]
+ active_provider: str | None = None
+ active_model: str | None = None
+ #: Providers ``/api/providers`` reports as usable (a key, or none needed).
+ configured_providers: list[str] = Field(default_factory=list)
+
+
+class SetupCheck(BaseModel):
+ id: str
+ name: str
+ level: Literal["ok", "warn", "fail"]
+ detail: str = ""
+ fix: str | None = None
+
+
+class OnboardingState(BaseModel):
+ """Per-machine onboarding state, plus the switches that hide hosted surfaces."""
+
+ #: Repo id -> when the welcome was seen on this machine.
+ welcome_seen: dict[str, str] = Field(default_factory=dict)
+ setup_pill_hidden: bool = False
+ hosted_card_hidden: bool = False
+ #: Off with ``repowise config hints off``, ``REPOWISE_NO_HINTS`` or ``DO_NOT_TRACK``.
+ hints_enabled: bool
+ signed_in: bool
+
+
+class SetupResponse(BaseModel):
+ repo_id: str
+ generated_at: str
+ index: SetupIndex
+ #: ``False`` when ``repowise agents`` could not run; ``agents`` is then empty.
+ agents_available: bool
+ agents: list[SetupAgent] = Field(default_factory=list)
+ #: ``False`` when the savings ledger could not be read; ``calls`` and the
+ #: agents' call times are then empty, which is not the same as "no calls".
+ calls_available: bool
+ calls: SetupCalls
+ sync: SetupSync
+ rewrite_hook: SetupRewriteHook
+ #: ``False`` when stored coverage or the report search could not be read.
+ coverage_available: bool
+ coverage: SetupCoverage
+ #: ``False`` when the provider settings could not be read; ``docs_mode`` still holds.
+ model_available: bool
+ model: SetupModel
+ #: ``False`` when ``repowise doctor`` could not run; ``checks`` is then empty.
+ checks_available: bool
+ checks: list[SetupCheck] = Field(default_factory=list)
+ onboarding: OnboardingState
+ #: Whether this caller may use the write routes.
+ writes_allowed: bool
+
+
+class SetupFileChange(BaseModel):
+ path: str
+ #: ``created | updated | removed | unchanged | kept``.
+ action: str
+ scope: str
+ reason: str | None = None
+
+
+class SetupWriteResponse(BaseModel):
+ """What a write did. ``ok`` is the command's own success."""
+
+ ok: bool
+ #: The same change as a terminal command.
+ command: str
+ message: str = ""
+ #: The command's output, last lines first trimmed.
+ output: list[str] = Field(default_factory=list)
+ #: Agent config files, for the agents routes.
+ files: list[SetupFileChange] = Field(default_factory=list)
+
+
+class HookToggle(BaseModel):
+ enabled: bool
+
+
+class CoverageAddRequest(BaseModel):
+ #: A report file inside the repo, relative to its root or absolute.
+ path: str = Field(..., min_length=1, max_length=1024)
+
+
+class OnboardingPatch(BaseModel):
+ #: Marks the welcome seen for this repo, stamped with the server's time.
+ welcome_seen_repo: str | None = Field(None, pattern=_REPO_ID_RE)
+ setup_pill_hidden: bool | None = None
+ hosted_card_hidden: bool | None = None
+
+
+# -- write guard ---------------------------------------------------------------
+
+
+def _ui_ports(request: Request) -> set[int]:
+ """The API's own port, and the UI's when ``repowise serve`` started one.
+
+ Nothing else on the usual UI port is trusted by default; a UI started some
+ other way sets ``REPOWISE_UI_PORT`` for the API.
+ """
+ ports = {request.url.port or (443 if request.url.scheme == "https" else 80)}
+ raw = os.environ.get("REPOWISE_UI_PORT", "")
+ if raw.isdigit():
+ ports.add(int(raw))
+ return ports
+
+
+def _loopback_port(value: str) -> int | None:
+ """The port of an http(s) origin on a loopback name, else ``None``."""
+ parts = urlsplit(value)
+ if parts.scheme not in ("http", "https") or parts.hostname not in _LOOPBACK_NAMES:
+ return None
+ try:
+ return parts.port or (443 if parts.scheme == "https" else 80)
+ except ValueError:
+ return None
+
+
+def _from_own_ui(request: Request) -> bool:
+ """A browser request whose Origin is this server's UI on loopback.
+
+ Browsers send ``Origin`` on every write, same-origin included, and a page
+ cannot forge it. The Host check also turns away a DNS-rebound name.
+ """
+ if request.headers.get("sec-fetch-site", "same-origin") not in ("same-origin", "none"):
+ return False
+ if _loopback_port(f"http://{request.headers.get('host') or ''}") is None:
+ return False
+ port = _loopback_port(request.headers.get("origin") or "")
+ return port is not None and port in _ui_ports(request)
+
+
+def require_local_write(request: Request) -> None:
+ """403 unless this write comes from the local UI of a keyless, loopback server."""
+ if get_authenticator().configured():
+ raise HTTPException(
+ status_code=403,
+ detail="This server uses an API key or access tokens, so setup changes "
+ "from the browser are off. Run the command in a terminal on this machine.",
+ )
+ if not client_is_local(request):
+ raise HTTPException(
+ status_code=403, detail="Setup changes are accepted only from this machine."
+ )
+ if not _from_own_ui(request):
+ raise HTTPException(
+ status_code=403,
+ detail="Setup changes are accepted only from the repowise web UI on this machine.",
+ )
+
+
+def _onboarding_state() -> OnboardingState:
+ return OnboardingState(
+ **onboarding.load_onboarding(),
+ hints_enabled=account.hints_enabled(),
+ signed_in=account.is_signed_in(),
+ )
+
+
+# -- reads ---------------------------------------------------------------------
+
+
[email protected]("/api/repos/{repo_id}/setup", response_model=SetupResponse)
+async def get_setup(
+ request: Request,
+ repo: Repository = Depends(resolve_local_repo),
+ session: AsyncSession = Depends(get_db_session),
+) -> dict[str, Any]:
+ """Everything the Setup page shows for one repo, cached for a few seconds."""
+ payload = await setup_status.setup_payload(session, repo)
+ return {
+ **payload,
+ "onboarding": _onboarding_state(),
+ "writes_allowed": auth_is_open(request),
+ }
+
+
[email protected]("/api/setup/onboarding", response_model=OnboardingState)
+async def get_onboarding() -> OnboardingState:
+ """Per-machine onboarding state, without the repo checks the full payload runs."""
+ return _onboarding_state()
+
+
+# -- writes --------------------------------------------------------------------
+
+
+def _check_target(target: str) -> None:
+ if not _TARGET_RE.match(target) or target in _TARGET_KEYWORDS:
+ raise HTTPException(status_code=400, detail=f"Not an agent id: {target}")
+
+
+def _file_changes(payload: Any) -> list[SetupFileChange]:
+ """Every file ``repowise agents add|remove --format json`` reports."""
+ changes: list[SetupFileChange] = []
+ agents = payload.get("agents") if isinstance(payload, dict) else None
+ for agent in agents if isinstance(agents, list) else []:
+ for scope, write in (agent.get("writes") or {}).items():
+ for f in write.get("files") or []:
+ changes.append(
+ SetupFileChange(
+ path=str(f.get("path", "")),
+ action=str(f.get("action", "")),
+ scope=str(scope),
+ reason=f.get("reason"),
+ )
+ )
+ return changes
+
+
+#: What a hook command also changes, said on success so the switch holds no surprise.
+_HOOK_ALSO = {
+ ("post-commit", False): "This also turned off the pre-commit security check and "
+ "the health gate, if they were on.",
+ ("rewrite", True): "Codex and Cursor get the rewrite hook too, when they are installed.",
+ ("rewrite", False): "This also removed the Codex and Cursor rewrite hooks.",
+}
+
+
+def _write_response(
+ run: setup_cli.CliRun, command: str, *, note: str = "", **extra: Any
+) -> SetupWriteResponse:
+ message = note if run.ok else f"That didn't work here. Run it in a terminal: {command}"
+ output = [] if run.json() is not None else run.lines()
+ return SetupWriteResponse(
+ ok=run.ok, command=command, message=message, output=output, **extra
+ )
+
+
+async def _agents_write(repo: Repository, target: str, *, remove: bool) -> SetupWriteResponse:
+ _check_target(target)
+ run = await asyncio.to_thread(
+ setup_cli.agents_write, Path(repo.local_path), target, remove=remove
+ )
+ setup_status.invalidate(repo.id)
+ if run.exit_code == 2:
+ # Click's usage error: the CLI does not know this id.
+ raise HTTPException(status_code=400, detail=f"Not an agent id: {target}")
+ verb = "remove" if remove else "add"
+ command = f"repowise agents {verb} --target={target}"
+ return _write_response(run, command, files=_file_changes(run.json()))
+
+
+ "/api/repos/{repo_id}/setup/agents/{target}",
+ response_model=SetupWriteResponse,
+ dependencies=[Depends(require_local_write)],
+)
+async def connect_agent(
+ target: str, repo: Repository = Depends(resolve_local_repo)
+) -> SetupWriteResponse:
+ """``repowise agents add --target=<target>`` for this repo."""
+ return await _agents_write(repo, target, remove=False)
+
+
+ "/api/repos/{repo_id}/setup/agents/{target}",
+ response_model=SetupWriteResponse,
+ dependencies=[Depends(require_local_write)],
+)
+async def disconnect_agent(
+ target: str, repo: Repository = Depends(resolve_local_repo)
+) -> SetupWriteResponse:
+ """``repowise agents remove --target=<target>`` for this repo."""
+ return await _agents_write(repo, target, remove=True)
+
+
+ "/api/repos/{repo_id}/setup/hooks/{name}",
+ response_model=SetupWriteResponse,
+ dependencies=[Depends(require_local_write)],
+)
+async def set_hook(
+ name: str, body: HookToggle, repo: Repository = Depends(resolve_local_repo)
+) -> SetupWriteResponse:
+ """``repowise hook install|uninstall`` (``post-commit``) or ``hook rewrite ...`` (``rewrite``)."""
+ if name not in setup_cli.HOOK_COMMANDS:
+ raise HTTPException(status_code=404, detail=f"No hook named {name}")
+ run = await asyncio.to_thread(
+ setup_cli.hook_write, Path(repo.local_path), name, enabled=body.enabled
+ )
+ setup_status.invalidate(repo.id)
+ verb = "install" if body.enabled else "uninstall"
+ command = " ".join(["repowise", *setup_cli.HOOK_COMMANDS[name], verb])
+ return _write_response(run, command, note=_HOOK_ALSO.get((name, body.enabled), ""))
+
+
+def _report_inside_repo(repo_path: Path, raw: str) -> Path:
+ """The report as an absolute file inside the repo, or a 400."""
+ raw = raw.strip()
+ if any(ch in raw for ch in "*?[=") or raw.startswith("-"):
+ raise HTTPException(status_code=400, detail="Give one report file, without wildcards.")
+ root = repo_path.resolve()
+ candidate = Path(raw) if Path(raw).is_absolute() else root / raw
+ try:
+ report = candidate.resolve(strict=True)
+ except OSError:
+ raise HTTPException(status_code=400, detail=f"No file at {raw}") from None
+ if not report.is_relative_to(root):
+ raise HTTPException(status_code=400, detail="The report has to be inside this repository.")
+ if not report.is_file():
+ raise HTTPException(status_code=400, detail=f"{raw} is not a file")
+ return report
+
+
+ "/api/repos/{repo_id}/setup/coverage",
+ response_model=SetupWriteResponse,
+ dependencies=[Depends(require_local_write)],
+)
+async def add_coverage(
+ body: CoverageAddRequest, repo: Repository = Depends(resolve_local_repo)
+) -> SetupWriteResponse:
+ """``repowise coverage add <report>`` for a report inside this repo."""
+ repo_path = Path(repo.local_path)
+ report = _report_inside_repo(repo_path, body.path)
+ run = await asyncio.to_thread(setup_cli.coverage_add, repo_path, report)
+ setup_status.invalidate(repo.id)
+ relative = report.relative_to(repo_path.resolve()).as_posix()
+ return _write_response(run, f"repowise coverage add {relative}")
+
+
+ "/api/setup/onboarding",
+ response_model=OnboardingState,
+ dependencies=[Depends(require_local_write)],
+)
+async def patch_onboarding(body: OnboardingPatch) -> OnboardingState:
+ """Mark the welcome seen, or hide the setup pill or the hosted card, on this machine."""
+ try:
+ await asyncio.to_thread(
+ onboarding.update_onboarding,
+ welcome_seen_repo=body.welcome_seen_repo,
+ setup_pill_hidden=body.setup_pill_hidden,
+ hosted_card_hidden=body.hosted_card_hidden,
+ )
+ except OSError as exc:
+ raise HTTPException(
+ status_code=500, detail=f"Couldn't save ~/.repowise/platform.json ({exc})"
+ ) from exc
+ setup_status.invalidate()
+ return _onboarding_state()
diff --git a/packages/server/src/repowise/server/services/setup_cli.py b/packages/server/src/repowise/server/services/setup_cli.py
new file mode 100644
index 000000000..d705888d4
--- /dev/null
+++ b/packages/server/src/repowise/server/services/setup_cli.py
@@ -0,0 +1,134 @@
+"""Run the CLI commands the Setup page reads and writes through.
+
+The server never imports ``repowise.cli`` (see ``routers/platform.py``): agent
+detection, hook state and doctor live there, so each answer comes from the
+command a person would type, run in a child process with a timeout. Every
+function here is blocking; callers run it in a thread.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+#: Doctor starts the MCP server once to check it answers; leave room for that.
+_READ_TIMEOUT_SECONDS = 90.0
+#: Writes touch a few config files; coverage add parses a report.
+_WRITE_TIMEOUT_SECONDS = 180.0
+
+#: Kept off the child's output: a wide fixed width stops rich from wrapping
+#: paths, and UTF-8 keeps its glyphs from failing on a Windows code page.
+_CHILD_ENV = {"COLUMNS": "200", "PYTHONIOENCODING": "utf-8", "NO_COLOR": "1"}
+
+
+@dataclass(frozen=True)
+class CliRun:
+ """What one command did. ``exit_code`` is ``None`` when it could not run."""
+
+ exit_code: int | None
+ stdout: str
+ stderr: str
+
+ @property
+ def ok(self) -> bool:
+ return self.exit_code == 0
+
+ def json(self) -> Any:
+ """Parsed stdout, or ``None`` when it is not JSON."""
+ try:
+ return json.loads(self.stdout)
+ except ValueError:
+ return None
+
+ def lines(self, limit: int = 40) -> list[str]:
+ """The command's output, both streams, trimmed for a response body."""
+ text = "\n".join(part for part in (self.stdout, self.stderr) if part.strip())
+ return [line.rstrip() for line in text.splitlines() if line.strip()][-limit:]
+
+
+def run_cli(args: list[str], *, cwd: Path, timeout: float) -> CliRun:
+ """``repowise <args>`` in *cwd*. Never raises."""
+ argv = [sys.executable, "-m", "repowise.cli.main", *args]
+ try:
+ proc = subprocess.run(
+ argv,
+ cwd=str(cwd),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ check=False,
+ env={**os.environ, **_CHILD_ENV},
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ logger.warning("repowise %s could not run: %s", " ".join(args[:2]), exc)
+ return CliRun(None, "", str(exc))
+ return CliRun(proc.returncode, proc.stdout or "", proc.stderr or "")
+
+
+# -- reads -------------------------------------------------------------------
+
+
+def doctor_json(repo_path: Path) -> dict | None:
+ """``repowise doctor --format json`` for this repo; it exits 1 on a failed check."""
+ run = run_cli(
+ [
+ "doctor",
+ str(repo_path),
+ "--no-workspace",
+ "--format",
+ "json",
+ ],
+ cwd=repo_path,
+ timeout=_READ_TIMEOUT_SECONDS,
+ )
+ payload = run.json()
+ return payload if isinstance(payload, dict) else None
+
+
+def agents_json(repo_path: Path) -> dict | None:
+ """``repowise agents --format json``, which lists against the current directory."""
+ run = run_cli(["agents", "--format", "json"], cwd=repo_path, timeout=_READ_TIMEOUT_SECONDS)
+ payload = run.json()
+ return payload if isinstance(payload, dict) else None
+
+
+# -- writes ------------------------------------------------------------------
+
+
+def agents_write(repo_path: Path, target: str, *, remove: bool) -> CliRun:
+ """``repowise agents add|remove PATH --target=<id> --format json``."""
+ verb = "remove" if remove else "add"
+ args = ["agents", verb, str(repo_path), f"--target={target}", "--format", "json"]
+ if not remove:
+ args.append("--yes")
+ return run_cli(args, cwd=repo_path, timeout=_WRITE_TIMEOUT_SECONDS)
+
+
+#: Hook name -> the command group it maps to.
+HOOK_COMMANDS: dict[str, list[str]] = {
+ "post-commit": ["hook"],
+ "rewrite": ["hook", "rewrite"],
+}
+
+
+def hook_write(repo_path: Path, name: str, *, enabled: bool) -> CliRun:
+ """``repowise hook [rewrite] install|uninstall PATH --no-workspace``."""
+ verb = "install" if enabled else "uninstall"
+ args = [*HOOK_COMMANDS[name], verb, str(repo_path), "--no-workspace"]
+ return run_cli(args, cwd=repo_path, timeout=_WRITE_TIMEOUT_SECONDS)
+
+
+def coverage_add(repo_path: Path, report: Path) -> CliRun:
+ """``repowise coverage add REPORT --path PATH``; *report* is absolute and inside the repo."""
+ args = ["coverage", "add", str(report), "--path", str(repo_path)]
+ return run_cli(args, cwd=repo_path, timeout=_WRITE_TIMEOUT_SECONDS)
diff --git a/packages/server/src/repowise/server/services/setup_status.py b/packages/server/src/repowise/server/services/setup_status.py
new file mode 100644
index 000000000..f75c13e27
--- /dev/null
+++ b/packages/server/src/repowise/server/services/setup_status.py
@@ -0,0 +1,344 @@
+"""The Setup page's one payload: index, agents, hooks, coverage, model, checks.
+
+Agent, hook and doctor state come from the CLI's own JSON (see
+:mod:`.setup_cli`); the rest is read here from the index, the savings ledger,
+the coverage discovery and the provider settings the other routes already use.
+The payload is cached for a few seconds per repo, because doctor starts the MCP
+server once and a page load must not do that on every request.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import sqlite3
+import time
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import func, select
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import GraphNode, Repository
+from repowise.server.services import setup_cli
+
+logger = logging.getLogger(__name__)
+
+#: How long one payload answers repeat requests for the same repo.
+SETUP_CACHE_SECONDS = 5.0
+
+#: Bounds on the lists the payload carries.
+_PARSE_ERROR_FILES_LIMIT = 50
+_DISCOVERED_REPORTS_LIMIT = 10
+
+_cache: dict[str, tuple[float, dict[str, Any]]] = {}
+_locks: dict[str, asyncio.Lock] = {}
+#: Bumped by every write, so a build that started before it is not cached.
+_generation = 0
+
+
+def invalidate(repo_id: str | None = None) -> None:
+ """Drop the cached payload for *repo_id*, or every one when ``None``."""
+ global _generation
+ _generation += 1
+ if repo_id is None:
+ _cache.clear()
+ else:
+ _cache.pop(repo_id, None)
+
+
+async def setup_payload(session: AsyncSession, repo: Repository) -> dict[str, Any]:
+ """The cached payload for *repo*, built once per window even under concurrent loads."""
+ lock = _locks.setdefault(repo.id, asyncio.Lock())
+ async with lock:
+ hit = _cache.get(repo.id)
+ if hit is not None and time.monotonic() - hit[0] < SETUP_CACHE_SECONDS:
+ return hit[1]
+ started = _generation
+ payload = await _build(session, repo)
+ if started == _generation:
+ _cache[repo.id] = (time.monotonic(), payload)
+ return payload
+
+
+async def _build(session: AsyncSession, repo: Repository) -> dict[str, Any]:
+ repo_path = Path(repo.local_path)
+ index = await _index_section(session, repo)
+ ingest_ok, coverage_ingested_at = await _coverage_ingested_at(session, repo.id)
+ doctor, agents, local = await asyncio.gather(
+ asyncio.to_thread(setup_cli.doctor_json, repo_path),
+ asyncio.to_thread(setup_cli.agents_json, repo_path),
+ asyncio.to_thread(_local_sections, repo.id, repo_path),
+ )
+ checks = _checks(doctor)
+ agent_calls, coverage_files, (model_ok, model) = local
+ agent_rows, calls = _agents(agents, agent_calls or {})
+ return {
+ "repo_id": repo.id,
+ "generated_at": datetime.now(UTC).isoformat(),
+ "index": index,
+ "agents_available": agents is not None,
+ "agents": agent_rows,
+ "calls_available": agent_calls is not None,
+ "calls": calls,
+ "sync": _sync(checks),
+ "rewrite_hook": _rewrite_hook(checks, agent_rows),
+ "coverage_available": ingest_ok and coverage_files is not None,
+ "coverage": {
+ "ingested_at": coverage_ingested_at,
+ **(coverage_files or {"configured_paths": [], "discovered": []}),
+ },
+ "model_available": model_ok,
+ "model": model,
+ "checks_available": doctor is not None,
+ "checks": checks,
+ }
+
+
+# -- index -------------------------------------------------------------------
+
+
+async def _index_section(session: AsyncSession, repo: Repository) -> dict[str, Any]:
+ from repowise.core.git_head import read_head_commit
+ from repowise.core.persistence.crud import index_synced_at
+ from repowise.core.workspace.update import resolve_indexed_commit
+
+ is_file = (GraphNode.repository_id == repo.id) & (GraphNode.node_type == "file")
+ file_count = (await session.execute(select(func.count()).where(is_file))).scalar_one()
+ error_rows = await session.execute(
+ select(GraphNode.node_id).where(is_file, GraphNode.has_error.is_(True)).order_by(
+ GraphNode.node_id
+ )
+ )
+ error_files = [row[0] for row in error_rows]
+
+ indexed = resolve_indexed_commit(Path(repo.local_path), repo.head_commit).sha
+ live = read_head_commit(repo.local_path)
+ synced_at = index_synced_at(repo)
+ return {
+ "state": _index_state(file_count, indexed, live),
+ "indexed_commit": indexed,
+ "live_head": live,
+ "indexed_at": synced_at.isoformat() if synced_at else None,
+ "file_count": file_count,
+ "parse_error_count": len(error_files),
+ "parse_error_files": error_files[:_PARSE_ERROR_FILES_LIMIT],
+ }
+
+
+def _index_state(file_count: int, indexed: str | None, live: str | None) -> str:
+ """``incomplete`` without files or a resolvable commit; ``behind`` when HEAD moved."""
+ if not file_count or not indexed:
+ return "incomplete"
+ if live and live != indexed:
+ return "behind"
+ return "up_to_date"
+
+
+async def _coverage_ingested_at(session: AsyncSession, repo_id: str) -> tuple[bool, str | None]:
+ """``(read ok, newest ingest time)``; an unreadable table is not "never ingested"."""
+ from repowise.core.persistence.models import CoverageFile
+
+ try:
+ stamp = (
+ await session.execute(
+ select(func.max(CoverageFile.ingested_at)).where(
+ CoverageFile.repository_id == repo_id
+ )
+ )
+ ).scalar_one_or_none()
+ except SQLAlchemyError:
+ logger.warning("setup: could not read stored coverage for %s", repo_id, exc_info=True)
+ return False, None
+ return True, stamp.isoformat() if isinstance(stamp, datetime) else None
+
+
+# -- local files: ledger, coverage reports, model -----------------------------
+
+
+def _local_sections(
+ repo_id: str, repo_path: Path
+) -> tuple[dict[str, tuple[str, str]] | None, dict[str, Any] | None, tuple[bool, dict[str, Any]]]:
+ """The blocking reads that need no CLI, run together in one thread.
+
+ Each comes back ``None`` (or flagged) when it could not be read, so the
+ page can say so instead of showing an empty section.
+ """
+ return _agent_calls(repo_path), _coverage_files(repo_path), _model(repo_id, repo_path)
+
+
+def _agent_calls(repo_path: Path) -> dict[str, tuple[str, str]] | None:
+ """Per-agent call times; ``{}`` with no ledger yet, ``None`` when it could not be read."""
+ from repowise.core.savings.service import load_agent_calls
+
+ try:
+ return load_agent_calls(repo_path) or {}
+ except (sqlite3.Error, OSError):
+ logger.warning("setup: could not read the savings ledger in %s", repo_path, exc_info=True)
+ return None
+
+
+def _coverage_files(repo_path: Path) -> dict[str, Any] | None:
+ """Configured report paths and the reports discovery finds; ``None`` when unreadable."""
+ from repowise.core.analysis.health.coverage import CoverageConfig, discover_artifacts
+ from repowise.core.repo_config import load_repo_config
+
+ try:
+ cfg = CoverageConfig.from_repo_config(load_repo_config(repo_path))
+ found = discover_artifacts(repo_path, globs=cfg.artifacts or None)
+ except (OSError, ValueError):
+ # ValueError covers an unparsable .repowise/config.yaml (RepoConfigError).
+ logger.warning("setup: could not look for coverage in %s", repo_path, exc_info=True)
+ return None
+ now = time.time()
+ discovered = []
+ for report in found[:_DISCOVERED_REPORTS_LIMIT]:
+ try:
+ mtime = report.stat().st_mtime
+ except OSError:
+ continue
+ discovered.append(
+ {
+ "path": report.relative_to(repo_path).as_posix(),
+ "modified_at": datetime.fromtimestamp(mtime, UTC).isoformat(),
+ "age_days": max(0, int((now - mtime) // 86_400)),
+ }
+ )
+ return {"configured_paths": list(cfg.paths), "discovered": discovered}
+
+
+def _model(repo_id: str, repo_path: Path) -> tuple[bool, dict[str, Any]]:
+ """Docs mode from state.json, and the provider settings ``/api/providers`` reports.
+
+ ``(False, ...)`` when the provider settings could not be read; docs mode
+ is still filled in.
+ """
+ from repowise.core.docs_mode import resolve_docs_mode
+ from repowise.server.provider_config import list_provider_status
+
+ try:
+ state = json.loads((repo_path / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ state = {}
+ model: dict[str, Any] = {
+ "docs_mode": resolve_docs_mode(state if isinstance(state, dict) else {}),
+ "active_provider": None,
+ "active_model": None,
+ "configured_providers": [],
+ }
+ try:
+ status = list_provider_status(repo_id=repo_id, repo_path=repo_path)
+ except (OSError, ValueError):
+ # ValueError covers an unparsable config.yaml or .env (RepoConfigError).
+ logger.warning("setup: could not read provider settings for %s", repo_path, exc_info=True)
+ return False, model
+ model["active_provider"] = status["active"]["provider"]
+ model["active_model"] = status["active"]["model"]
+ model["configured_providers"] = [p["id"] for p in status["providers"] if p["configured"]]
+ return True, model
+
+
+# -- CLI answers --------------------------------------------------------------
+
+
+def _checks(doctor: dict | None) -> list[dict[str, Any]]:
+ """Doctor rows, keeping only the fields the page reads."""
+ rows = doctor.get("checks") if doctor else None
+ return [
+ {
+ "id": str(row.get("id") or ""),
+ "name": str(row.get("name") or ""),
+ "level": row.get("level") if row.get("level") in ("ok", "warn", "fail") else "warn",
+ "detail": str(row.get("detail") or ""),
+ "fix": row.get("fix") if isinstance(row.get("fix"), str) else None,
+ }
+ for row in (rows if isinstance(rows, list) else [])
+ if isinstance(row, dict)
+ ]
+
+
+def _agents(
+ listing: dict | None, calls: dict[str, tuple[str, str]]
+) -> tuple[list[dict[str, Any]], dict[str, Any]]:
+ """Agent rows with their own call times, and the repo-level call summary."""
+ from repowise.core.agents.identity import UNKNOWN_AGENT, identity_for_target_id
+
+ rows = []
+ for row in _listing_rows(listing):
+ identity = identity_for_target_id(str(row.get("id", "")))
+ first, last = calls.get(identity.slug, (None, None)) if identity else (None, None)
+ rows.append(_agent_row(row, first, last))
+ times = list(calls.values())
+ summary = {
+ "first_call_at": min((t[0] for t in times), default=None),
+ "last_call_at": max((t[1] for t in times), default=None),
+ # Calls whose client named no known agent count here and on no row.
+ "unattributed": UNKNOWN_AGENT in calls,
+ }
+ return rows, summary
+
+
+def _listing_rows(listing: dict | None) -> list[dict]:
+ rows = listing.get("agents") if listing else None
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+def _agent_row(row: dict, first: str | None, last: str | None) -> dict[str, Any]:
+ registrations = [r for r in row.get("registrations") or [] if isinstance(r, dict)]
+ files = row.get("config_files")
+ return {
+ "id": str(row.get("id", "")),
+ "display_name": str(row.get("display_name", "")),
+ "tier": row.get("tier"),
+ "docs_url": row.get("docs_url"),
+ "installed": bool(row.get("present")),
+ "connected": bool(registrations),
+ "registrations": [
+ {
+ "method": str(r.get("method", "")),
+ "scope": str(r.get("scope", "")),
+ "config_path": str(r.get("config_path", "")),
+ }
+ for r in registrations
+ ],
+ "config_files": files if isinstance(files, dict) else {},
+ "first_call_at": first,
+ "last_call_at": last,
+ }
+
+
+def _check(checks: list[dict[str, Any]], check_id: str) -> dict[str, Any] | None:
+ return next((c for c in checks if c["id"] == check_id), None)
+
+
+def _sync(checks: list[dict[str, Any]]) -> dict[str, Any]:
+ """The post-commit hook, from doctor's ``post-commit-hook`` row."""
+ row = _check(checks, "post-commit-hook")
+ if row is None:
+ return {"installed": None, "detail": ""}
+ detail = row["detail"]
+ installed: bool | None = None
+ if detail.startswith("installed"):
+ installed = True
+ elif detail.startswith("not installed"):
+ installed = False
+ return {"installed": installed, "detail": detail}
+
+
+def _rewrite_hook(checks: list[dict[str, Any]], agents: list[dict[str, Any]]) -> dict[str, Any]:
+ """The distill rewrite hook; ``not_applicable`` when Claude Code is not on this machine."""
+ row = _check(checks, "distill-rewrite-hook")
+ detail = row["detail"] if row else ""
+ claude = next((a for a in agents if a["id"] == "claude-code"), None)
+ if detail.startswith("installed"):
+ state = "installed"
+ elif claude is not None and not (claude["installed"] or claude["connected"]):
+ state = "not_applicable"
+ elif row is not None:
+ state = "not_installed"
+ else:
+ state = "unknown"
+ return {"state": state, "detail": detail}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 764a42ee4..47edafa2a 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1315,6 +1315,10 @@ export interface CouplingNodeResponse {
nloc?: number;
}
+export interface CoverageAddRequest {
+ path: string;
+}
+
/** One ingested report's repo-wide figures, as ``crud.load_coverage_history`` reads them. */
export interface CoverageHistoryPoint {
ingested_at: string;
@@ -2619,6 +2623,10 @@ export interface HealthWorkQueueResponse {
limit?: number;
}
+export interface HookToggle {
+ enabled: boolean;
+}
+
export interface HotFilesGraphResponse {
nodes: HotFilesNodeResponse[];
links: GraphEdgeResponse[];
@@ -2951,6 +2959,21 @@ export interface OkResponse {
ok?: boolean;
}
+export interface OnboardingPatch {
+ welcome_seen_repo?: string | null;
+ setup_pill_hidden?: boolean | null;
+ hosted_card_hidden?: boolean | null;
+}
+
+/** Per-machine onboarding state, plus the switches that hide hosted surfaces. */
+export interface OnboardingState {
+ welcome_seen?: Record<string, string>;
+ setup_pill_hidden?: boolean;
+ hosted_card_hidden?: boolean;
+ hints_enabled: boolean;
+ signed_in: boolean;
+}
+
/** Every display name and canonical email folded into one person. */
export interface OwnerAliases {
names: string[];
@@ -4093,6 +4116,115 @@ export interface SetApiKeyRequest {
repo_id?: string | null;
}
+export interface SetupAgent {
+ id: string;
+ display_name: string;
+ tier?: string | null;
+ docs_url?: string | null;
+ installed: boolean;
+ connected: boolean;
+ registrations?: SetupRegistration[];
+ config_files?: Record<string, string[]>;
+ first_call_at?: string | null;
+ last_call_at?: string | null;
+}
+
+/** Every call to this repo's index, whichever agent made it. */
+export interface SetupCalls {
+ first_call_at?: string | null;
+ last_call_at?: string | null;
+ unattributed?: boolean;
+}
+
+export interface SetupCheck {
+ id: string;
+ name: string;
+ level: "ok" | "warn" | "fail";
+ detail?: string;
+ fix?: string | null;
+}
+
+export interface SetupCoverage {
+ ingested_at?: string | null;
+ configured_paths?: string[];
+ discovered?: SetupCoverageReport[];
+}
+
+export interface SetupCoverageReport {
+ path: string;
+ modified_at: string;
+ age_days: number;
+}
+
+export interface SetupFileChange {
+ path: string;
+ action: string;
+ scope: string;
+ reason?: string | null;
+}
+
+export interface SetupIndex {
+ state: "up_to_date" | "behind" | "incomplete";
+ indexed_commit?: string | null;
+ live_head?: string | null;
+ indexed_at?: string | null;
+ file_count?: number;
+ parse_error_count?: number;
+ parse_error_files?: string[];
+}
+
+export interface SetupModel {
+ docs_mode: "none" | "deterministic" | "llm";
+ active_provider?: string | null;
+ active_model?: string | null;
+ configured_providers?: string[];
+}
+
+export interface SetupRegistration {
+ method: string;
+ scope: string;
+ config_path: string;
+}
+
+export interface SetupResponse {
+ repo_id: string;
+ generated_at: string;
+ index: SetupIndex;
+ agents_available: boolean;
+ agents?: SetupAgent[];
+ calls_available: boolean;
+ calls: SetupCalls;
+ sync: SetupSync;
+ rewrite_hook: SetupRewriteHook;
+ coverage_available: boolean;
+ coverage: SetupCoverage;
+ model_available: boolean;
+ model: SetupModel;
+ checks_available: boolean;
+ checks?: SetupCheck[];
+ onboarding: OnboardingState;
+ writes_allowed: boolean;
+}
+
+export interface SetupRewriteHook {
+ state: "installed" | "not_installed" | "not_applicable" | "unknown";
+ detail?: string;
+}
+
+export interface SetupSync {
+ installed?: boolean | null;
+ detail?: string;
+}
+
+/** What a write did. ``ok`` is the command's own success. */
+export interface SetupWriteResponse {
+ ok: boolean;
+ command: string;
+ message?: string;
+ output?: string[];
+ files?: SetupFileChange[];
+}
+
export interface SiloModule {
module: string;
owner: OwnerRef;
diff --git a/packages/web/src/lib/api/setup.ts b/packages/web/src/lib/api/setup.ts
new file mode 100644
index 000000000..534f03234
--- /dev/null
+++ b/packages/web/src/lib/api/setup.ts
@@ -0,0 +1,3 @@
+import "./client";
+
+export * from "@repowise-dev/api-client/setup";
diff --git a/scripts/export_openapi.py b/scripts/export_openapi.py
index 7c13a1620..fbaaba6ee 100644
--- a/scripts/export_openapi.py
+++ b/scripts/export_openapi.py
@@ -71,6 +71,7 @@ INTERNAL_TAGS = frozenset(
"owners",
"platform",
"providers",
+ "setup",
"stats",
}
)
diff --git a/tests/unit/savings/test_service.py b/tests/unit/savings/test_service.py
index 483d88a38..5d5ca031c 100644
--- a/tests/unit/savings/test_service.py
+++ b/tests/unit/savings/test_service.py
@@ -362,3 +362,22 @@ def test_an_interaction_that_saved_nothing_is_counted_but_not_averaged_in(
# 800/1000, not 800/2000: the second interaction is coverage, not a zero.
assert report.input_reduction_ratio == pytest.approx(0.8)
assert report.baseline_input_tokens == 1_000
+
+
+def test_agent_calls_give_each_agent_its_first_and_last_mcp_call(tmp_path: Path) -> None:
+ from repowise.core.savings.service import load_agent_calls
+
+ assert load_agent_calls(tmp_path) is None
+ _sidecar(tmp_path)
+ assert load_agent_calls(tmp_path) == {}
+ _record(tmp_path, baseline=10, agent="codex", occurred_at="2026-10-01T10:00:00Z")
+ _record(tmp_path, baseline=10, agent="codex", occurred_at="2026-10-03T10:00:00Z")
+ _record(tmp_path, baseline=10, agent="claude_code", occurred_at="2026-10-02T10:00:00Z")
+ # A distill event is not a call the agent made to the index.
+ _record(
+ tmp_path, baseline=10, agent="cursor", surface="distill", occurred_at="2026-10-04T10:00:00Z"
+ )
+ calls = load_agent_calls(tmp_path)
+ assert set(calls) == {"codex", "claude_code"}
+ assert calls["codex"][0].startswith("2026-10-01")
+ assert calls["codex"][1].startswith("2026-10-03")
diff --git a/tests/unit/server/test_setup_route.py b/tests/unit/server/test_setup_route.py
new file mode 100644
index 000000000..dccb3eeec
--- /dev/null
+++ b/tests/unit/server/test_setup_route.py
@@ -0,0 +1,590 @@
+"""/api/repos/{id}/setup and /api/setup: the Setup page's payload and its write routes."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from httpx import ASGITransport, AsyncClient
+
+from repowise.core.platform import telemetry
+from repowise.server import deps
+from repowise.server.routers import setup
+from repowise.server.services import setup_cli, setup_status
+from tests.unit.server.conftest import create_test_repo
+
+_UI = {"Origin": "http://localhost:3000"}
+_UI_PORT = "3000"
+
+_DOCTOR = {
+ "ok": False,
+ "checks": [
+ {"name": "Post-commit hook", "ok": True, "detail": "installed", "id": "post-commit-hook",
+ "level": "ok", "fix": None},
+ {"name": "Distill rewrite hook", "ok": True,
+ "detail": "not installed (opt-in: repowise hook rewrite install)",
+ "id": "distill-rewrite-hook", "level": "ok", "fix": None},
+ {"name": "Database", "ok": False, "detail": "wiki.db not found", "id": "database",
+ "level": "fail", "fix": "repowise init"},
+ ],
+}
+
+
+def _agents_listing(repo: str) -> dict:
+ return {
+ "repo": repo,
+ "agents": [
+ {
+ "id": "claude-code", "display_name": "Claude Code", "tier": "full",
+ "docs_url": None, "project_file_id": "claude-md", "present": True,
+ "method": "repowise",
+ "registrations": [
+ {"method": "repowise", "scope": "user", "config_path": "/h/.claude.json"}
+ ],
+ "config_files": {"project": [f"{repo}/.mcp.json"], "user": ["/h/.claude.json"]},
+ },
+ {
+ "id": "cursor", "display_name": "Cursor", "tier": "full", "docs_url": None,
+ "project_file_id": "cursor-rules", "present": True, "method": "repowise",
+ "registrations": [],
+ "config_files": {"project": [f"{repo}/.cursor/mcp.json"]},
+ },
+ ],
+ }
+
+
+def _agents_write_payload(target: str, action: str) -> dict:
+ return {
+ "action": "add",
+ "repo": "r",
+ "scope": "both",
+ "changed": True,
+ "agents": [
+ {
+ "id": target, "display_name": target, "method": "repowise", "skips": {},
+ "writes": {
+ "project": {
+ "files": [{"path": "/r/.cursor/mcp.json", "action": action,
+ "reason": None}],
+ "notes": [],
+ }
+ },
+ }
+ ],
+ }
+
+
+class FakeCli:
+ """Stands in for ``run_cli``: records argv and answers per command."""
+
+ def __init__(self, repo_path: str) -> None:
+ self.calls: list[list[str]] = []
+ self.repo_path = repo_path
+ self.exit_code = 0
+
+ def __call__(self, args: list[str], *, cwd: Path, timeout: float) -> setup_cli.CliRun:
+ self.calls.append(args)
+ if args[0] == "doctor":
+ return setup_cli.CliRun(1, json.dumps(_DOCTOR), "")
+ if args == ["agents", "--format", "json"]:
+ return setup_cli.CliRun(0, json.dumps(_agents_listing(self.repo_path)), "")
+ if args[0] == "agents":
+ action = "removed" if args[1] == "remove" else "created"
+ return setup_cli.CliRun(self.exit_code, json.dumps(_agents_write_payload("cursor", action)), "")
+ return setup_cli.CliRun(self.exit_code, "Post-commit hook: installed\n", "")
+
+
+def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ home = tmp_path / "home"
+ (home / ".repowise").mkdir(parents=True)
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))
+ for name in ("DO_NOT_TRACK", "REPOWISE_NO_HINTS"):
+ monkeypatch.delenv(name, raising=False)
+ # What `repowise serve` records when it starts the UI.
+ monkeypatch.setenv("REPOWISE_UI_PORT", _UI_PORT)
+ monkeypatch.setattr(telemetry, "_state_cache", None)
+ return home
+
+
+async def local(app, home: Path) -> AsyncClient:
+ """A loopback client addressed to the API the way the UI's proxy reaches it."""
+ app.include_router(setup.router)
+ setup_status.invalidate()
+ transport = ASGITransport(app=app, client=("127.0.0.1", 50000))
+ async with AsyncClient(transport=transport, base_url="http://localhost:7337") as c:
+ yield c
+ setup_status.invalidate()
+
+
+async def repo(local: AsyncClient, tmp_path: Path) -> dict:
+ return await create_test_repo(local, tmp_path)
+
+
+def cli(repo: dict, monkeypatch: pytest.MonkeyPatch) -> FakeCli:
+ fake = FakeCli(repo["local_path"])
+ monkeypatch.setattr(setup_cli, "run_cli", fake)
+ return fake
+
+
+# -- GET -----------------------------------------------------------------------
+
+
+async def test_setup_payload_shape(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from repowise.core.savings import service
+
+ monkeypatch.setattr(
+ service,
+ "load_agent_calls",
+ lambda root: {
+ "claude_code": ("2026-10-01T10:00:00Z", "2026-10-02T10:00:00Z"),
+ "unknown": ("2026-09-30T10:00:00Z", "2026-09-30T11:00:00Z"),
+ },
+ )
+ report = Path(repo["local_path"]) / "coverage" / "lcov.info"
+ report.parent.mkdir()
+ report.write_text("TN:\n", encoding="utf-8")
+
+ resp = await local.get(f"/api/repos/{repo['id']}/setup")
+ assert resp.status_code == 200
+ body = resp.json()
+
+ assert body["index"]["state"] == "incomplete" # no file nodes yet
+ assert body["agents_available"] is True
+ claude, cursor = body["agents"]
+ assert claude["connected"] and claude["installed"]
+ assert claude["first_call_at"] == "2026-10-01T10:00:00Z"
+ assert cursor["connected"] is False and cursor["installed"] is True
+ assert cursor["first_call_at"] is None
+ assert cursor["config_files"]["project"][0].endswith(".cursor/mcp.json")
+ assert body["calls"] == {
+ "first_call_at": "2026-09-30T10:00:00Z",
+ "last_call_at": "2026-10-02T10:00:00Z",
+ "unattributed": True,
+ }
+ assert body["sync"] == {"installed": True, "detail": "installed"}
+ assert body["rewrite_hook"]["state"] == "not_installed"
+ assert body["coverage"]["ingested_at"] is None
+ assert [r["path"] for r in body["coverage"]["discovered"]] == ["coverage/lcov.info"]
+ assert body["model"]["docs_mode"] == "none"
+ assert {c["id"] for c in body["checks"]} == {
+ "post-commit-hook", "distill-rewrite-hook", "database"
+ }
+ assert body["checks"][2] == {
+ "id": "database", "name": "Database", "level": "fail",
+ "detail": "wiki.db not found", "fix": "repowise init",
+ }
+ assert body["onboarding"] == {
+ "welcome_seen": {}, "setup_pill_hidden": False, "hosted_card_hidden": False,
+ "hints_enabled": True, "signed_in": False,
+ }
+ assert body["writes_allowed"] is True
+ assert body["calls_available"] and body["coverage_available"] and body["model_available"]
+
+
+async def test_setup_payload_is_cached_between_page_loads(
+ local: AsyncClient, repo: dict, cli: FakeCli
+) -> None:
+ await local.get(f"/api/repos/{repo['id']}/setup")
+ await local.get(f"/api/repos/{repo['id']}/setup")
+ assert sum(1 for c in cli.calls if c[0] == "doctor") == 1
+
+
+async def test_rewrite_hook_not_applicable_without_claude_code(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ listing = _agents_listing(repo["local_path"])
+ listing["agents"][0].update(present=False, registrations=[])
+ original = cli.__call__
+
+ def answer(args, *, cwd, timeout):
+ if args == ["agents", "--format", "json"]:
+ return setup_cli.CliRun(0, json.dumps(listing), "")
+ return original(args, cwd=cwd, timeout=timeout)
+
+ monkeypatch.setattr(setup_cli, "run_cli", answer)
+ body = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ assert body["rewrite_hook"]["state"] == "not_applicable"
+
+
+async def test_setup_degrades_when_the_cli_cannot_run(
+ local: AsyncClient, repo: dict, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ setup_cli, "run_cli", lambda args, **kw: setup_cli.CliRun(None, "", "no python")
+ )
+ body = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ assert body["agents_available"] is False and body["agents"] == []
+ assert body["checks_available"] is False and body["checks"] == []
+ assert body["sync"]["installed"] is None
+ assert body["rewrite_hook"]["state"] == "unknown"
+
+
+async def test_setup_flags_sections_it_could_not_read(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import sqlite3
+
+ from repowise.core.analysis.health import coverage
+ from repowise.core.savings import service
+ from repowise.server import provider_config
+
+ def ledger_locked(root):
+ raise sqlite3.OperationalError("database is locked")
+
+ def bad_config(**kwargs):
+ raise ValueError("Could not parse config.yaml")
+
+ def unreadable_dir(*args, **kwargs):
+ raise PermissionError("denied")
+
+ monkeypatch.setattr(service, "load_agent_calls", ledger_locked)
+ monkeypatch.setattr(provider_config, "list_provider_status", bad_config)
+ monkeypatch.setattr(coverage, "discover_artifacts", unreadable_dir)
+
+ resp = await local.get(f"/api/repos/{repo['id']}/setup")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["calls_available"] is False
+ assert body["coverage_available"] is False
+ assert body["model_available"] is False
+ assert body["model"]["docs_mode"] == "none"
+ # The CLI-backed sections are unaffected.
+ assert body["agents_available"] is True and body["checks_available"] is True
+
+
+# -- writes ----------------------------------------------------------------------
+
+
+async def test_connect_agent_runs_agents_add_and_names_the_files(
+ local: AsyncClient, repo: dict, cli: FakeCli
+) -> None:
+ resp = await local.post(f"/api/repos/{repo['id']}/setup/agents/cursor", headers=_UI)
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["command"] == "repowise agents add --target=cursor"
+ assert body["files"] == [
+ {"path": "/r/.cursor/mcp.json", "action": "created", "scope": "project", "reason": None}
+ ]
+ assert cli.calls[-1] == [
+ "agents", "add", repo["local_path"], "--target=cursor", "--format", "json", "--yes"
+ ]
+
+
+async def test_disconnect_agent_runs_agents_remove(
+ local: AsyncClient, repo: dict, cli: FakeCli
+) -> None:
+ resp = await local.delete(f"/api/repos/{repo['id']}/setup/agents/cursor", headers=_UI)
+ assert resp.status_code == 200
+ assert resp.json()["files"][0]["action"] == "removed"
+ assert cli.calls[-1] == [
+ "agents", "remove", repo["local_path"], "--target=cursor", "--format", "json"
+ ]
+
+
[email protected]("target", ["all", "auto", "none", "cursor,codex", "Cursor", "../x"])
+async def test_connect_agent_refuses_anything_but_one_id(
+ local: AsyncClient, repo: dict, cli: FakeCli, target: str
+) -> None:
+ resp = await local.post(f"/api/repos/{repo['id']}/setup/agents/{target}", headers=_UI)
+ assert resp.status_code in (400, 404)
+ assert cli.calls == []
+
+
+async def test_unknown_agent_id_is_400(local: AsyncClient, repo: dict, cli: FakeCli) -> None:
+ cli.exit_code = 2
+ resp = await local.post(f"/api/repos/{repo['id']}/setup/agents/notanagent", headers=_UI)
+ assert resp.status_code == 400
+
+
+ ("name", "enabled", "argv", "command"),
+ [
+ ("post-commit", True, ["hook", "install"], "repowise hook install"),
+ ("post-commit", False, ["hook", "uninstall"], "repowise hook uninstall"),
+ ("rewrite", True, ["hook", "rewrite", "install"], "repowise hook rewrite install"),
+ ("rewrite", False, ["hook", "rewrite", "uninstall"], "repowise hook rewrite uninstall"),
+ ],
+)
+async def test_hooks_run_the_hook_commands(
+ local: AsyncClient,
+ repo: dict,
+ cli: FakeCli,
+ name: str,
+ enabled: bool,
+ argv: list[str],
+ command: str,
+) -> None:
+ resp = await local.put(
+ f"/api/repos/{repo['id']}/setup/hooks/{name}", json={"enabled": enabled}, headers=_UI
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True and body["command"] == command
+ assert body["output"] == ["Post-commit hook: installed"]
+ # Turning sync off runs `hook uninstall`, which removes more; the answer says so.
+ assert ("security check" in body["message"]) is (name == "post-commit" and not enabled)
+ assert cli.calls[-1] == [*argv, repo["local_path"], "--no-workspace"]
+
+
+async def test_a_failed_hook_command_says_so(
+ local: AsyncClient, repo: dict, cli: FakeCli
+) -> None:
+ cli.exit_code = 1
+ resp = await local.put(
+ f"/api/repos/{repo['id']}/setup/hooks/post-commit", json={"enabled": True}, headers=_UI
+ )
+ body = resp.json()
+ assert body["ok"] is False
+ assert "repowise hook install" in body["message"]
+
+
+async def test_unknown_hook_is_404(local: AsyncClient, repo: dict, cli: FakeCli) -> None:
+ resp = await local.put(
+ f"/api/repos/{repo['id']}/setup/hooks/pre-push", json={"enabled": True}, headers=_UI
+ )
+ assert resp.status_code == 404
+ assert cli.calls == []
+
+
+async def test_coverage_add_runs_for_a_report_inside_the_repo(
+ local: AsyncClient, repo: dict, cli: FakeCli
+) -> None:
+ report = Path(repo["local_path"]) / "coverage" / "lcov.info"
+ report.parent.mkdir()
+ report.write_text("TN:\n", encoding="utf-8")
+ resp = await local.post(
+ f"/api/repos/{repo['id']}/setup/coverage", json={"path": "coverage/lcov.info"}, headers=_UI
+ )
+ assert resp.status_code == 200
+ assert resp.json()["command"] == "repowise coverage add coverage/lcov.info"
+ assert cli.calls[-1] == [
+ "coverage", "add", str(report.resolve()), "--path", repo["local_path"]
+ ]
+
+
[email protected]("path", ["../outside.info", "coverage/*.info", "missing.info", "a=b"])
+async def test_coverage_add_refuses_paths_outside_or_vague(
+ local: AsyncClient, repo: dict, cli: FakeCli, tmp_path: Path, path: str
+) -> None:
+ (Path(repo["local_path"]).parent / "outside.info").write_text("TN:\n", encoding="utf-8")
+ resp = await local.post(
+ f"/api/repos/{repo['id']}/setup/coverage", json={"path": path}, headers=_UI
+ )
+ assert resp.status_code == 400
+ assert cli.calls == []
+
+
+# -- write refusals ----------------------------------------------------------------
+
+
+ "headers",
+ [
+ {},
+ {"Origin": "https://evil.example"},
+ {"Origin": "http://localhost:8080"},
+ {"Origin": "null"},
+ {"Origin": "http://localhost:3000", "Sec-Fetch-Site": "cross-site"},
+ {"Origin": "http://localhost:3000", "Sec-Fetch-Site": "same-site"},
+ {"Origin": "http://localhost:3000", "Host": "rebound.example:7337"},
+ ],
+)
+async def test_writes_refuse_requests_not_from_the_local_ui(
+ local: AsyncClient, repo: dict, cli: FakeCli, headers: dict
+) -> None:
+ resp = await local.put(
+ f"/api/repos/{repo['id']}/setup/hooks/post-commit", json={"enabled": True}, headers=headers
+ )
+ assert resp.status_code == 403
+ assert "web UI" in resp.json()["detail"]
+ assert cli.calls == []
+
+
+async def test_writes_accept_the_api_port_and_the_recorded_ui_port(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ url = f"/api/repos/{repo['id']}/setup/hooks/post-commit"
+ ok = await local.put(url, json={"enabled": True}, headers={"Origin": "http://127.0.0.1:7337"})
+ assert ok.status_code == 200
+ monkeypatch.setenv("REPOWISE_UI_PORT", "4123")
+ moved = await local.put(url, json={"enabled": True}, headers={"Origin": "http://localhost:4123"})
+ assert moved.status_code == 200
+ old = await local.put(url, json={"enabled": True}, headers=_UI)
+ assert old.status_code == 403
+ # With no UI recorded, the usual UI port is not trusted on its own.
+ monkeypatch.delenv("REPOWISE_UI_PORT")
+ unrecorded = await local.put(url, json={"enabled": True}, headers=_UI)
+ assert unrecorded.status_code == 403
+
+
+async def test_writes_refused_when_the_server_has_an_api_key(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(deps, "_API_KEY", "secret")
+ resp = await local.put(
+ f"/api/repos/{repo['id']}/setup/hooks/post-commit",
+ json={"enabled": True},
+ headers={**_UI, "Authorization": "Bearer secret"},
+ )
+ assert resp.status_code == 403
+ assert "API key" in resp.json()["detail"]
+ assert cli.calls == []
+ # Reads still follow the usual auth, and say writes are off.
+ body = (
+ await local.get(
+ f"/api/repos/{repo['id']}/setup", headers={"Authorization": "Bearer secret"}
+ )
+ ).json()
+ assert body["writes_allowed"] is False
+
+
+async def test_writes_refused_from_a_remote_peer(app, repo: dict, cli: FakeCli) -> None:
+ transport = ASGITransport(app=app, client=("10.0.0.5", 50000))
+ async with AsyncClient(transport=transport, base_url="http://localhost:7337") as remote:
+ resp = await remote.put(
+ f"/api/repos/{repo['id']}/setup/hooks/post-commit",
+ json={"enabled": True},
+ headers=_UI,
+ )
+ assert resp.status_code == 403
+ assert cli.calls == []
+
+
+# -- onboarding -------------------------------------------------------------------
+
+
+async def test_onboarding_round_trip(local: AsyncClient, home: Path) -> None:
+ platform_json = home / ".repowise" / "platform.json"
+ platform_json.write_text(json.dumps({"anon_id": "keep-me"}), encoding="utf-8")
+
+ resp = await local.patch(
+ "/api/setup/onboarding",
+ json={"welcome_seen_repo": "abc123", "hosted_card_hidden": True},
+ headers=_UI,
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert set(body["welcome_seen"]) == {"abc123"}
+ assert body["hosted_card_hidden"] is True and body["setup_pill_hidden"] is False
+
+ again = (await local.get("/api/setup/onboarding")).json()
+ assert again == body
+ stored = json.loads(platform_json.read_text(encoding="utf-8"))
+ assert stored["anon_id"] == "keep-me"
+ assert stored["onboarding"]["welcome_seen"] == body["welcome_seen"]
+
+ await local.patch("/api/setup/onboarding", json={"hosted_card_hidden": False}, headers=_UI)
+ after = (await local.get("/api/setup/onboarding")).json()
+ assert after["hosted_card_hidden"] is False
+ assert set(after["welcome_seen"]) == {"abc123"}
+ assert json.loads(platform_json.read_text(encoding="utf-8"))["anon_id"] == "keep-me"
+
+
+async def test_onboarding_reports_hint_switches(
+ local: AsyncClient, home: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("DO_NOT_TRACK", "1")
+ (home / ".repowise" / "credentials.json").write_text(
+ json.dumps({"access_token": "t"}), encoding="utf-8"
+ )
+ body = (await local.get("/api/setup/onboarding")).json()
+ assert body["hints_enabled"] is False and body["signed_in"] is True
+
+
+async def test_onboarding_write_never_replaces_a_file_it_cannot_read(
+ local: AsyncClient, home: Path
+) -> None:
+ platform_json = home / ".repowise" / "platform.json"
+ platform_json.write_text('{"anon_id": "keep-me", ', encoding="utf-8")
+ resp = await local.patch(
+ "/api/setup/onboarding", json={"setup_pill_hidden": True}, headers=_UI
+ )
+ assert resp.status_code == 500
+ assert platform_json.read_text(encoding="utf-8") == '{"anon_id": "keep-me", '
+
+
+async def test_a_write_during_a_build_keeps_the_old_payload_out_of_the_cache(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ real_build = setup_status._build
+
+ async def build_then_write(session, row):
+ payload = await real_build(session, row)
+ setup_status.invalidate(row.id) # a write lands while this build runs
+ return payload
+
+ monkeypatch.setattr(setup_status, "_build", build_then_write)
+ await local.get(f"/api/repos/{repo['id']}/setup")
+ assert repo["id"] not in setup_status._cache
+
+
+async def test_onboarding_patch_needs_the_local_ui(local: AsyncClient, home: Path) -> None:
+ resp = await local.patch("/api/setup/onboarding", json={"setup_pill_hidden": True})
+ assert resp.status_code == 403
+ assert not (home / ".repowise" / "platform.json").exists()
+
+
+async def test_onboarding_rejects_a_malformed_repo_id(local: AsyncClient) -> None:
+ resp = await local.patch(
+ "/api/setup/onboarding", json={"welcome_seen_repo": "../../x"}, headers=_UI
+ )
+ assert resp.status_code == 422
+
+
+ ("command", "flags"),
+ [
+ (["doctor"], ["--no-workspace", "--format"]),
+ (["agents", "add"], ["--target", "--format", "--yes"]),
+ (["agents", "remove"], ["--target", "--format"]),
+ (["hook", "install"], ["--no-workspace"]),
+ (["hook", "uninstall"], ["--no-workspace"]),
+ (["hook", "rewrite", "install"], ["--no-workspace"]),
+ (["hook", "rewrite", "uninstall"], ["--no-workspace"]),
+ (["coverage", "add"], ["--path"]),
+ ],
+)
+def test_the_cli_commands_take_the_flags_the_routes_pass(
+ command: list[str], flags: list[str]
+) -> None:
+ """The routes run these commands in a child process; their flags must exist."""
+ from click.testing import CliRunner
+
+ from repowise.cli.main import cli as repowise_cli
+
+ result = CliRunner().invoke(repowise_cli, [*command, "--help"])
+ assert result.exit_code == 0, result.output
+ for flag in flags:
+ assert flag in result.output