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.

refactor(serve): split serve_cmd into a package and serve_command into steps (#3982)

Raghav Chamadiya050636e22dc6
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index 4fc99ffda..1fa7093b9 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -178,7 +178,7 @@ file, every surface behaves exactly as described below.
(`deps.py`, `client_is_local`). The known consequence is that a same-host
reverse proxy makes every peer loopback, so that deployment shape still needs
the key. `repowise serve --host 0.0.0.0` without a key prints a warning at
-startup (`packages/cli/src/repowise/cli/commands/serve_cmd.py`) and the
+startup (`packages/cli/src/repowise/cli/commands/serve_cmd/command.py`) and the
requests themselves are refused as above. All three rows were exercised against
a running app with a fabricated remote peer.
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.py
deleted file mode 100644
index 8876c509b..000000000
--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py
+++ /dev/null
@@ -1,819 +0,0 @@
-"""``repowise serve`` — start the API server and web UI."""
-
-from __future__ import annotations
-
-import contextlib
-import json
-import os
-import posixpath
-import shutil
-import socket
-import subprocess
-import tarfile
-import tempfile
-from datetime import UTC, datetime
-from pathlib import Path, PurePosixPath, PureWindowsPath
-
-import click
-
-from repowise.cli import __version__
-from repowise.cli.helpers import console, load_config
-
-_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.
-
- The lockfile lets other local tooling discover a running server (port,
- pid) without port-scanning. It lives next to the index the server is
- serving: ``.repowise/`` for a single repo, ``.repowise-workspace/`` for a
- workspace root. Returns None when neither exists (nothing to serve).
- """
- base = cwd or Path.cwd()
- for dirname in (".repowise", ".repowise-workspace"):
- candidate = base / dirname
- if candidate.is_dir():
- return candidate / _SERVE_LOCK_NAME
- return None
-
-
-def _write_serve_lock(lock_path: Path, *, host: str, port: int, ui_port: int | None) -> None:
- """Best-effort write of the discovery lockfile. Never blocks startup.
-
- Consumers must treat ``pid`` as the liveness check: a killed server
- cannot clean up after itself, so a stale file with a dead pid means
- "not running".
- """
- # A wildcard bind isn't a connectable URL; loopback always is.
- url_host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
- payload = {
- "pid": os.getpid(),
- "host": host,
- "port": port,
- "url": f"http://{url_host}:{port}",
- "ui_port": ui_port,
- "server_version": __version__,
- "started_at": datetime.now(UTC).isoformat(),
- }
- with contextlib.suppress(OSError):
- lock_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
-
-
-def _remove_serve_lock(lock_path: Path) -> None:
- """Best-effort removal; only removes a lock owned by this process."""
- try:
- data = json.loads(lock_path.read_text(encoding="utf-8"))
- if data.get("pid") == os.getpid():
- lock_path.unlink()
- except (OSError, ValueError):
- pass
-
-
-def _setup_embedder() -> None:
- """Ensure REPOWISE_EMBEDDER is set before the server starts.
-
- Priority:
- 1. Already set in environment → nothing to do.
- 2. Saved in ~/.repowise/config.yaml → restore it (and its API key).
- 3. Prompt the user interactively → save choice for next time.
- """
- if os.environ.get("REPOWISE_EMBEDDER"):
- return
-
- # Check global config saved by a previous serve/init run.
- cfg = load_config(Path.home())
- saved_embedder = cfg.get("embedder", "")
- if saved_embedder and saved_embedder != "mock":
- os.environ["REPOWISE_EMBEDDER"] = saved_embedder
- # Restore API key if saved alongside the config.
- if cfg.get("embedder_api_key"):
- _set_api_key_env(saved_embedder, cfg["embedder_api_key"])
- return
-
- # Detect which providers already have keys in the environment.
- has_gemini = bool(os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"))
- has_openai = bool(os.environ.get("OPENAI_API_KEY"))
- has_openrouter = bool(os.environ.get("OPENROUTER_API_KEY"))
-
- console.print(
- "\n[bold]Chat & search require an embedder.[/bold] "
- "Choose one or skip (other features still work).\n"
- )
-
- options = []
- labels = []
- if has_gemini:
- options.append("gemini")
- labels.append("[1] gemini [green]✓ key set[/green]")
- else:
- options.append("gemini")
- labels.append("[1] gemini [dim]needs GEMINI_API_KEY / GOOGLE_API_KEY[/dim]")
- if has_openai:
- options.append("openai")
- labels.append("[2] openai [green]✓ key set[/green]")
- else:
- options.append("openai")
- labels.append("[2] openai [dim]needs OPENAI_API_KEY[/dim]")
- if has_openrouter:
- options.append("openrouter")
- labels.append("[3] openrouter [green]✓ key set[/green]")
- else:
- options.append("openrouter")
- labels.append("[3] openrouter [dim]needs OPENROUTER_API_KEY[/dim]")
- options.append("skip")
- labels.append(f"[{len(options)}] skip [dim]no chat/search[/dim]")
-
- for label in labels:
- console.print(f" {label}")
- console.print()
-
- default = "1" if (has_gemini or has_openai) else "3"
- raw = click.prompt(" Select", default=default).strip()
-
- # Map number or name to option.
- choice = (
- raw
- if raw in options
- else (options[int(raw) - 1] if raw.isdigit() and 1 <= int(raw) <= len(options) else "skip")
- )
-
- if choice == "skip":
- console.print("[dim]Skipping embedder — chat and search will be unavailable.[/dim]\n")
- return
-
- os.environ["REPOWISE_EMBEDDER"] = choice
-
- # Ensure the API key is present; prompt if missing.
- api_key = _get_or_prompt_api_key(choice)
- if api_key:
- _set_api_key_env(choice, api_key)
-
- # Save choice (and key) to ~/.repowise/config.yaml for future runs.
- _save_global_embedder(choice, api_key)
- console.print()
-
-
-def _get_or_prompt_api_key(embedder: str) -> str:
- """Return existing API key for *embedder* or prompt the user for one."""
- if embedder == "gemini":
- key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
- if key:
- return key
- return click.prompt(" GEMINI_API_KEY", default="", show_default=False).strip()
- if embedder == "openai":
- key = os.environ.get("OPENAI_API_KEY", "")
- if key:
- return key
- return click.prompt(" OPENAI_API_KEY", default="", show_default=False).strip()
- if embedder == "openrouter":
- key = os.environ.get("OPENROUTER_API_KEY", "")
- if key:
- return key
- return click.prompt(" OPENROUTER_API_KEY", default="", show_default=False).strip()
- return ""
-
-
-def _set_api_key_env(embedder: str, key: str) -> None:
- if not key:
- return
- if embedder == "gemini":
- os.environ.setdefault("GEMINI_API_KEY", key)
- elif embedder == "openai":
- os.environ.setdefault("OPENAI_API_KEY", key)
- elif embedder == "openrouter":
- os.environ.setdefault("OPENROUTER_API_KEY", key)
-
-
-def _save_global_embedder(embedder: str, api_key: str) -> None:
- """Persist embedder choice to ~/.repowise/config.yaml."""
- _GLOBAL_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
- config_path = _GLOBAL_CONFIG_DIR / "config.yaml"
- try:
- existing: dict = {}
- if config_path.exists():
- import yaml # type: ignore[import-untyped]
-
- existing = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
- existing["embedder"] = embedder
- if api_key:
- existing["embedder_api_key"] = api_key
- import yaml # type: ignore[import-untyped]
-
- config_path.write_text(
- yaml.dump(existing, default_flow_style=False, sort_keys=False),
- encoding="utf-8",
- )
- except Exception:
- pass # Non-fatal — user just gets prompted again next time.
-
-
-def _load_local_provider_config() -> None:
- """Load ``.repowise/.env`` and seed the embedder from ``config.yaml``.
-
- The API server runs in-process here and builds one process-wide embedder
- at startup from env vars, so those are set now. ``load_dotenv`` never
- overwrites an existing var, and the embedder vars are only set when unset,
- so explicit environment configuration always wins. The chat provider
- needs no seeding: it is resolved per repo from that repo's own files.
- """
- from repowise.cli.helpers import load_config
- from repowise.cli.ui import load_dotenv
-
- cwd = Path.cwd()
- if not (cwd / ".repowise").exists():
- return
-
- # 1) API keys (OPENAI_API_KEY, ANTHROPIC_API_KEY, …) from .repowise/.env
- load_dotenv(cwd)
- cfg = load_config(cwd)
-
- # 2) Embedder from config so chat/search work without an interactive prompt.
- # Including "mock": that pin is not a preference to be talked out of, it is
- # the width the table on disk was written at. Skipping it sent a keyless
- # repo down _setup_embedder's detection path, which picks up any exported
- # API key and queries an 8-wide table with 1536-wide vectors — search
- # returns nothing, and nothing says why.
- embedder = cfg.get("embedder")
- if embedder and not os.environ.get("REPOWISE_EMBEDDER"):
- os.environ["REPOWISE_EMBEDDER"] = str(embedder)
-
- # 3) Embedding model from config — without this the server rebuilds the
- # embedder with a provider default (e.g. text-embedding-3-small) that
- # mismatches the indexed vectors, degrading chat/search retrieval (#426).
- embedding_model = cfg.get("embedding_model")
- if embedding_model and not os.environ.get("REPOWISE_EMBEDDING_MODEL"):
- os.environ["REPOWISE_EMBEDDING_MODEL"] = str(embedding_model)
-
-
-def _is_port_free(host: str, port: int) -> bool:
- """Return True if *port* can be bound on *host* right now."""
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
- if os.name != "nt":
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- try:
- sock.bind((host, port))
- except OSError:
- return False
- return True
-
-
-def _find_free_port(host: str, preferred: int, label: str, max_attempts: int = 20) -> int:
- """Return *preferred* if free, otherwise the next free port within range.
-
- Falls back to an OS-assigned port if a contiguous slot can't be found.
- Prints a notice when the preferred port is unavailable so the user knows
- the bind moved.
- """
- if _is_port_free(host, preferred):
- return preferred
-
- for offset in range(1, max_attempts + 1):
- candidate = preferred + offset
- if candidate > 65535:
- break
- if _is_port_free(host, candidate):
- console.print(
- f"[yellow]Port {preferred} for {label} is in use — using {candidate} instead.[/yellow]"
- )
- return candidate
-
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
- sock.bind((host, 0))
- candidate = sock.getsockname()[1]
- console.print(
- f"[yellow]Port {preferred} for {label} and nearby ports busy — using {candidate}.[/yellow]"
- )
- return candidate
-
-
-_GITHUB_REPO = "repowise-dev/repowise"
-_WEB_CACHE_DIR = Path.home() / ".repowise" / "web"
-_MARKER_FILE = _WEB_CACHE_DIR / ".version"
-
-
-_NODE_MIN_MAJOR = 20 # Next.js 15 (see packages/web/package.json engines.node)
-
-
-def _node_available() -> str | None:
- """Return the path to node binary, or None."""
- return shutil.which("node")
-
-
-def _node_major_version(node: str) -> int | None:
- """Return the major version of the *node* binary, or None if it can't be read.
-
- A failure to invoke or parse is treated as "unknown" rather than fatal — the
- caller decides whether to proceed or fall back.
- """
- try:
- result = subprocess.run(
- [node, "--version"],
- capture_output=True,
- text=True,
- timeout=5,
- check=True,
- )
- except (OSError, subprocess.SubprocessError):
- return None
-
- raw = result.stdout.strip().lstrip("v")
- head = raw.split(".", 1)[0]
- try:
- return int(head)
- except ValueError:
- return None
-
-
-def _npm_available() -> str | None:
- """Return the path to npm binary, or None."""
- return shutil.which("npm")
-
-
-def _web_is_cached(version: str) -> bool:
- """Check if the web frontend is cached and matches the current version."""
- server_js = _WEB_CACHE_DIR / "server.js"
- if not server_js.exists():
- return False
- return _MARKER_FILE.exists() and _MARKER_FILE.read_text().strip() == version
-
-
-def _find_local_web() -> Path | None:
- """Check if running from the repo with packages/web available."""
- # Check from both __file__ (source installs) and cwd (pip-installed runs)
- roots = [Path(__file__).resolve(), Path.cwd().resolve()]
- for start in roots:
- candidate = start
- for _ in range(10):
- candidate = candidate.parent
- pkg_web = candidate / "packages" / "web"
- if (pkg_web / "package.json").exists():
- # Next.js standalone in monorepos nests server under package path
- standalone = pkg_web / ".next" / "standalone" / "packages" / "web" / "server.js"
- if standalone.exists():
- return pkg_web
- return pkg_web # exists but may need build
- return None
-
-
-def _local_build_is_stale(web_dir: Path) -> bool:
- """True if the local .next/standalone bundle is older than any input source.
-
- Compares the standalone server.js mtime against the newest mtime under the
- source roots that get compiled into the bundle (web/ui/types packages plus
- web's config files). Skips node_modules / .next / .turbo. Used so that a
- cloned monorepo with stale build artifacts falls back to the released
- tarball instead of serving a bundle behind the user's source tree.
- """
- standalone = web_dir / ".next" / "standalone" / "packages" / "web" / "server.js"
- if not standalone.exists():
- return True
- build_mtime = standalone.stat().st_mtime
-
- repo_root = web_dir.parent.parent # packages/web → repo root
- skip_dirs = {"node_modules", ".next", ".turbo", "dist", ".git"}
-
- file_inputs: list[Path] = [
- web_dir / "package.json",
- web_dir / "next.config.ts",
- web_dir / "next.config.js",
- web_dir / "tsconfig.json",
- ]
- dir_inputs: list[Path] = [
- web_dir / "src",
- web_dir / "app",
- web_dir / "components",
- web_dir / "lib",
- web_dir / "public",
- repo_root / "packages" / "ui" / "src",
- repo_root / "packages" / "types" / "src",
- ]
-
- for f in file_inputs:
- if f.exists() and f.is_file() and f.stat().st_mtime > build_mtime:
- return True
-
- for root in dir_inputs:
- if not root.exists():
- continue
- for path in root.rglob("*"):
- if any(part in skip_dirs for part in path.parts):
- continue
- try:
- if path.is_file() and path.stat().st_mtime > build_mtime:
- return True
- except OSError:
- continue
- return False
-
-
-def _safe_extract_tar(archive: Path, dest: Path) -> None:
- """Extract a .tar.gz into ``dest``, refusing any member that would land outside it."""
- root = dest.resolve()
-
- def _inside(target: Path) -> bool:
- return target == root or target.is_relative_to(root)
-
- def _check_name(raw: str, member: str, what: str) -> str:
- name = raw.replace("\\", "/")
- # A colon covers drive-relative names (C:x) and NTFS alternate data streams.
- if (
- name.startswith("/")
- or Path(name).is_absolute()
- or PureWindowsPath(name).drive
- or ":" in name
- ):
- raise ValueError(f"archive {what} is absolute or drive-qualified: {member}")
- return name
-
- with tarfile.open(archive, "r:gz") as tar:
- members = tar.getmembers()
- symlinks = {posixpath.normpath(m.name.replace("\\", "/")) for m in members if m.issym()}
- for m in members:
- name = _check_name(m.name, m.name, "member path")
- target = (root / name).resolve()
- if not _inside(target):
- raise ValueError(f"archive member escapes the destination: {m.name}")
- # Static resolution cannot follow links the archive itself creates, so no
- # path may pass through one (blocks chains like a -> . then a/b -> ..).
- parts = PurePosixPath(posixpath.normpath(name)).parts
- if any("/".join(parts[:i]) in symlinks for i in range(1, len(parts))):
- raise ValueError(f"archive member passes through a link: {m.name}")
- if m.issym() or m.islnk():
- link = _check_name(m.linkname, m.name, "link target")
- # Symlinks resolve from the member's directory, hardlinks from the root.
- base = target.parent if m.issym() else root
- if not _inside((base / link).resolve()):
- raise ValueError(f"archive link escapes the destination: {m.name}")
- if m.islnk():
- lparts = PurePosixPath(posixpath.normpath(link)).parts
- if any("/".join(lparts[:i]) in symlinks for i in range(1, len(lparts) + 1)):
- raise ValueError(f"archive link passes through a link: {m.name}")
- elif not (m.isfile() or m.isdir()):
- raise ValueError(f"archive member is not a file or directory: {m.name}")
- # The stdlib data filter (3.11.4+) re-checks the same rules at write time.
- if hasattr(tarfile, "data_filter"):
- tar.extractall(root, members=members, filter="data")
- else:
- tar.extractall(root, members=members)
-
-
-def _download_web(version: str) -> bool:
- """Download pre-built web frontend from GitHub releases."""
- import httpx
-
- tag = f"v{version}"
- url = f"https://github.com/{_GITHUB_REPO}/releases/download/{tag}/repowise-web.tar.gz"
-
- console.print(f"[dim]Downloading web UI ({url})...[/dim]")
- try:
- tmp_path = None
- with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as tmp:
- tmp_path = tmp.name
- with httpx.stream("GET", url, follow_redirects=True, timeout=120) as resp:
- resp.raise_for_status()
- for chunk in resp.iter_bytes(chunk_size=65536):
- tmp.write(chunk)
- except (httpx.HTTPStatusError, httpx.RequestError) as exc:
- console.print(f"[yellow]Could not download web UI: {exc}[/yellow]")
- if tmp_path:
- os.unlink(tmp_path)
- return False
-
- try:
- _WEB_CACHE_DIR.mkdir(parents=True, exist_ok=True)
- # Clean old cache
- for item in _WEB_CACHE_DIR.iterdir():
- if item.is_dir():
- shutil.rmtree(item)
- else:
- item.unlink()
-
- _safe_extract_tar(Path(tmp_path), _WEB_CACHE_DIR)
-
- _MARKER_FILE.write_text(version)
- console.print("[green]Web UI downloaded and cached.[/green]")
- return True
- except Exception as exc:
- console.print(f"[yellow]Failed to extract web UI: {exc}[/yellow]")
- return False
- finally:
- os.unlink(tmp_path)
-
-
-def _build_local_web(web_dir: Path, npm: str) -> bool:
- """Build the Next.js frontend from source."""
- console.print("[dim]Building web UI (first time only)...[/dim]")
- try:
- # Install deps if needed
- if not (web_dir / "node_modules").exists():
- subprocess.run(
- [npm, "install"],
- cwd=str(web_dir),
- check=True,
- capture_output=True,
- )
- # Build
- subprocess.run(
- [npm, "run", "build"],
- cwd=str(web_dir),
- check=True,
- capture_output=True,
- )
- return True
- except subprocess.CalledProcessError as exc:
- console.print(f"[yellow]Web UI build failed: {exc}[/yellow]")
- return False
-
-
-def _start_frontend(
- node: str,
- backend_port: int,
- frontend_port: int,
- local_web: Path | None = None,
- host: str = "127.0.0.1",
-) -> subprocess.Popen | None:
- """Start the Next.js frontend server. Returns the process or None.
-
- If ``local_web`` is provided, the local monorepo build is used as Option 1.
- Pass ``None`` to skip the local build (e.g. when it's stale or refresh was
- forced) and use only the cached tarball at ``~/.repowise/web``.
-
- ``host`` is the API's bind address, and the UI takes the same one. The UI
- rewrites ``/api/*`` to the API on loopback (packages/web/src/middleware.ts),
- so a UI on the wildcard while the API is loopback-only handed the whole API
- to the network through the proxy, with every request looking local.
- """
- env = {
- **os.environ,
- "REPOWISE_API_URL": f"http://localhost:{backend_port}",
- "HOSTNAME": host,
- "PORT": str(frontend_port),
- }
-
- # Option 1: Local repo build (preferred — uses latest source)
- if local_web:
- standalone_dir = local_web / ".next" / "standalone"
- server_js = standalone_dir / "packages" / "web" / "server.js"
- if server_js.exists():
- # Copy static files into standalone (Next.js requirement)
- static_src = local_web / ".next" / "static"
- static_dst = standalone_dir / "packages" / "web" / ".next" / "static"
- if static_src.exists() and not static_dst.exists():
- shutil.copytree(str(static_src), str(static_dst))
- public_src = local_web / "public"
- public_dst = standalone_dir / "packages" / "web" / "public"
- if public_src.exists() and not public_dst.exists():
- shutil.copytree(str(public_src), str(public_dst))
-
- return subprocess.Popen(
- [node, str(server_js)],
- cwd=str(standalone_dir / "packages" / "web"),
- env=env,
- )
-
- # Option 2: Cached download (fallback for pip-installed users)
- cached_server = _WEB_CACHE_DIR / "server.js"
- if cached_server.exists():
- return subprocess.Popen(
- [node, str(cached_server)],
- cwd=str(_WEB_CACHE_DIR),
- env=env,
- )
-
- return None
-
-
[email protected]("--port", default=7337, type=int, help="API server port.", envvar="REPOWISE_PORT")
[email protected]("--host", default="127.0.0.1", help="Host to bind to.")
[email protected]("--workers", default=1, type=int, help="Number of uvicorn workers.")
[email protected]("--ui-port", default=3000, type=int, help="Web UI port.")
[email protected]("--no-ui", is_flag=True, help="Start API server only, skip the web UI.")
- "--refresh-ui",
- is_flag=True,
- help="Force re-download of the web UI tarball, ignoring any cache.",
-)
-def serve_command(
- port: int, host: str, workers: int, ui_port: int, no_ui: bool, refresh_ui: bool
-) -> None:
- """Start the repowise server with the web UI.
-
- Starts the API backend and automatically launches the web frontend.
- The web UI is downloaded and cached on first run (~50 MB, one-time).
-
- Use --no-ui to start only the API server.
- """
- try:
- import uvicorn
- except ImportError:
- 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 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:
- 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
- # runs before _setup_embedder so a configured embedder/key is detected
- # instead of re-prompting, and so the in-process API server starts with a
- # working provider (otherwise chat fails even though `init` saved a key).
- # Existing env vars always take precedence.
- _load_local_provider_config()
-
- _setup_embedder()
-
- # Auto-detect local .repowise/ directory if REPOWISE_DB_URL is not set.
- # repowise init writes to <repo>/.repowise/wiki.db, so honour it when
- # the user runs `repowise serve` from the same directory.
- #
- # Skip this when cwd is inside a workspace (has an upstream
- # .repowise-workspace.yaml). Setting REPOWISE_DB_URL here is read back
- # by the workspace-detection code in app.py as "the user explicitly
- # configured one shared database for the whole workspace" (the real,
- # separate shared-DB/Postgres feature), which then routes every repo
- # lookup through the workspace root's own near-empty coordinator
- # wiki.db instead of each repo's own <repo>/.repowise/wiki.db. Every
- # repo in the workspace then reports needs_index with zeroed stats,
- # and the UI can't open any of them even though each repo's own index
- # is complete and correct on disk.
- from repowise.core.workspace.config import find_workspace_root
-
- if not os.environ.get("REPOWISE_DB_URL") and find_workspace_root() is None:
- local_repowise = Path.cwd() / ".repowise"
- if local_repowise.exists():
- local_db = local_repowise / "wiki.db"
- os.environ["REPOWISE_DB_URL"] = f"sqlite+aiosqlite:///{local_db.as_posix()}"
- console.print(f"[dim]Using local database: {local_db}[/dim]")
-
- # The server reads REPOWISE_HOST to describe its own bind. Nothing used to
- # set it from --host, so `serve --host 0.0.0.0` left the auth layer
- # believing it was loopback-only. Set before the app is imported (uvicorn
- # imports the factory below, and workers inherit the environment).
- os.environ["REPOWISE_HOST"] = host
- if not os.environ.get("REPOWISE_API_KEY") and host not in ("127.0.0.1", "localhost", "::1"):
- console.print(
- f"[yellow]Binding to {host} without REPOWISE_API_KEY: non-local requests "
- f"will be refused.[/yellow]\n"
- "[dim]Set REPOWISE_API_KEY to allow them, or bind to 127.0.0.1.[/dim]"
- )
-
- # Resolve a usable API port up front — uvicorn would otherwise crash later
- # with a bare OSError, and the chosen port needs to flow into the frontend
- # via REPOWISE_API_URL.
- port = _find_free_port(host, port, "API server")
-
- frontend_proc: subprocess.Popen | None = None
-
- if not no_ui:
- # The Next.js server takes the same bind as the API (see HOSTNAME
- # below), so probe there.
- ui_port = _find_free_port(host, ui_port, "web UI")
-
- node = _node_available()
- npm = _npm_available()
-
- # Reject Node versions older than what the bundled Next.js needs.
- # Without this check, an old node silently produces cryptic syntax
- # errors from inside the Next.js runtime (e.g. `Unexpected token '?'`
- # on `??`) once the frontend tries to start — see issue #276.
- node_major = _node_major_version(node) if node else None
- node_too_old = node is not None and node_major is not None and node_major < _NODE_MIN_MAJOR
-
- if not node:
- console.print(
- f"[yellow]Node.js not found — starting API server only.[/yellow]\n"
- f"[dim]To get the web UI, install Node.js {_NODE_MIN_MAJOR}+ or use Docker:\n"
- f" docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"
- )
- elif node_too_old:
- console.print(
- f"[yellow]Node.js {node_major} is too old for the bundled web UI "
- f"(requires {_NODE_MIN_MAJOR}+) — starting API server only.[/yellow]\n"
- f"[dim]Upgrade Node.js to {_NODE_MIN_MAJOR}+ or use Docker:\n"
- f" docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"
- )
- else:
- # Try to get the frontend running
- ready = False
- local_web: Path | None = None if refresh_ui else _find_local_web()
-
- # Option 1: Local repo build (preferred — uses latest source).
- # Only honoured when the bundle isn't behind the source tree.
- if local_web:
- if _local_build_is_stale(local_web):
- if npm:
- console.print(
- "[dim]Local web bundle is older than source — rebuilding...[/dim]"
- )
- ready = _build_local_web(local_web, npm)
- if not ready:
- console.print(
- "[yellow]Local rebuild failed — falling back to "
- "released tarball.[/yellow]"
- )
- local_web = None
- else:
- console.print(
- "[yellow]Local web bundle is stale and npm not found — "
- "falling back to released tarball.[/yellow]"
- )
- local_web = None
- else:
- ready = True
-
- # Option 2: Cached download (skip when --refresh-ui is set).
- if not ready and not refresh_ui and _web_is_cached(__version__):
- ready = True
-
- # Option 3: Download from GitHub releases.
- if not ready:
- ready = _download_web(__version__)
-
- if ready:
- frontend_proc = _start_frontend(
- node, port, ui_port, local_web=local_web, host=host
- )
- if frontend_proc:
- console.print(f"[green]Web UI starting on http://localhost:{ui_port}[/green]")
- else:
- console.print("[yellow]Could not start web UI — running API only.[/yellow]")
- else:
- console.print(
- "[yellow]Web UI not available — starting API server only.[/yellow]\n"
- "[dim]The web UI will be available in a future release.\n"
- "For now, use Docker for the full experience:[/dim]\n"
- f"[dim] docker build -t repowise https://github.com/{_GITHUB_REPO}.git\n"
- " docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"
- )
-
- console.print(f"[green]API server starting on http://{host}:{port}[/green]")
-
- lock_path = _serve_lock_path()
- if lock_path:
- _write_serve_lock(
- lock_path,
- host=host,
- port=port,
- ui_port=None if (no_ui or frontend_proc is None) else ui_port,
- )
-
- try:
- uvicorn.run(
- "repowise.server.app:create_app",
- factory=True,
- host=host,
- port=port,
- workers=workers,
- log_level="info",
- )
- finally:
- if lock_path:
- _remove_serve_lock(lock_path)
- if frontend_proc:
- frontend_proc.terminate()
- frontend_proc.wait(timeout=5)
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/serve_cmd/__init__.py
new file mode 100644
index 000000000..461e68f87
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/__init__.py
@@ -0,0 +1,82 @@
+"""``repowise serve`` command package.
+
+* :mod:`.command`: the Click command
+* :mod:`._advisory`: periodic update advisory
+* :mod:`._lock`: discovery lockfile
+* :mod:`._embedder`: embedder and provider env setup
+* :mod:`._ports`: port probing
+* :mod:`._web_assets`: node/npm detection and web bundle resolution
+* :mod:`._frontend`: launching the web UI
+
+Every name is re-exported so ``repowise.cli.commands.serve_cmd`` keeps its
+import surface. Patch a name on the submodule that defines it: a patch here
+does not reach lookups inside the submodules.
+"""
+
+from __future__ import annotations
+
+from ._advisory import (
+ _UPDATE_ADVISORY_INTERVAL_S,
+ _start_update_advisory_loop,
+ _update_advisory_tick,
+)
+from ._embedder import (
+ _GLOBAL_CONFIG_DIR,
+ _get_or_prompt_api_key,
+ _load_local_provider_config,
+ _save_global_embedder,
+ _set_api_key_env,
+ _setup_embedder,
+)
+from ._frontend import _start_frontend
+from ._lock import _SERVE_LOCK_NAME, _remove_serve_lock, _serve_lock_path, _write_serve_lock
+from ._ports import _find_free_port, _is_port_free
+from ._web_assets import (
+ _GITHUB_REPO,
+ _MARKER_FILE,
+ _NODE_MIN_MAJOR,
+ _WEB_CACHE_DIR,
+ _build_local_web,
+ _download_web,
+ _find_local_web,
+ _local_build_is_stale,
+ _node_available,
+ _node_major_version,
+ _npm_available,
+ _safe_extract_tar,
+ _web_is_cached,
+)
+from .command import serve_command
+
+__all__ = [
+ "_GITHUB_REPO",
+ "_GLOBAL_CONFIG_DIR",
+ "_MARKER_FILE",
+ "_NODE_MIN_MAJOR",
+ "_SERVE_LOCK_NAME",
+ "_UPDATE_ADVISORY_INTERVAL_S",
+ "_WEB_CACHE_DIR",
+ "_build_local_web",
+ "_download_web",
+ "_find_free_port",
+ "_find_local_web",
+ "_get_or_prompt_api_key",
+ "_is_port_free",
+ "_load_local_provider_config",
+ "_local_build_is_stale",
+ "_node_available",
+ "_node_major_version",
+ "_npm_available",
+ "_remove_serve_lock",
+ "_safe_extract_tar",
+ "_save_global_embedder",
+ "_serve_lock_path",
+ "_set_api_key_env",
+ "_setup_embedder",
+ "_start_frontend",
+ "_start_update_advisory_loop",
+ "_update_advisory_tick",
+ "_web_is_cached",
+ "_write_serve_lock",
+ "serve_command",
+]
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_advisory.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_advisory.py
new file mode 100644
index 000000000..9686dfb3a
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_advisory.py
@@ -0,0 +1,48 @@
+"""Periodic "newer release available" advisory while ``serve`` runs."""
+
+from __future__ import annotations
+
+from repowise.cli.helpers import console
+
+#: 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 _start_update_advisory() -> None:
+ """Announce now, then once per interval; interactive terminals only."""
+ if not console.is_terminal:
+ return
+ announced: set[str] = set()
+ _update_advisory_tick(announced)
+ _start_update_advisory_loop(announced)
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_embedder.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_embedder.py
new file mode 100644
index 000000000..3c00a14ea
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_embedder.py
@@ -0,0 +1,167 @@
+"""Embedder and provider env setup before the in-process API server starts."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import click
+
+from repowise.cli.helpers import console, load_config
+
+_GLOBAL_CONFIG_DIR = Path.home() / ".repowise"
+
+
+#: Embedders offered at the prompt, in menu order, with the env vars that
+#: carry their key. The first var is the one prompted for and set.
+_EMBEDDER_KEY_VARS: dict[str, tuple[str, ...]] = {
+ "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY"),
+ "openai": ("OPENAI_API_KEY",),
+ "openrouter": ("OPENROUTER_API_KEY",),
+}
+
+
+def _setup_embedder() -> None:
+ """Ensure REPOWISE_EMBEDDER is set before the server starts.
+
+ Priority:
+ 1. Already set in environment → nothing to do.
+ 2. Saved in ~/.repowise/config.yaml → restore it (and its API key).
+ 3. Prompt the user interactively → save choice for next time.
+ """
+ if os.environ.get("REPOWISE_EMBEDDER") or _restore_saved_embedder():
+ return
+
+ choice = _prompt_embedder_choice()
+ if choice == "skip":
+ console.print("[dim]Skipping embedder — chat and search will be unavailable.[/dim]\n")
+ return
+
+ os.environ["REPOWISE_EMBEDDER"] = choice
+ api_key = _get_or_prompt_api_key(choice)
+ _set_api_key_env(choice, api_key)
+ # Save choice (and key) to ~/.repowise/config.yaml for future runs.
+ _save_global_embedder(choice, api_key)
+ console.print()
+
+
+def _restore_saved_embedder() -> bool:
+ """Restore the embedder (and key) a previous serve/init saved globally."""
+ cfg = load_config(Path.home())
+ saved_embedder = cfg.get("embedder", "")
+ if not saved_embedder or saved_embedder == "mock":
+ return False
+ os.environ["REPOWISE_EMBEDDER"] = saved_embedder
+ if cfg.get("embedder_api_key"):
+ _set_api_key_env(saved_embedder, cfg["embedder_api_key"])
+ return True
+
+
+def _exported_key(embedder: str) -> str:
+ """The first non-empty exported key for *embedder*, or ``""``."""
+ names = _EMBEDDER_KEY_VARS.get(embedder, ())
+ return next((os.environ[n] for n in names if os.environ.get(n)), "")
+
+
+def _prompt_embedder_choice() -> str:
+ """Show the embedder menu and return the chosen name, or ``"skip"``."""
+ console.print(
+ "\n[bold]Chat & search require an embedder.[/bold] "
+ "Choose one or skip (other features still work).\n"
+ )
+ options = [*_EMBEDDER_KEY_VARS, "skip"]
+ for number, (name, key_vars) in enumerate(_EMBEDDER_KEY_VARS.items(), start=1):
+ status = (
+ "[green]✓ key set[/green]"
+ if _exported_key(name)
+ else f"[dim]needs {' / '.join(key_vars)}[/dim]"
+ )
+ console.print(f" [{number}] {name:<12}{status}")
+ console.print(f" [{len(options)}] skip [dim]no chat/search[/dim]")
+ console.print()
+
+ default = "1" if (_exported_key("gemini") or _exported_key("openai")) else "3"
+ raw = click.prompt(" Select", default=default).strip()
+ if raw in options:
+ return raw
+ if raw.isdigit() and 1 <= int(raw) <= len(options):
+ return options[int(raw) - 1]
+ return "skip"
+
+
+def _get_or_prompt_api_key(embedder: str) -> str:
+ """Return existing API key for *embedder* or prompt the user for one."""
+ key_vars = _EMBEDDER_KEY_VARS.get(embedder)
+ if not key_vars:
+ return ""
+ return (
+ _exported_key(embedder)
+ or click.prompt(f" {key_vars[0]}", default="", show_default=False).strip()
+ )
+
+
+def _set_api_key_env(embedder: str, key: str) -> None:
+ key_vars = _EMBEDDER_KEY_VARS.get(embedder)
+ if key and key_vars:
+ os.environ.setdefault(key_vars[0], key)
+
+
+def _save_global_embedder(embedder: str, api_key: str) -> None:
+ """Persist embedder choice to ~/.repowise/config.yaml."""
+ _GLOBAL_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
+ config_path = _GLOBAL_CONFIG_DIR / "config.yaml"
+ try:
+ existing: dict = {}
+ if config_path.exists():
+ import yaml # type: ignore[import-untyped]
+
+ existing = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
+ existing["embedder"] = embedder
+ if api_key:
+ existing["embedder_api_key"] = api_key
+ import yaml # type: ignore[import-untyped]
+
+ config_path.write_text(
+ yaml.dump(existing, default_flow_style=False, sort_keys=False),
+ encoding="utf-8",
+ )
+ except Exception:
+ pass # Non-fatal — user just gets prompted again next time.
+
+
+def _load_local_provider_config() -> None:
+ """Load ``.repowise/.env`` and seed the embedder from ``config.yaml``.
+
+ The API server runs in-process here and builds one process-wide embedder
+ at startup from env vars, so those are set now. ``load_dotenv`` never
+ overwrites an existing var, and the embedder vars are only set when unset,
+ so explicit environment configuration always wins. The chat provider
+ needs no seeding: it is resolved per repo from that repo's own files.
+ """
+ from repowise.cli.helpers import load_config
+ from repowise.cli.ui import load_dotenv
+
+ cwd = Path.cwd()
+ if not (cwd / ".repowise").exists():
+ return
+
+ # 1) API keys (OPENAI_API_KEY, ANTHROPIC_API_KEY, …) from .repowise/.env
+ load_dotenv(cwd)
+ cfg = load_config(cwd)
+
+ # 2) Embedder from config so chat/search work without an interactive prompt.
+ # Including "mock": that pin is not a preference to be talked out of, it is
+ # the width the table on disk was written at. Skipping it sent a keyless
+ # repo down _setup_embedder's detection path, which picks up any exported
+ # API key and queries an 8-wide table with 1536-wide vectors — search
+ # returns nothing, and nothing says why.
+ embedder = cfg.get("embedder")
+ if embedder and not os.environ.get("REPOWISE_EMBEDDER"):
+ os.environ["REPOWISE_EMBEDDER"] = str(embedder)
+
+ # 3) Embedding model from config — without this the server rebuilds the
+ # embedder with a provider default (e.g. text-embedding-3-small) that
+ # mismatches the indexed vectors, degrading chat/search retrieval (#426).
+ embedding_model = cfg.get("embedding_model")
+ if embedding_model and not os.environ.get("REPOWISE_EMBEDDING_MODEL"):
+ os.environ["REPOWISE_EMBEDDING_MODEL"] = str(embedding_model)
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_frontend.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_frontend.py
new file mode 100644
index 000000000..7a088fc7f
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_frontend.py
@@ -0,0 +1,159 @@
+"""Launching the Next.js web UI next to the API server."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+from pathlib import Path
+
+from repowise.cli import __version__
+from repowise.cli.helpers import console
+
+from . import _web_assets
+
+_DOCKER_RUN = " docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"
+
+
+def _node_is_usable(node: str | None) -> bool:
+ """Reject a missing node, or one older than the bundled Next.js needs.
+
+ An old node otherwise fails inside the Next.js runtime with cryptic syntax
+ errors (e.g. ``Unexpected token '?'`` on ``??``), see issue #276. An
+ unreadable version is treated as usable.
+ """
+ min_major = _web_assets._NODE_MIN_MAJOR
+ if not node:
+ console.print(
+ f"[yellow]Node.js not found — starting API server only.[/yellow]\n"
+ f"[dim]To get the web UI, install Node.js {min_major}+ or use Docker:\n"
+ f"{_DOCKER_RUN}"
+ )
+ return False
+ node_major = _web_assets._node_major_version(node)
+ if node_major is None or node_major >= min_major:
+ return True
+ console.print(
+ f"[yellow]Node.js {node_major} is too old for the bundled web UI "
+ f"(requires {min_major}+) — starting API server only.[/yellow]\n"
+ f"[dim]Upgrade Node.js to {min_major}+ or use Docker:\n"
+ f"{_DOCKER_RUN}"
+ )
+ return False
+
+
+def _rebuild_stale_local_web(local_web: Path) -> bool:
+ """Rebuild a local bundle that is behind its source; False means fall back."""
+ npm = _web_assets._npm_available()
+ if not npm:
+ console.print(
+ "[yellow]Local web bundle is stale and npm not found — "
+ "falling back to released tarball.[/yellow]"
+ )
+ return False
+ console.print("[dim]Local web bundle is older than source — rebuilding...[/dim]")
+ if _web_assets._build_local_web(local_web, npm):
+ return True
+ console.print("[yellow]Local rebuild failed — falling back to released tarball.[/yellow]")
+ return False
+
+
+def _resolve_web_bundle(refresh_ui: bool) -> tuple[bool, Path | None]:
+ """Return (ready, local_web): a fresh local build, else the cache, else a download.
+
+ ``--refresh-ui`` skips both the local build and the cache.
+ """
+ local_web = None if refresh_ui else _web_assets._find_local_web()
+ if local_web and (
+ not _web_assets._local_build_is_stale(local_web) or _rebuild_stale_local_web(local_web)
+ ):
+ return True, local_web
+ if not refresh_ui and _web_assets._web_is_cached(__version__):
+ return True, None
+ return _web_assets._download_web(__version__), None
+
+
+def _launch_web_ui(
+ host: str, api_port: int, ui_port: int, *, refresh_ui: bool
+) -> subprocess.Popen | None:
+ """Start the web UI when node and a bundle are available; None runs API only."""
+ node = _web_assets._node_available()
+ if not _node_is_usable(node):
+ return None
+
+ ready, local_web = _resolve_web_bundle(refresh_ui)
+ if not ready:
+ console.print(
+ "[yellow]Web UI not available — starting API server only.[/yellow]\n"
+ "[dim]The web UI will be available in a future release.\n"
+ "For now, use Docker for the full experience:[/dim]\n"
+ f"[dim] docker build -t repowise https://github.com/{_web_assets._GITHUB_REPO}.git\n"
+ " docker run -p 7337:7337 -p 3000:3000 -v .repowise:/data repowise[/dim]"
+ )
+ return None
+
+ proc = _start_frontend(node, api_port, ui_port, local_web=local_web, host=host)
+ if proc:
+ console.print(f"[green]Web UI starting on http://localhost:{ui_port}[/green]")
+ else:
+ console.print("[yellow]Could not start web UI — running API only.[/yellow]")
+ return proc
+
+
+def _start_frontend(
+ node: str,
+ backend_port: int,
+ frontend_port: int,
+ local_web: Path | None = None,
+ host: str = "127.0.0.1",
+) -> subprocess.Popen | None:
+ """Start the Next.js frontend server. Returns the process or None.
+
+ If ``local_web`` is provided, the local monorepo build is used as Option 1.
+ Pass ``None`` to skip the local build (e.g. when it's stale or refresh was
+ forced) and use only the cached tarball at ``~/.repowise/web``.
+
+ ``host`` is the API's bind address, and the UI takes the same one. The UI
+ rewrites ``/api/*`` to the API on loopback (packages/web/src/middleware.ts),
+ so a UI on the wildcard while the API is loopback-only handed the whole API
+ to the network through the proxy, with every request looking local.
+ """
+ env = {
+ **os.environ,
+ "REPOWISE_API_URL": f"http://localhost:{backend_port}",
+ "HOSTNAME": host,
+ "PORT": str(frontend_port),
+ }
+
+ # Option 1: Local repo build (preferred — uses latest source)
+ if local_web:
+ standalone_dir = local_web / ".next" / "standalone"
+ server_js = standalone_dir / "packages" / "web" / "server.js"
+ if server_js.exists():
+ # Copy static files into standalone (Next.js requirement)
+ static_src = local_web / ".next" / "static"
+ static_dst = standalone_dir / "packages" / "web" / ".next" / "static"
+ if static_src.exists() and not static_dst.exists():
+ shutil.copytree(str(static_src), str(static_dst))
+ public_src = local_web / "public"
+ public_dst = standalone_dir / "packages" / "web" / "public"
+ if public_src.exists() and not public_dst.exists():
+ shutil.copytree(str(public_src), str(public_dst))
+
+ return subprocess.Popen(
+ [node, str(server_js)],
+ cwd=str(standalone_dir / "packages" / "web"),
+ env=env,
+ )
+
+ # Option 2: Cached download (fallback for pip-installed users)
+ cache_dir = _web_assets._WEB_CACHE_DIR
+ cached_server = cache_dir / "server.js"
+ if cached_server.exists():
+ return subprocess.Popen(
+ [node, str(cached_server)],
+ cwd=str(cache_dir),
+ env=env,
+ )
+
+ return None
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_lock.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_lock.py
new file mode 100644
index 000000000..c12938099
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_lock.py
@@ -0,0 +1,61 @@
+"""Discovery lockfile for a running ``serve`` (port, pid)."""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+from datetime import UTC, datetime
+from pathlib import Path
+
+from repowise.cli import __version__
+
+_SERVE_LOCK_NAME = "serve.lock.json"
+
+
+def _serve_lock_path(cwd: Path | None = None) -> Path | None:
+ """Return where the serve lockfile belongs for this directory, if anywhere.
+
+ The lockfile lets other local tooling discover a running server (port,
+ pid) without port-scanning. It lives next to the index the server is
+ serving: ``.repowise/`` for a single repo, ``.repowise-workspace/`` for a
+ workspace root. Returns None when neither exists (nothing to serve).
+ """
+ base = cwd or Path.cwd()
+ for dirname in (".repowise", ".repowise-workspace"):
+ candidate = base / dirname
+ if candidate.is_dir():
+ return candidate / _SERVE_LOCK_NAME
+ return None
+
+
+def _write_serve_lock(lock_path: Path, *, host: str, port: int, ui_port: int | None) -> None:
+ """Best-effort write of the discovery lockfile. Never blocks startup.
+
+ Consumers must treat ``pid`` as the liveness check: a killed server
+ cannot clean up after itself, so a stale file with a dead pid means
+ "not running".
+ """
+ # A wildcard bind isn't a connectable URL; loopback always is.
+ url_host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
+ payload = {
+ "pid": os.getpid(),
+ "host": host,
+ "port": port,
+ "url": f"http://{url_host}:{port}",
+ "ui_port": ui_port,
+ "server_version": __version__,
+ "started_at": datetime.now(UTC).isoformat(),
+ }
+ with contextlib.suppress(OSError):
+ lock_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+
+
+def _remove_serve_lock(lock_path: Path) -> None:
+ """Best-effort removal; only removes a lock owned by this process."""
+ try:
+ data = json.loads(lock_path.read_text(encoding="utf-8"))
+ if data.get("pid") == os.getpid():
+ lock_path.unlink()
+ except (OSError, ValueError):
+ pass
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_ports.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_ports.py
new file mode 100644
index 000000000..2e255face
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_ports.py
@@ -0,0 +1,49 @@
+"""Port probing for the API and web UI binds."""
+
+from __future__ import annotations
+
+import os
+import socket
+
+from repowise.cli.helpers import console
+
+
+def _is_port_free(host: str, port: int) -> bool:
+ """Return True if *port* can be bound on *host* right now."""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ if os.name != "nt":
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ sock.bind((host, port))
+ except OSError:
+ return False
+ return True
+
+
+def _find_free_port(host: str, preferred: int, label: str, max_attempts: int = 20) -> int:
+ """Return *preferred* if free, otherwise the next free port within range.
+
+ Falls back to an OS-assigned port if a contiguous slot can't be found.
+ Prints a notice when the preferred port is unavailable so the user knows
+ the bind moved.
+ """
+ if _is_port_free(host, preferred):
+ return preferred
+
+ for offset in range(1, max_attempts + 1):
+ candidate = preferred + offset
+ if candidate > 65535:
+ break
+ if _is_port_free(host, candidate):
+ console.print(
+ f"[yellow]Port {preferred} for {label} is in use — using {candidate} instead.[/yellow]"
+ )
+ return candidate
+
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind((host, 0))
+ candidate = sock.getsockname()[1]
+ console.print(
+ f"[yellow]Port {preferred} for {label} and nearby ports busy — using {candidate}.[/yellow]"
+ )
+ return candidate
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/_web_assets.py b/packages/cli/src/repowise/cli/commands/serve_cmd/_web_assets.py
new file mode 100644
index 000000000..cbf20d76e
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/_web_assets.py
@@ -0,0 +1,251 @@
+"""Node/npm detection and web UI bundle resolution (cache, download, local build)."""
+
+from __future__ import annotations
+
+import os
+import posixpath
+import shutil
+import subprocess
+import tarfile
+import tempfile
+from pathlib import Path, PurePosixPath, PureWindowsPath
+
+from repowise.cli.helpers import console
+
+_GITHUB_REPO = "repowise-dev/repowise"
+_WEB_CACHE_DIR = Path.home() / ".repowise" / "web"
+_MARKER_FILE = _WEB_CACHE_DIR / ".version"
+
+
+_NODE_MIN_MAJOR = 20 # Next.js 15 (see packages/web/package.json engines.node)
+
+
+def _node_available() -> str | None:
+ """Return the path to node binary, or None."""
+ return shutil.which("node")
+
+
+def _node_major_version(node: str) -> int | None:
+ """Return the major version of the *node* binary, or None if it can't be read.
+
+ A failure to invoke or parse is treated as "unknown" rather than fatal — the
+ caller decides whether to proceed or fall back.
+ """
+ try:
+ result = subprocess.run(
+ [node, "--version"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=True,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+ raw = result.stdout.strip().lstrip("v")
+ head = raw.split(".", 1)[0]
+ try:
+ return int(head)
+ except ValueError:
+ return None
+
+
+def _npm_available() -> str | None:
+ """Return the path to npm binary, or None."""
+ return shutil.which("npm")
+
+
+def _web_is_cached(version: str) -> bool:
+ """Check if the web frontend is cached and matches the current version."""
+ server_js = _WEB_CACHE_DIR / "server.js"
+ if not server_js.exists():
+ return False
+ return _MARKER_FILE.exists() and _MARKER_FILE.read_text().strip() == version
+
+
+def _find_local_web() -> Path | None:
+ """Check if running from the repo with packages/web available."""
+ # Check from both __file__ (source installs) and cwd (pip-installed runs)
+ roots = [Path(__file__).resolve(), Path.cwd().resolve()]
+ for start in roots:
+ candidate = start
+ for _ in range(10):
+ candidate = candidate.parent
+ pkg_web = candidate / "packages" / "web"
+ if (pkg_web / "package.json").exists():
+ # Next.js standalone in monorepos nests server under package path
+ standalone = pkg_web / ".next" / "standalone" / "packages" / "web" / "server.js"
+ if standalone.exists():
+ return pkg_web
+ return pkg_web # exists but may need build
+ return None
+
+
+def _local_build_is_stale(web_dir: Path) -> bool:
+ """True if the local .next/standalone bundle is older than any input source.
+
+ Compares the standalone server.js mtime against the newest mtime under the
+ source roots that get compiled into the bundle (web/ui/types packages plus
+ web's config files). Skips node_modules / .next / .turbo. Used so that a
+ cloned monorepo with stale build artifacts falls back to the released
+ tarball instead of serving a bundle behind the user's source tree.
+ """
+ standalone = web_dir / ".next" / "standalone" / "packages" / "web" / "server.js"
+ if not standalone.exists():
+ return True
+ build_mtime = standalone.stat().st_mtime
+
+ repo_root = web_dir.parent.parent # packages/web → repo root
+ skip_dirs = {"node_modules", ".next", ".turbo", "dist", ".git"}
+
+ file_inputs: list[Path] = [
+ web_dir / "package.json",
+ web_dir / "next.config.ts",
+ web_dir / "next.config.js",
+ web_dir / "tsconfig.json",
+ ]
+ dir_inputs: list[Path] = [
+ web_dir / "src",
+ web_dir / "app",
+ web_dir / "components",
+ web_dir / "lib",
+ web_dir / "public",
+ repo_root / "packages" / "ui" / "src",
+ repo_root / "packages" / "types" / "src",
+ ]
+
+ for f in file_inputs:
+ if f.exists() and f.is_file() and f.stat().st_mtime > build_mtime:
+ return True
+
+ for root in dir_inputs:
+ if not root.exists():
+ continue
+ for path in root.rglob("*"):
+ if any(part in skip_dirs for part in path.parts):
+ continue
+ try:
+ if path.is_file() and path.stat().st_mtime > build_mtime:
+ return True
+ except OSError:
+ continue
+ return False
+
+
+def _safe_extract_tar(archive: Path, dest: Path) -> None:
+ """Extract a .tar.gz into ``dest``, refusing any member that would land outside it."""
+ root = dest.resolve()
+
+ def _inside(target: Path) -> bool:
+ return target == root or target.is_relative_to(root)
+
+ def _check_name(raw: str, member: str, what: str) -> str:
+ name = raw.replace("\\", "/")
+ # A colon covers drive-relative names (C:x) and NTFS alternate data streams.
+ if (
+ name.startswith("/")
+ or Path(name).is_absolute()
+ or PureWindowsPath(name).drive
+ or ":" in name
+ ):
+ raise ValueError(f"archive {what} is absolute or drive-qualified: {member}")
+ return name
+
+ with tarfile.open(archive, "r:gz") as tar:
+ members = tar.getmembers()
+ symlinks = {posixpath.normpath(m.name.replace("\\", "/")) for m in members if m.issym()}
+ for m in members:
+ name = _check_name(m.name, m.name, "member path")
+ target = (root / name).resolve()
+ if not _inside(target):
+ raise ValueError(f"archive member escapes the destination: {m.name}")
+ # Static resolution cannot follow links the archive itself creates, so no
+ # path may pass through one (blocks chains like a -> . then a/b -> ..).
+ parts = PurePosixPath(posixpath.normpath(name)).parts
+ if any("/".join(parts[:i]) in symlinks for i in range(1, len(parts))):
+ raise ValueError(f"archive member passes through a link: {m.name}")
+ if m.issym() or m.islnk():
+ link = _check_name(m.linkname, m.name, "link target")
+ # Symlinks resolve from the member's directory, hardlinks from the root.
+ base = target.parent if m.issym() else root
+ if not _inside((base / link).resolve()):
+ raise ValueError(f"archive link escapes the destination: {m.name}")
+ if m.islnk():
+ lparts = PurePosixPath(posixpath.normpath(link)).parts
+ if any("/".join(lparts[:i]) in symlinks for i in range(1, len(lparts) + 1)):
+ raise ValueError(f"archive link passes through a link: {m.name}")
+ elif not (m.isfile() or m.isdir()):
+ raise ValueError(f"archive member is not a file or directory: {m.name}")
+ # The stdlib data filter (3.11.4+) re-checks the same rules at write time.
+ if hasattr(tarfile, "data_filter"):
+ tar.extractall(root, members=members, filter="data")
+ else:
+ tar.extractall(root, members=members)
+
+
+def _download_web(version: str) -> bool:
+ """Download pre-built web frontend from GitHub releases."""
+ import httpx
+
+ tag = f"v{version}"
+ url = f"https://github.com/{_GITHUB_REPO}/releases/download/{tag}/repowise-web.tar.gz"
+
+ console.print(f"[dim]Downloading web UI ({url})...[/dim]")
+ try:
+ tmp_path = None
+ with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as tmp:
+ tmp_path = tmp.name
+ with httpx.stream("GET", url, follow_redirects=True, timeout=120) as resp:
+ resp.raise_for_status()
+ for chunk in resp.iter_bytes(chunk_size=65536):
+ tmp.write(chunk)
+ except (httpx.HTTPStatusError, httpx.RequestError) as exc:
+ console.print(f"[yellow]Could not download web UI: {exc}[/yellow]")
+ if tmp_path:
+ os.unlink(tmp_path)
+ return False
+
+ try:
+ _WEB_CACHE_DIR.mkdir(parents=True, exist_ok=True)
+ # Clean old cache
+ for item in _WEB_CACHE_DIR.iterdir():
+ if item.is_dir():
+ shutil.rmtree(item)
+ else:
+ item.unlink()
+
+ _safe_extract_tar(Path(tmp_path), _WEB_CACHE_DIR)
+
+ _MARKER_FILE.write_text(version)
+ console.print("[green]Web UI downloaded and cached.[/green]")
+ return True
+ except Exception as exc:
+ console.print(f"[yellow]Failed to extract web UI: {exc}[/yellow]")
+ return False
+ finally:
+ os.unlink(tmp_path)
+
+
+def _build_local_web(web_dir: Path, npm: str) -> bool:
+ """Build the Next.js frontend from source."""
+ console.print("[dim]Building web UI (first time only)...[/dim]")
+ try:
+ # Install deps if needed
+ if not (web_dir / "node_modules").exists():
+ subprocess.run(
+ [npm, "install"],
+ cwd=str(web_dir),
+ check=True,
+ capture_output=True,
+ )
+ # Build
+ subprocess.run(
+ [npm, "run", "build"],
+ cwd=str(web_dir),
+ check=True,
+ capture_output=True,
+ )
+ return True
+ except subprocess.CalledProcessError as exc:
+ console.print(f"[yellow]Web UI build failed: {exc}[/yellow]")
+ return False
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd/command.py b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
new file mode 100644
index 000000000..6791165cd
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd/command.py
@@ -0,0 +1,145 @@
+"""The ``repowise serve`` Click command."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from pathlib import Path
+from types import ModuleType
+
+import click
+
+from repowise.cli.helpers import console
+
+from . import _advisory, _embedder, _frontend, _lock, _ports
+
+_LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")
+
+
+def _import_uvicorn() -> ModuleType:
+ try:
+ import uvicorn
+ except ImportError:
+ console.print("[red]uvicorn is not installed. Install it with: pip install repowise[/red]")
+ raise SystemExit(1) from None
+ return uvicorn
+
+
+def _resolve_db_url() -> None:
+ """Point ``REPOWISE_DB_URL`` at ``./.repowise/wiki.db`` when nothing set it.
+
+ Skipped inside a workspace: app.py reads a set ``REPOWISE_DB_URL`` there as
+ "one shared database for the whole workspace" and routes every repo through
+ the root's near-empty coordinator wiki.db, so every repo reports
+ needs_index although each one's own index is complete on disk.
+ """
+ from repowise.core.workspace.config import find_workspace_root
+
+ if os.environ.get("REPOWISE_DB_URL") or find_workspace_root() is not None:
+ return
+ local_repowise = Path.cwd() / ".repowise"
+ if not local_repowise.exists():
+ return
+ local_db = local_repowise / "wiki.db"
+ os.environ["REPOWISE_DB_URL"] = f"sqlite+aiosqlite:///{local_db.as_posix()}"
+ console.print(f"[dim]Using local database: {local_db}[/dim]")
+
+
+def _configure_host_env(host: str) -> None:
+ """Publish the bind as ``REPOWISE_HOST`` and warn on a keyless wide bind.
+
+ The auth layer reads ``REPOWISE_HOST`` to describe its own bind, so it is
+ set before uvicorn imports the app factory (workers inherit it).
+ """
+ os.environ["REPOWISE_HOST"] = host
+ if os.environ.get("REPOWISE_API_KEY") or host in _LOOPBACK_HOSTS:
+ return
+ console.print(
+ f"[yellow]Binding to {host} without REPOWISE_API_KEY: non-local requests "
+ f"will be refused.[/yellow]\n"
+ "[dim]Set REPOWISE_API_KEY to allow them, or bind to 127.0.0.1.[/dim]"
+ )
+
+
+def _run_api(
+ uvicorn: ModuleType,
+ *,
+ host: str,
+ port: int,
+ workers: int,
+ ui_port: int | None,
+ frontend_proc: subprocess.Popen | None,
+) -> None:
+ """Run uvicorn with the discovery lockfile held; clean up on exit."""
+ lock_path = _lock._serve_lock_path()
+ if lock_path:
+ _lock._write_serve_lock(lock_path, host=host, port=port, ui_port=ui_port)
+
+ try:
+ uvicorn.run(
+ "repowise.server.app:create_app",
+ factory=True,
+ host=host,
+ port=port,
+ workers=workers,
+ log_level="info",
+ )
+ finally:
+ if lock_path:
+ _lock._remove_serve_lock(lock_path)
+ if frontend_proc:
+ frontend_proc.terminate()
+ frontend_proc.wait(timeout=5)
+
+
[email protected]("--port", default=7337, type=int, help="API server port.", envvar="REPOWISE_PORT")
[email protected]("--host", default="127.0.0.1", help="Host to bind to.")
[email protected]("--workers", default=1, type=int, help="Number of uvicorn workers.")
[email protected]("--ui-port", default=3000, type=int, help="Web UI port.")
[email protected]("--no-ui", is_flag=True, help="Start API server only, skip the web UI.")
+ "--refresh-ui",
+ is_flag=True,
+ help="Force re-download of the web UI tarball, ignoring any cache.",
+)
+def serve_command(
+ port: int, host: str, workers: int, ui_port: int, no_ui: bool, refresh_ui: bool
+) -> None:
+ """Start the repowise server with the web UI.
+
+ Starts the API backend and automatically launches the web frontend.
+ The web UI is downloaded and cached on first run (~50 MB, one-time).
+
+ Use --no-ui to start only the API server.
+ """
+ uvicorn = _import_uvicorn()
+ _advisory._start_update_advisory()
+
+ # Local .repowise/.env and config.yaml first, so a configured embedder is
+ # found instead of re-prompting. Existing env vars always win.
+ _embedder._load_local_provider_config()
+ _embedder._setup_embedder()
+
+ _resolve_db_url()
+ _configure_host_env(host)
+
+ # Resolve the API port up front: uvicorn would crash later with a bare
+ # OSError, and the chosen port flows into the frontend's REPOWISE_API_URL.
+ port = _ports._find_free_port(host, port, "API server")
+
+ frontend_proc: subprocess.Popen | None = None
+ if not no_ui:
+ # The UI takes the same bind as the API, so probe there.
+ ui_port = _ports._find_free_port(host, ui_port, "web UI")
+ frontend_proc = _frontend._launch_web_ui(host, port, ui_port, refresh_ui=refresh_ui)
+
+ console.print(f"[green]API server starting on http://{host}:{port}[/green]")
+ _run_api(
+ uvicorn,
+ host=host,
+ port=port,
+ workers=workers,
+ ui_port=None if frontend_proc is None else ui_port,
+ frontend_proc=frontend_proc,
+ )
diff --git a/tests/unit/cli/test_serve_db_url_isolation.py b/tests/unit/cli/test_serve_db_url_isolation.py
index e8f386586..3b2158ec2 100644
--- a/tests/unit/cli/test_serve_db_url_isolation.py
+++ b/tests/unit/cli/test_serve_db_url_isolation.py
@@ -20,6 +20,7 @@ import pytest
from click.testing import CliRunner
from repowise.cli.commands import serve_cmd
+from repowise.cli.commands.serve_cmd import _embedder, _lock, _ports
SENTINEL = "sqlite+aiosqlite:///:memory:"
@@ -28,10 +29,10 @@ SENTINEL = "sqlite+aiosqlite:///:memory:"
def stub_serve(monkeypatch) -> None:
"""Everything `serve` would really do, except touching the database."""
monkeypatch.setattr("uvicorn.run", lambda _app, **_kwargs: None)
- monkeypatch.setattr(serve_cmd, "_load_local_provider_config", lambda: None)
- monkeypatch.setattr(serve_cmd, "_setup_embedder", lambda: None)
- monkeypatch.setattr(serve_cmd, "_serve_lock_path", lambda: None)
- monkeypatch.setattr(serve_cmd, "_find_free_port", lambda _host, port, _label: port)
+ monkeypatch.setattr(_embedder, "_load_local_provider_config", lambda: None)
+ monkeypatch.setattr(_embedder, "_setup_embedder", lambda: None)
+ monkeypatch.setattr(_lock, "_serve_lock_path", lambda: None)
+ monkeypatch.setattr(_ports, "_find_free_port", lambda _host, port, _label: port)
monkeypatch.delenv("REPOWISE_API_KEY", raising=False)
monkeypatch.setenv("REPOWISE_HOST", "127.0.0.1")
diff --git a/tests/unit/cli/test_serve_host_env.py b/tests/unit/cli/test_serve_host_env.py
index 41806cfcd..af0f53625 100644
--- a/tests/unit/cli/test_serve_host_env.py
+++ b/tests/unit/cli/test_serve_host_env.py
@@ -13,6 +13,7 @@ import pytest
from click.testing import CliRunner
from repowise.cli.commands import serve_cmd
+from repowise.cli.commands.serve_cmd import _embedder, _frontend, _lock, _ports, _web_assets
@pytest.fixture
@@ -25,11 +26,11 @@ def stub_serve(monkeypatch) -> dict:
captured["repowise_host_env"] = os.environ.get("REPOWISE_HOST")
monkeypatch.setattr("uvicorn.run", fake_run)
- monkeypatch.setattr(serve_cmd, "_load_local_provider_config", lambda: None)
- monkeypatch.setattr(serve_cmd, "_setup_embedder", lambda: None)
- monkeypatch.setattr(serve_cmd, "_serve_lock_path", lambda: None)
+ monkeypatch.setattr(_embedder, "_load_local_provider_config", lambda: None)
+ monkeypatch.setattr(_embedder, "_setup_embedder", lambda: None)
+ monkeypatch.setattr(_lock, "_serve_lock_path", lambda: None)
# No real sockets: the port probe is not what these tests are about.
- monkeypatch.setattr(serve_cmd, "_find_free_port", lambda _host, port, _label: port)
+ monkeypatch.setattr(_ports, "_find_free_port", lambda _host, port, _label: port)
monkeypatch.delenv("REPOWISE_API_KEY", raising=False)
# The command auto-detects `./.repowise/wiki.db` and assigns
# REPOWISE_DB_URL straight onto os.environ. Under CliRunner the cwd is the
@@ -77,7 +78,7 @@ def test_web_ui_takes_the_api_bind(monkeypatch, tmp_path) -> None:
return None
(tmp_path / "server.js").write_text("")
- monkeypatch.setattr(serve_cmd.subprocess, "Popen", fake_popen)
- monkeypatch.setattr(serve_cmd, "_WEB_CACHE_DIR", tmp_path)
+ monkeypatch.setattr(_frontend.subprocess, "Popen", fake_popen)
+ monkeypatch.setattr(_web_assets, "_WEB_CACHE_DIR", tmp_path)
serve_cmd._start_frontend("node", 7337, 3000, local_web=None, host="127.0.0.1")
assert captured["hostname"] == "127.0.0.1"
diff --git a/tests/unit/cli/test_serve_node_version.py b/tests/unit/cli/test_serve_node_version.py
index cccf40cf1..9354223d2 100644
--- a/tests/unit/cli/test_serve_node_version.py
+++ b/tests/unit/cli/test_serve_node_version.py
@@ -14,6 +14,7 @@ from typing import Any
import pytest
from repowise.cli.commands import serve_cmd
+from repowise.cli.commands.serve_cmd import _web_assets
class _FakeCompleted:
@@ -26,7 +27,7 @@ def test_node_major_version_parses_standard_output(monkeypatch: pytest.MonkeyPat
def fake_run(*_args: Any, **_kwargs: Any) -> _FakeCompleted:
return _FakeCompleted("v20.11.1\n")
- monkeypatch.setattr(serve_cmd.subprocess, "run", fake_run)
+ monkeypatch.setattr(_web_assets.subprocess, "run", fake_run)
assert serve_cmd._node_major_version("/usr/bin/node") == 20
@@ -36,7 +37,7 @@ def test_node_major_version_parses_old_release(monkeypatch: pytest.MonkeyPatch)
def fake_run(*_args: Any, **_kwargs: Any) -> _FakeCompleted:
return _FakeCompleted("v12.22.12\n")
- monkeypatch.setattr(serve_cmd.subprocess, "run", fake_run)
+ monkeypatch.setattr(_web_assets.subprocess, "run", fake_run)
assert serve_cmd._node_major_version("/usr/bin/node") == 12
@@ -46,7 +47,7 @@ def test_node_major_version_handles_missing_v_prefix(
def fake_run(*_args: Any, **_kwargs: Any) -> _FakeCompleted:
return _FakeCompleted("18.20.3\n")
- monkeypatch.setattr(serve_cmd.subprocess, "run", fake_run)
+ monkeypatch.setattr(_web_assets.subprocess, "run", fake_run)
assert serve_cmd._node_major_version("/usr/bin/node") == 18
@@ -56,7 +57,7 @@ def test_node_major_version_returns_none_on_subprocess_error(
def fake_run(*_args: Any, **_kwargs: Any) -> _FakeCompleted:
raise subprocess.CalledProcessError(1, "node")
- monkeypatch.setattr(serve_cmd.subprocess, "run", fake_run)
+ monkeypatch.setattr(_web_assets.subprocess, "run", fake_run)
assert serve_cmd._node_major_version("/usr/bin/node") is None
@@ -66,7 +67,7 @@ def test_node_major_version_returns_none_on_oserror(
def fake_run(*_args: Any, **_kwargs: Any) -> _FakeCompleted:
raise OSError("not executable")
- monkeypatch.setattr(serve_cmd.subprocess, "run", fake_run)
+ monkeypatch.setattr(_web_assets.subprocess, "run", fake_run)
assert serve_cmd._node_major_version("/missing/node") is None
@@ -76,7 +77,7 @@ def test_node_major_version_returns_none_on_garbage_output(
def fake_run(*_args: Any, **_kwargs: Any) -> _FakeCompleted:
return _FakeCompleted("not a version string\n")
- monkeypatch.setattr(serve_cmd.subprocess, "run", fake_run)
+ monkeypatch.setattr(_web_assets.subprocess, "run", fake_run)
assert serve_cmd._node_major_version("/usr/bin/node") is None
diff --git a/tests/unit/cli/test_serve_paths.py b/tests/unit/cli/test_serve_paths.py
index 9ded4a7cf..70d10c08d 100644
--- a/tests/unit/cli/test_serve_paths.py
+++ b/tests/unit/cli/test_serve_paths.py
@@ -1,4 +1,4 @@
-"""Safety net for `repowise serve` before the module is split.
+"""Safety net for `repowise serve`.
Pins the embedder prompt, port fallback, web asset resolution (download,
local build, staleness), frontend launch and the command's branch order.
@@ -22,6 +22,13 @@ import pytest
from click.testing import CliRunner
from repowise.cli.commands import serve_cmd
+from repowise.cli.commands.serve_cmd import (
+ _advisory,
+ _embedder,
+ _frontend,
+ _ports,
+ _web_assets,
+)
from ._real_call_guard import guard_real_calls
@@ -57,15 +64,15 @@ _EMBED_ENV = (
def embed_env(monkeypatch, tmp_path) -> dict:
"""Clean embedder env, a tmp global config dir and a scripted prompt."""
_own_env(monkeypatch, *_EMBED_ENV)
- monkeypatch.setattr(serve_cmd, "_GLOBAL_CONFIG_DIR", tmp_path / "global")
+ monkeypatch.setattr(_embedder, "_GLOBAL_CONFIG_DIR", tmp_path / "global")
state: dict = {"config": {}, "answers": [], "prompts": []}
- monkeypatch.setattr(serve_cmd, "load_config", lambda _p: state["config"])
+ monkeypatch.setattr(_embedder, "load_config", lambda _p: state["config"])
def fake_prompt(text, default=None, **_kw):
state["prompts"].append((text.strip(), default))
return state["answers"].pop(0)
- monkeypatch.setattr(serve_cmd.click, "prompt", fake_prompt)
+ monkeypatch.setattr(_embedder.click, "prompt", fake_prompt)
return state
@@ -234,7 +241,7 @@ def test_find_free_port_scans_upward(monkeypatch) -> None:
probed.append(port)
return port == 3002
- monkeypatch.setattr(serve_cmd, "_is_port_free", fake_free)
+ monkeypatch.setattr(_ports, "_is_port_free", fake_free)
assert serve_cmd._find_free_port("127.0.0.1", 3000, "web UI") == 3002
assert probed == [3000, 3001, 3002]
@@ -246,7 +253,7 @@ def test_find_free_port_respects_max_attempts(monkeypatch) -> None:
probed.append(port)
return False
- monkeypatch.setattr(serve_cmd, "_is_port_free", fake_free)
+ monkeypatch.setattr(_ports, "_is_port_free", fake_free)
serve_cmd._find_free_port("127.0.0.1", 4000, "API server", max_attempts=3)
assert probed == [4000, 4001, 4002, 4003]
@@ -258,7 +265,7 @@ def test_find_free_port_stops_scanning_at_65535(monkeypatch) -> None:
probed.append(port)
return False
- monkeypatch.setattr(serve_cmd, "_is_port_free", fake_free)
+ monkeypatch.setattr(_ports, "_is_port_free", fake_free)
chosen = serve_cmd._find_free_port("127.0.0.1", 65534, "API server")
assert probed == [65534, 65535]
assert isinstance(chosen, int) and chosen > 0
@@ -272,8 +279,8 @@ def test_find_free_port_stops_scanning_at_65535(monkeypatch) -> None:
@pytest.fixture
def web_cache(monkeypatch, tmp_path) -> Path:
cache = tmp_path / "web-cache"
- monkeypatch.setattr(serve_cmd, "_WEB_CACHE_DIR", cache)
- monkeypatch.setattr(serve_cmd, "_MARKER_FILE", cache / ".version")
+ monkeypatch.setattr(_web_assets, "_WEB_CACHE_DIR", cache)
+ monkeypatch.setattr(_web_assets, "_MARKER_FILE", cache / ".version")
return cache
@@ -294,16 +301,14 @@ def test_find_local_web_walks_up_from_cwd(monkeypatch, tmp_path) -> None:
(repo / "packages" / "web" / "package.json").write_text("{}")
deep = repo / "a" / "b"
deep.mkdir(parents=True)
- # Retarget to the submodule that reads __file__ once serve_cmd is a package.
- monkeypatch.setattr(serve_cmd, "__file__", str(tmp_path / "x" / "y" / "serve_cmd.py"))
+ monkeypatch.setattr(_web_assets, "__file__", str(tmp_path / "x" / "y" / "serve_cmd.py"))
monkeypatch.chdir(deep)
assert serve_cmd._find_local_web() == (repo / "packages" / "web").resolve()
def test_find_local_web_none_without_package_json(monkeypatch, tmp_path) -> None:
(tmp_path / "packages" / "web").mkdir(parents=True) # no package.json
- # Retarget to the submodule that reads __file__ once serve_cmd is a package.
- monkeypatch.setattr(serve_cmd, "__file__", str(tmp_path / "x" / "serve_cmd.py"))
+ monkeypatch.setattr(_web_assets, "__file__", str(tmp_path / "x" / "serve_cmd.py"))
monkeypatch.chdir(tmp_path)
assert serve_cmd._find_local_web() is None
@@ -440,7 +445,7 @@ def fake_run(monkeypatch) -> dict:
if len(st["calls"]) == st["fail_at"]:
raise subprocess.CalledProcessError(1, cmd)
- monkeypatch.setattr(serve_cmd.subprocess, "run", _run)
+ monkeypatch.setattr(_web_assets.subprocess, "run", _run)
return st
@@ -478,7 +483,7 @@ def fake_popen(monkeypatch) -> list:
calls.append((cmd, kw))
return "proc"
- monkeypatch.setattr(serve_cmd.subprocess, "Popen", _popen)
+ monkeypatch.setattr(_frontend.subprocess, "Popen", _popen)
return calls
@@ -579,30 +584,30 @@ def serve(monkeypatch, tmp_path) -> dict:
return _f
- monkeypatch.setattr(serve_cmd, "_update_advisory_tick", lambda _a: None)
- monkeypatch.setattr(serve_cmd, "_start_update_advisory_loop", lambda _a: None)
- monkeypatch.setattr(serve_cmd, "_load_local_provider_config", rec("load_local"))
- monkeypatch.setattr(serve_cmd, "_setup_embedder", rec("setup_embedder"))
+ monkeypatch.setattr(_advisory, "_update_advisory_tick", lambda _a: None)
+ monkeypatch.setattr(_advisory, "_start_update_advisory_loop", lambda _a: None)
+ monkeypatch.setattr(_embedder, "_load_local_provider_config", rec("load_local"))
+ monkeypatch.setattr(_embedder, "_setup_embedder", rec("setup_embedder"))
def free_port(host, port, label):
ev.append(("port", host, port, label))
return port + 1
- monkeypatch.setattr(serve_cmd, "_find_free_port", free_port)
- monkeypatch.setattr(serve_cmd, "_node_available", lambda: st["node"])
- monkeypatch.setattr(serve_cmd, "_npm_available", lambda: st["npm"])
- monkeypatch.setattr(serve_cmd, "_node_major_version", lambda _n: st["node_major"])
- monkeypatch.setattr(serve_cmd, "_find_local_web", rec("find_local", "local_web"))
- monkeypatch.setattr(serve_cmd, "_local_build_is_stale", rec("stale", "stale"))
- monkeypatch.setattr(serve_cmd, "_build_local_web", rec("build", "build_ok"))
- monkeypatch.setattr(serve_cmd, "_web_is_cached", rec("cached", "cached"))
- monkeypatch.setattr(serve_cmd, "_download_web", rec("download", "download_ok"))
+ monkeypatch.setattr(_ports, "_find_free_port", free_port)
+ monkeypatch.setattr(_web_assets, "_node_available", lambda: st["node"])
+ monkeypatch.setattr(_web_assets, "_npm_available", lambda: st["npm"])
+ monkeypatch.setattr(_web_assets, "_node_major_version", lambda _n: st["node_major"])
+ monkeypatch.setattr(_web_assets, "_find_local_web", rec("find_local", "local_web"))
+ monkeypatch.setattr(_web_assets, "_local_build_is_stale", rec("stale", "stale"))
+ monkeypatch.setattr(_web_assets, "_build_local_web", rec("build", "build_ok"))
+ monkeypatch.setattr(_web_assets, "_web_is_cached", rec("cached", "cached"))
+ monkeypatch.setattr(_web_assets, "_download_web", rec("download", "download_ok"))
def start(node, port, ui_port, local_web=None, host=None):
ev.append(("start", node, port, ui_port, local_web, host))
return _Proc(ev) if st["proc"] else None
- monkeypatch.setattr(serve_cmd, "_start_frontend", start)
+ monkeypatch.setattr(_frontend, "_start_frontend", start)
def fake_uvicorn(app, **kw):
lock = serve_cmd._serve_lock_path()
@@ -767,12 +772,12 @@ def test_serve_missing_uvicorn_exits_1(serve, monkeypatch) -> None:
def test_serve_advisory_runs_only_on_a_terminal(serve, monkeypatch) -> None:
ticks: list = []
- monkeypatch.setattr(serve_cmd, "_update_advisory_tick", lambda a: ticks.append("tick"))
- monkeypatch.setattr(serve_cmd, "_start_update_advisory_loop", lambda a: ticks.append("loop"))
- monkeypatch.setattr(type(serve_cmd.console), "is_terminal", property(lambda _s: False))
+ monkeypatch.setattr(_advisory, "_update_advisory_tick", lambda a: ticks.append("tick"))
+ monkeypatch.setattr(_advisory, "_start_update_advisory_loop", lambda a: ticks.append("loop"))
+ monkeypatch.setattr(type(_advisory.console), "is_terminal", property(lambda _s: False))
_invoke("--no-ui")
assert ticks == []
- monkeypatch.setattr(type(serve_cmd.console), "is_terminal", property(lambda _s: True))
+ monkeypatch.setattr(type(_advisory.console), "is_terminal", property(lambda _s: True))
_invoke("--no-ui")
assert ticks == ["tick", "loop"]
diff --git a/tests/unit/cli/test_serve_port_fallback.py b/tests/unit/cli/test_serve_port_fallback.py
index bbf43b019..7901bc421 100644
--- a/tests/unit/cli/test_serve_port_fallback.py
+++ b/tests/unit/cli/test_serve_port_fallback.py
@@ -13,6 +13,7 @@ import socket
import pytest
from repowise.cli.commands import serve_cmd
+from repowise.cli.commands.serve_cmd import _ports
def _bind_listener(host: str = "127.0.0.1") -> tuple[socket.socket, int]:
@@ -64,7 +65,7 @@ def test_find_free_port_handles_contiguous_busy_block(
to an OS-assigned ephemeral port instead of raising."""
# Pretend every port in the scan range is busy; the function should still
# produce a usable port via the wildcard bind path.
- monkeypatch.setattr(serve_cmd, "_is_port_free", lambda host, port: False)
+ monkeypatch.setattr(_ports, "_is_port_free", lambda host, port: False)
chosen = serve_cmd._find_free_port("127.0.0.1", 3000, "web UI", max_attempts=5)
assert isinstance(chosen, int)
diff --git a/tests/unit/cli/test_serve_web_extract.py b/tests/unit/cli/test_serve_web_extract.py
index f7e75584b..36e802951 100644
--- a/tests/unit/cli/test_serve_web_extract.py
+++ b/tests/unit/cli/test_serve_web_extract.py
@@ -9,6 +9,7 @@ from pathlib import Path
import pytest
from repowise.cli.commands import serve_cmd
+from repowise.cli.commands.serve_cmd import _web_assets
def _make_tar(path: Path, members: list[tuple[str, str | None, bytes]]) -> Path:
@@ -106,8 +107,8 @@ def test_download_web_reports_failure_on_tampered_archive(
monkeypatch.setattr(httpx, "stream", lambda *_a, **_k: _Resp())
dest = _dest(tmp_path)
- monkeypatch.setattr(serve_cmd, "_WEB_CACHE_DIR", dest)
- monkeypatch.setattr(serve_cmd, "_MARKER_FILE", dest / ".version")
+ monkeypatch.setattr(_web_assets, "_WEB_CACHE_DIR", dest)
+ monkeypatch.setattr(_web_assets, "_MARKER_FILE", dest / ".version")
assert serve_cmd._download_web("0.0.0") is False
assert not (dest / ".version").exists()
diff --git a/tests/unit/ingestion/test_fs_walk.py b/tests/unit/ingestion/test_fs_walk.py
index b4a8d8a3d..136fefdf0 100644
--- a/tests/unit/ingestion/test_fs_walk.py
+++ b/tests/unit/ingestion/test_fs_walk.py
@@ -558,7 +558,7 @@ _WALK_ALLOWLIST: dict[tuple[str, str], frozenset[str]] = {
# Sizes .repowise/ only — repowise-owned, cannot contain junk trees.
("cli", "commands/status_cmd.py"): frozenset({"rglob"}),
# Scans repowise's own packaged web/ui source dirs, not the user repo.
- ("cli", "commands/serve_cmd.py"): frozenset({"rglob"}),
+ ("cli", "commands/serve_cmd/_web_assets.py"): frozenset({"rglob"}),
# Sizes .repowise/ only — repowise-owned, cannot contain junk trees.
("server", "services/overview_payload.py"): frozenset({"rglob"}),
}
diff --git a/tests/unit/test_providers/test_provider_specs.py b/tests/unit/test_providers/test_provider_specs.py
index 1fab7a39c..3e5a77c42 100644
--- a/tests/unit/test_providers/test_provider_specs.py
+++ b/tests/unit/test_providers/test_provider_specs.py
@@ -103,7 +103,7 @@ _ALLOWED: dict[str, frozenset[str]] = {
"core/src/repowise/core/providers/embedding/resolve.py": _EMBEDDERS,
"cli/src/repowise/cli/commands/init_cmd/command.py": _EMBEDDERS,
"cli/src/repowise/cli/commands/reindex_cmd.py": _EMBEDDERS,
- "cli/src/repowise/cli/commands/serve_cmd.py": _EMBEDDERS,
+ "cli/src/repowise/cli/commands/serve_cmd/_embedder.py": _EMBEDDERS,
"cli/src/repowise/cli/commands/update_cmd/deterministic.py": _EMBEDDERS,
"cli/src/repowise/cli/providers/embedders.py": _EMBEDDERS,
"cli/src/repowise/cli/ui/mode_selection.py": _EMBEDDERS,