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.

Workspace robustness — auto-detect, fan-out, doctor, web UI (#173)

Raghav Chamadiyae6d381bc9934
diff --git a/.gitignore b/.gitignore
index ab475a8e9..02eef4b0f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -128,6 +128,21 @@ docs/LANGUAGE_REMAINING_WORK.md
# Local UI/UX audit notes
AUDIT_UI_UX.md
+docs/WEB_UI_IMPROVEMENT_PLAN.md
+docs/WORKSPACE_ROBUSTNESS.md
+
+# Local demo scripts (not for distribution)
+demo/
+
+# Local scratch — dead-code analysis & R2 tooling
+_pip_check/
+content_engine/
+analyze_findings.py
+fetch_r2.py
+upload_r2.py
+filter_dead_code.py
+inspect_*.py
+eshop_hosted_dead_code.*
# Local scratch / sibling tools (not for distribution)
GitNexus/
diff --git a/README.md b/README.md
index 0e325e28a..253f63662 100644
--- a/README.md
+++ b/README.md
@@ -159,14 +159,18 @@ repowise init . # scan, select repos, index each, run cross-repo analy
```bash
repowise workspace list # show all repos and their status
-repowise workspace add ../new-service # add a repo to the workspace
+repowise workspace add ../new-service # add a repo (auto-indexes + docs by default)
repowise workspace remove api-gateway # remove a repo (doesn't delete files)
repowise workspace scan # re-scan for new repos
-repowise update --workspace # update all stale repos + cross-repo analysis
+repowise update --workspace # update all stale repos + first-time index any new ones
+repowise update --repo backend # scope to one repo (auto-detected from cwd too)
repowise watch --workspace # auto-update all repos on file change
+repowise doctor --workspace --repair # validate every repo; sync state drift; drop dead entries
repowise hook install --workspace # install post-commit hooks for all repos
```
+Most commands also accept `--no-workspace` to force single-repo mode and `--repo <alias>` to scope to one repo. See [CLI Reference](docs/CLI_REFERENCE.md#workspace-auto-detect-cross-cutting).
+
Full guide: [docs/WORKSPACES.md](docs/WORKSPACES.md)
---
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index 64d2837b0..4af4b81f1 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -2,6 +2,19 @@
Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](QUICKSTART.md).
+## Workspace auto-detect (cross-cutting)
+
+Most commands auto-detect whether you're in a workspace root and route accordingly. When auto-detection fires, the command prints a one-line `[workspace] …` notice. You can always override:
+
+| Flag | Effect |
+|------|--------|
+| `--workspace` / `-w` | Force workspace mode. Errors if no `.repowise-workspace.yaml` is found. |
+| `--no-workspace` | Force single-repo mode even when invoked from a workspace root. |
+| `--repo <alias>` | Scope a workspace command to one repo. Available on commands where it makes sense. |
+| `--all` | Fan out across every workspace repo (on `costs`, `search`). |
+
+The commands that grew these flags in v0.8.x: `update`, `status`, `watch`, `doctor`, `costs`, `search`, `dead-code`, `decision`, `generate-claude-md`, `hook install/status/uninstall`.
+
---
## Core Commands
@@ -85,16 +98,20 @@ Incrementally update wiki pages for files changed since the last sync.
| `--cascade-budget` | Max pages to regenerate (default: auto) |
| `--dry-run` | Show what would be updated without regenerating |
| `--workspace` | Update all stale repos in the workspace + cross-repo analysis |
+| `--no-workspace` | Force single-repo mode (handy when running from a workspace root) |
| `--repo` | Update a specific workspace repo by alias |
+**First-time indexing:** as of v0.8, `update --workspace` now runs full first-time indexing for workspace entries that have no `.repowise/` dir yet (previously skipped with `"not_indexed"`). The pipeline runs index-only — no LLM cost — and writes a state.json marker so `repowise update --repo <alias> --docs` later picks up doc generation cleanly.
+
**Examples:**
```bash
repowise update # diff since last sync
repowise update --dry-run # preview
repowise update --since v1.0.0 # diff from a tag
-repowise update --workspace # all workspace repos
+repowise update --workspace # all workspace repos (incl. first-time indexing)
repowise update --repo backend # specific workspace repo
+repowise update --no-workspace # force single-repo mode in a workspace root
```
---
@@ -143,11 +160,14 @@ Watch for file changes and auto-update wiki pages. Press `Ctrl+C` to stop.
| `--model` | Model override |
| `--debounce` | Delay in ms after last change (default: 2000) |
| `--workspace` | Watch all workspace repos |
+| `--no-workspace` | Force single-repo mode |
+| `--repo` | Watch a single workspace repo by alias |
```bash
-repowise watch # single repo
+repowise watch # single repo (auto-detects)
repowise watch --debounce 5000 # 5s debounce
repowise watch --workspace # all workspace repos
+repowise watch --repo backend # just one
```
---
@@ -164,11 +184,16 @@ Search wiki pages by keyword, meaning, or symbol name.
|------|-------------|
| `--mode` | `fulltext` (default), `semantic`, `symbol` |
| `--limit` | Max results (default: 10) |
+| `--repo` | Scope to a specific workspace repo by alias |
+| `--all` | Fan out across every workspace repo and merge results |
+| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
```bash
repowise search "rate limiting"
repowise search "how are errors handled" --mode semantic
repowise search "AuthService" --mode symbol
+repowise search "rate limit" --repo backend # workspace, one repo
+repowise search "rate limit" --all # workspace, fan-out
```
---
@@ -189,10 +214,13 @@ repowise query "what files handle payment processing?"
Show wiki sync state, page statistics, and coverage.
```bash
-repowise status # single repo
+repowise status # auto-detects mode
repowise status --workspace # all workspace repos
+repowise status --no-workspace # force single-repo even in a workspace
```
+In workspace mode, the table includes a **Docs** column with each repo's page count and a per-repo **Docs status** block listing skip reasons (e.g. `cost gate declined`) and the exact remediation command.
+
---
## Analysis Commands
@@ -211,11 +239,14 @@ Detect dead and unused code.
| `--format` | Output: `table` (default), `json`, `md` |
| `--include-internals` | Include private/underscore symbols |
| `--include-zombie-packages` | Include unused declared packages |
+| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
+| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
```bash
repowise dead-code
repowise dead-code --safe-only --min-confidence 0.8
repowise dead-code --format json
+repowise dead-code --repo backend # workspace, single repo
repowise dead-code resolve <id> # mark resolved / false positive
```
@@ -252,11 +283,20 @@ repowise decision health [PATH] # health dashboard
Show LLM spend tracking.
+| Flag | Description |
+|------|-------------|
+| `--by` | Grouping: `operation`, `model`, `day` |
+| `--repo` | Scope to a specific workspace repo |
+| `--all` | Aggregate across every workspace repo |
+| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
+
```bash
-repowise costs # total spend
+repowise costs # auto-detects mode
repowise costs --by operation # grouped by operation
repowise costs --by model # grouped by model
repowise costs --by day # grouped by day
+repowise costs --all # workspace-wide aggregate
+repowise costs --repo backend # one workspace repo
```
---
@@ -271,8 +311,20 @@ Show all repos in the workspace with their index status.
Add a new repo to an existing workspace and index it.
+**As of v0.8 this defaults to `--index --docs`** when a provider is configured — the added repo is indexed and gets LLM doc generation in one step, with a cost-gate prompt before any tokens are spent. Pass `--no-docs` to skip generation, or `--no-index` to only register the entry. The provider, model, embedder, and exclude patterns are inherited from the primary repo's `.repowise/config.yaml` unless overridden.
+
+| Flag | Description |
+|------|-------------|
+| `--alias` | Short name for the repo (defaults to directory name) |
+| `--index` / `--no-index` | Run the index pipeline (default: on) |
+| `--docs` / `--no-docs` | Run LLM doc generation (default: on when a provider is configured) |
+| `--provider` / `--model` | Override the inherited provider/model |
+| `--primary` | Mark this repo as the workspace default |
+
```bash
repowise workspace add ../new-service --alias api-gateway
+repowise workspace add ../mobile --no-docs # index, no LLM
+repowise workspace add ../shared --no-index # register only
```
### `repowise workspace remove <alias>`
@@ -391,11 +443,18 @@ repowise reindex --embedder gemini --batch-size 50
### `repowise doctor [PATH]`
-Run health checks on the wiki setup.
+Run health checks on the wiki setup. Auto-detects workspace mode; in workspace mode runs a workspace-level table (directory exists, git repo, state.json ↔ workspace config drift) followed by the per-repo check battery for every indexed entry.
+
+| Flag | Description |
+|------|-------------|
+| `--repair` | Repair detected issues: rebuild FTS, re-embed missing pages, sync drifted workspace state, drop dead workspace entries |
+| `--workspace` / `--no-workspace` | Force workspace / single-repo mode |
```bash
-repowise doctor
-repowise doctor --repair # fix detected store mismatches
+repowise doctor # auto-detects
+repowise doctor --repair # fix detected store mismatches
+repowise doctor --workspace # every workspace repo
+repowise doctor --workspace --repair # also drop dead entries / sync drift
```
---
diff --git a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
index 13f318919..880b80228 100644
--- a/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/claude_md_cmd.py
@@ -8,9 +8,11 @@ from pathlib import Path
import click
from repowise.cli.helpers import (
+ console,
ensure_repowise_dir,
find_workspace_root,
get_db_url_for_repo,
+ resolve_command_target,
run_async,
)
@@ -38,15 +40,23 @@ from repowise.cli.helpers import (
is_flag=True,
default=False,
help=(
- "Generate a workspace-level CLAUDE.md that includes cross-repo contracts, "
- "co-changes, package dependencies, and per-repo summaries."
+ "Force workspace mode. Generates a workspace-level CLAUDE.md at the "
+ "workspace root with cross-repo contracts, co-changes, and per-repo "
+ "summaries."
),
)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
def claude_md_command(
path: str | None,
output_path: str | None,
to_stdout: bool,
workspace_mode: bool,
+ no_workspace: bool,
) -> None:
"""Generate or update CLAUDE.md with codebase intelligence context.
@@ -58,21 +68,28 @@ def claude_md_command(
Run 'repowise init' or 'repowise update' to keep it current automatically.
- Pass --workspace / -w to generate a workspace-level CLAUDE.md at the workspace
- root instead of a per-repo file.
+ Auto-detects workspace mode when invoked from a workspace root. Use
+ --workspace to force on, --no-workspace to force off.
"""
- start_path = Path(path).resolve() if path else Path.cwd()
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace_mode,
+ no_workspace_flag=no_workspace,
+ )
+ target.notice(console, command="generate-claude-md")
- if workspace_mode:
+ if target.is_workspace:
+ assert target.ws_root is not None
try:
- content = _generate_workspace(start_path, output_path, to_stdout)
+ content = _generate_workspace(target.ws_root, output_path, to_stdout)
except Exception as exc:
raise click.ClickException(str(exc)) from exc
if to_stdout:
click.echo(content, nl=False)
return
- repo_path = start_path
+ repo_path = target.repo_path
+ assert repo_path is not None
ensure_repowise_dir(repo_path)
try:
diff --git a/packages/cli/src/repowise/cli/commands/costs_cmd.py b/packages/cli/src/repowise/cli/commands/costs_cmd.py
index 000eb84eb..3a976cac7 100644
--- a/packages/cli/src/repowise/cli/commands/costs_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/costs_cmd.py
@@ -12,6 +12,7 @@ from rich.table import Table
from repowise.cli.helpers import (
console,
get_db_url_for_repo,
+ resolve_command_target,
resolve_repo_path,
run_async,
)
@@ -55,28 +56,116 @@ def _parse_date(value: str | None) -> datetime | None:
metavar="PATH",
help="Repository path (defaults to current directory).",
)
+ "--repo",
+ "repo_alias",
+ default=None,
+ help="Workspace repo alias to query (implies workspace mode).",
+)
+ "--all",
+ "show_all",
+ is_flag=True,
+ default=False,
+ help="In workspace mode, sum costs across every repo instead of just the primary.",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
def costs_command(
path: str | None,
since: str | None,
group_by: str,
repo_path_flag: str | None,
+ repo_alias: str | None,
+ show_all: bool,
+ no_workspace: bool,
) -> None:
"""Show LLM cost history for a repository.
PATH (or --repo-path) defaults to the current directory.
+
+ In workspace mode, defaults to the primary repo; pass --repo <alias>
+ for a specific one or --all to sum across every repo.
"""
# Support both positional PATH and --repo-path flag
raw_path = path or repo_path_flag
- repo_path = resolve_repo_path(raw_path)
- repowise_dir = repo_path / ".repowise"
- if not repowise_dir.exists():
- console.print("[yellow]No .repowise/ directory found. Run 'repowise init' first.[/yellow]")
+ target = resolve_command_target(
+ path=raw_path,
+ no_workspace_flag=no_workspace,
+ repo_alias=repo_alias,
+ )
+ target.notice(console, command="costs")
+
+ # Resolve which repo paths to query
+ repo_paths: list[Path] = []
+ if target.is_workspace:
+ assert target.ws_root is not None and target.ws_config is not None
+ if show_all:
+ repo_paths = [
+ (target.ws_root / e.path).resolve() for e in target.ws_config.repos
+ ]
+ elif target.repo_filter is not None:
+ picked = target.resolve_repo_alias(target.repo_filter)
+ if picked is None:
+ raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
+ repo_paths = [picked]
+ else:
+ primary = target.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ repo_paths = [primary]
+ else:
+ assert target.repo_path is not None
+ repo_paths = [target.repo_path]
+
+ # Filter to repos that have a .repowise/ — otherwise the cost query
+ # would just return an empty result and confuse the user.
+ valid_paths = [p for p in repo_paths if (p / ".repowise").is_dir()]
+ if not valid_paths:
+ console.print("[yellow]No indexed .repowise/ directory found. Run 'repowise init' first.[/yellow]")
return
+ if len(valid_paths) < len(repo_paths):
+ missing = [p.name for p in repo_paths if p not in valid_paths]
+ console.print(
+ f"[yellow]Skipping unindexed repos: {', '.join(missing)}[/yellow]"
+ )
since_dt = _parse_date(since)
- rows = run_async(_query_costs(repo_path, since=since_dt, group_by=group_by))
+ # Aggregate cost rows across every selected repo. For single-repo this
+ # is the original behavior; for --all it sums per group across repos.
+ rows: list[dict[str, Any]] = []
+ if len(valid_paths) == 1:
+ rows = run_async(_query_costs(valid_paths[0], since=since_dt, group_by=group_by))
+ else:
+ merged: dict[str, dict[str, Any]] = {}
+ for rp in valid_paths:
+ try:
+ per_repo = run_async(_query_costs(rp, since=since_dt, group_by=group_by))
+ except Exception:
+ continue
+ for row in per_repo:
+ key = str(row.get("group") or "—")
+ m = merged.setdefault(
+ key,
+ {
+ "group": key,
+ "calls": 0,
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cost_usd": 0.0,
+ },
+ )
+ m["calls"] += row.get("calls", 0)
+ m["input_tokens"] += row.get("input_tokens", 0)
+ m["output_tokens"] += row.get("output_tokens", 0)
+ m["cost_usd"] += row.get("cost_usd", 0.0)
+ rows = sorted(merged.values(), key=lambda r: r["cost_usd"], reverse=True)
if not rows:
msg = "No cost records found"
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index 2a9981c3e..a54b3645c 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -9,6 +9,7 @@ from rich.table import Table
from repowise.cli.helpers import (
console,
+ resolve_command_target,
resolve_repo_path,
run_async,
)
@@ -54,6 +55,18 @@ from repowise.cli.helpers import (
default=False,
help="Skip detection of unused public exports.",
)
+ "--repo",
+ "repo_alias",
+ default=None,
+ help="Workspace repo alias to analyze (implies workspace mode).",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
def dead_code_command(
path: str | None,
min_confidence: float,
@@ -64,14 +77,44 @@ def dead_code_command(
include_zombie_packages: bool,
no_unreachable: bool,
no_unused_exports: bool,
+ repo_alias: str | None,
+ no_workspace: bool,
) -> None:
- """Detect dead and unused code."""
+ """Detect dead and unused code.
+
+ In workspace mode, analyzes the primary repo by default; pass
+ --repo <alias> to target a different repo. Cross-repo dead-code
+ detection is not yet supported — run once per repo for now.
+ """
from pathlib import Path as PathlibPath
from repowise.core.analysis.dead_code import DeadCodeAnalyzer
from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
- repo_path = resolve_repo_path(path)
+ target = resolve_command_target(
+ path=path,
+ no_workspace_flag=no_workspace,
+ repo_alias=repo_alias,
+ )
+ target.notice(console, command="dead-code")
+
+ if target.is_workspace:
+ if target.repo_filter is not None:
+ picked = target.resolve_repo_alias(target.repo_filter)
+ if picked is None:
+ raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
+ repo_path = picked
+ else:
+ primary = target.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ repo_path = primary
+ console.print(
+ "[dim] (Tip: pass --repo <alias> to analyze a different repo.)[/dim]"
+ )
+ else:
+ assert target.repo_path is not None
+ repo_path = target.repo_path
console.print(f"[bold]repowise dead-code[/bold] — {repo_path}")
diff --git a/packages/cli/src/repowise/cli/commands/decision_cmd.py b/packages/cli/src/repowise/cli/commands/decision_cmd.py
index 95e793807..e2108e19e 100644
--- a/packages/cli/src/repowise/cli/commands/decision_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_cmd.py
@@ -12,11 +12,31 @@ from repowise.cli.helpers import (
console,
ensure_repowise_dir,
get_db_url_for_repo,
+ resolve_command_target,
resolve_repo_path,
run_async,
)
+def _resolve_decision_repo(path: str | None):
+ """Resolve the repo path for decision subcommands.
+
+ Honors workspace auto-detection: in workspace mode without an explicit
+ path, targets the primary repo and prints a transparency notice.
+ """
+ from pathlib import Path
+
+ target = resolve_command_target(path=path)
+ target.notice(console, command="decision")
+ if target.is_workspace:
+ primary = target.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ return primary
+ assert target.repo_path is not None
+ return target.repo_path
+
+
@click.group("decision")
def decision_group() -> None:
"""Manage architectural decision records."""
@@ -31,7 +51,7 @@ def decision_group() -> None:
@click.argument("path", required=False, default=None)
def decision_add(path: str | None) -> None:
"""Interactively add a new architectural decision."""
- repo_path = resolve_repo_path(path)
+ repo_path = _resolve_decision_repo(path)
ensure_repowise_dir(repo_path)
console.print("[bold]Add Architectural Decision[/bold]\n")
@@ -127,7 +147,7 @@ def decision_list(
stale_only: bool,
) -> None:
"""List architectural decision records."""
- repo_path = resolve_repo_path(path)
+ repo_path = _resolve_decision_repo(path)
async def _query() -> list:
from repowise.core.persistence import (
@@ -212,7 +232,7 @@ def decision_list(
@click.argument("path", required=False, default=None)
def decision_show(decision_id: str, path: str | None) -> None:
"""Show full details of a decision record."""
- repo_path = resolve_repo_path(path)
+ repo_path = _resolve_decision_repo(path)
async def _query():
from repowise.core.persistence import (
@@ -291,7 +311,7 @@ def decision_show(decision_id: str, path: str | None) -> None:
@click.argument("path", required=False, default=None)
def decision_confirm(decision_id: str, path: str | None) -> None:
"""Confirm a proposed decision (set status to active)."""
- repo_path = resolve_repo_path(path)
+ repo_path = _resolve_decision_repo(path)
async def _update():
from repowise.core.persistence import (
@@ -330,7 +350,7 @@ def decision_confirm(decision_id: str, path: str | None) -> None:
@click.argument("path", required=False, default=None)
def decision_dismiss(decision_id: str, path: str | None) -> None:
"""Dismiss (delete) a proposed decision."""
- repo_path = resolve_repo_path(path)
+ repo_path = _resolve_decision_repo(path)
if not click.confirm(f"Delete decision {decision_id[:8]}?"):
console.print("[yellow]Cancelled.[/yellow]")
@@ -374,7 +394,7 @@ def decision_dismiss(decision_id: str, path: str | None) -> None:
@click.option("--superseded-by", default=None, help="ID of the decision that replaces this one.")
def decision_deprecate(decision_id: str, path: str | None, superseded_by: str | None) -> None:
"""Deprecate an active decision."""
- repo_path = resolve_repo_path(path)
+ repo_path = _resolve_decision_repo(path)
async def _update():
from repowise.core.persistence import (
@@ -414,7 +434,7 @@ def decision_deprecate(decision_id: str, path: str | None, superseded_by: str |
@click.argument("path", required=False, default=None)
def decision_health(path: str | None) -> None:
"""Show decision health: stale decisions, proposed, ungoverned hotspots."""
- repo_path = resolve_repo_path(path)
+ repo_path = _resolve_decision_repo(path)
async def _query():
from repowise.core.persistence import (
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
index bf25b0168..a4819e6da 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
@@ -5,11 +5,14 @@ from __future__ import annotations
import click
from rich.table import Table
+from pathlib import Path as _DoctorPath
+
from repowise.cli.helpers import (
console,
get_db_url_for_repo,
get_repowise_dir,
load_state,
+ resolve_command_target,
resolve_repo_path,
run_async,
)
@@ -20,12 +23,13 @@ def _check(name: str, ok: bool, detail: str = "") -> tuple[str, str, str]:
return (name, status, detail)
[email protected]("path", required=False, default=None)
[email protected]("--repair", is_flag=True, default=False, help="Attempt to fix detected mismatches.")
-def doctor_command(path: str | None, repair: bool) -> None:
- """Run health checks on the wiki setup."""
- repo_path = resolve_repo_path(path)
+def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:
+ """Run the standard health checks against one repo. Returns ``True`` if
+ all checks passed.
+
+ Extracted so workspace mode can iterate over every repo without
+ duplicating the full check body.
+ """
checks: list[tuple[str, str, str]] = []
# 1. Git repository?
@@ -298,7 +302,7 @@ def doctor_command(path: str | None, repair: bool) -> None:
checks.append(_check("Coordinator drift", True, f"Could not check: {exc}"))
# Display
- table = Table(title="repowise Doctor")
+ table = Table(title=f"repowise Doctor — {repo_path.name}")
table.add_column("Check", style="cyan")
table.add_column("Status")
table.add_column("Detail")
@@ -400,3 +404,240 @@ def doctor_command(path: str | None, repair: bool) -> None:
console.print(f"[bold green]Repaired {repaired_count} entries.[/bold green]")
elif repair and not has_mismatches:
console.print("[green]Nothing to repair.[/green]")
+
+ return all_ok
+
+
[email protected]("path", required=False, default=None)
[email protected]("--repair", is_flag=True, default=False, help="Attempt to fix detected mismatches.")
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Force workspace mode (run checks against every repo in the workspace).",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
+def doctor_command(
+ path: str | None,
+ repair: bool,
+ workspace: bool,
+ no_workspace: bool,
+) -> None:
+ """Run health checks on the wiki setup.
+
+ Auto-detects workspace mode when invoked from a workspace root. In
+ workspace mode, runs the full check battery against each indexed repo
+ and prints a per-repo table plus a workspace-level summary.
+ """
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace,
+ no_workspace_flag=no_workspace,
+ )
+ target.notice(console, command="doctor")
+
+ if not target.is_workspace:
+ assert target.repo_path is not None
+ _run_repo_checks(target.repo_path, repair)
+ return
+
+ # Workspace mode — iterate over every entry, run workspace-level
+ # validation, and report a summary table at the end so the user knows
+ # which repos need attention.
+ assert target.ws_root is not None and target.ws_config is not None
+ ws_root = target.ws_root
+ ws_config = target.ws_config
+
+ ws_issues = _run_workspace_checks(ws_root, ws_config, repair=repair)
+
+ overall_ok = True
+ not_indexed: list[str] = []
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+ if not abs_path.is_dir():
+ continue
+ if not (abs_path / ".repowise").is_dir():
+ not_indexed.append(entry.alias)
+ continue
+ console.print()
+ console.print(
+ f"[bold]── {entry.alias}[/bold] "
+ f"[dim]({entry.path})[/dim]"
+ + (" [bold cyan](primary)[/bold cyan]" if entry.alias == ws_config.default_repo else "")
+ )
+ ok = _run_repo_checks(abs_path, repair)
+ overall_ok = overall_ok and ok
+
+ console.print()
+ if not_indexed:
+ console.print(
+ f"[yellow]Not indexed:[/yellow] {', '.join(not_indexed)}"
+ )
+ console.print(
+ " Run [bold]repowise update --workspace[/bold] to index them."
+ )
+ if ws_issues and not repair:
+ console.print(
+ f"[yellow]{len(ws_issues)} workspace-level issue(s); "
+ f"rerun with [bold]--repair[/bold] to attempt fixes.[/yellow]"
+ )
+
+ workspace_clean = not ws_issues and overall_ok and not not_indexed
+ if workspace_clean:
+ console.print("[bold green]Workspace healthy.[/bold green]")
+ elif overall_ok and not ws_issues:
+ console.print("[bold yellow]All indexed repos healthy; some repos unindexed.[/bold yellow]")
+ else:
+ console.print("[bold yellow]Some checks failed across the workspace.[/bold yellow]")
+
+
+def _run_workspace_checks(
+ ws_root: _DoctorPath,
+ ws_config,
+ *,
+ repair: bool,
+) -> list[str]:
+ """Run workspace-level validation. Returns a list of issue strings.
+
+ Covers:
+ - Per-entry directory existence & ``.git`` presence.
+ - State drift between ``WorkspaceConfig.last_commit_at_index`` and
+ each repo's ``.repowise/state.json``.
+ - MCP server registration (best-effort detection in claude config).
+ - ``--repair``: rebuild missing ``state.json``, drop dead workspace
+ entries (with a notice).
+ """
+ from repowise.core.workspace.update import (
+ read_state_commit,
+ sync_workspace_state_from_disk,
+ )
+
+ rows: list[tuple[str, str, str]] = []
+ issues: list[str] = []
+
+ dead_entries: list[str] = []
+ for entry in ws_config.repos:
+ abs_path = (ws_root / entry.path).resolve()
+
+ # Dir & git presence
+ if not abs_path.is_dir():
+ rows.append((entry.alias, "[red]MISSING[/red]", f"directory not found: {entry.path}"))
+ dead_entries.append(entry.alias)
+ issues.append(f"{entry.alias}: missing directory")
+ continue
+ if not (abs_path / ".git").exists():
+ rows.append((entry.alias, "[yellow]WARN[/yellow]", "not a git repo"))
+ issues.append(f"{entry.alias}: not a git repo")
+
+ # State drift
+ disk_commit = read_state_commit(abs_path)
+ cfg_commit = entry.last_commit_at_index
+ if disk_commit and cfg_commit and disk_commit != cfg_commit:
+ rows.append((
+ entry.alias,
+ "[yellow]DRIFT[/yellow]",
+ f"config={cfg_commit[:8]}, state.json={disk_commit[:8]}",
+ ))
+ issues.append(f"{entry.alias}: workspace config / state.json drift")
+ elif disk_commit and not cfg_commit:
+ rows.append((
+ entry.alias,
+ "[yellow]DRIFT[/yellow]",
+ f"workspace config missing last_commit_at_index (state.json has {disk_commit[:8]})",
+ ))
+ issues.append(f"{entry.alias}: workspace config missing commit pointer")
+ elif (abs_path / ".repowise").is_dir() and not disk_commit:
+ rows.append((
+ entry.alias, "[yellow]WARN[/yellow]",
+ "state.json missing or empty (run `repowise update`)",
+ ))
+ issues.append(f"{entry.alias}: missing state.json")
+ else:
+ rows.append((entry.alias, "[green]OK[/green]", entry.path))
+
+ table = Table(title="repowise Workspace Doctor")
+ table.add_column("Repo", style="cyan")
+ table.add_column("Status")
+ table.add_column("Detail")
+ for r in rows:
+ table.add_row(*r)
+ console.print(table)
+
+ # MCP server registration — best-effort, advisory only.
+ _check_mcp_registered(ws_root)
+
+ # --repair: sync the workspace config from disk and drop dead entries.
+ if repair:
+ changed = sync_workspace_state_from_disk(ws_root, ws_config)
+ if changed:
+ console.print(
+ f"[green]Repaired workspace config from disk for:[/green] "
+ f"{', '.join(changed)}"
+ )
+ if dead_entries:
+ console.print(
+ f"[yellow]Removing dead workspace entries:[/yellow] "
+ f"{', '.join(dead_entries)}"
+ )
+ for alias in dead_entries:
+ ws_config.remove_repo(alias)
+ ws_config.save(ws_root)
+ console.print("[green]Workspace config updated.[/green]")
+ if not changed and not dead_entries:
+ console.print("[green]No workspace-level repairs needed.[/green]")
+
+ return issues
+
+
+def _check_mcp_registered(ws_root: _DoctorPath) -> None:
+ """Best-effort check that a Claude MCP entry points at this workspace.
+
+ The check is advisory: a missing entry is not an error, since the user
+ may use the HTTP server or a different MCP client. We just print a
+ helpful hint so the workspace can be wired up if the user wants it.
+ """
+ import json as _json
+ import os as _os
+
+ candidates: list[_DoctorPath] = []
+ appdata = _os.environ.get("APPDATA")
+ if appdata:
+ candidates.append(_DoctorPath(appdata) / "Claude" / "claude_desktop_config.json")
+ home = _DoctorPath.home()
+ candidates.extend([
+ home / ".claude" / "claude_desktop_config.json",
+ home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",
+ home / ".config" / "Claude" / "claude_desktop_config.json",
+ ])
+
+ found_paths: list[str] = []
+ for cfg in candidates:
+ if not cfg.is_file():
+ continue
+ try:
+ data = _json.loads(cfg.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ servers = data.get("mcpServers", {}) or {}
+ for name, spec in servers.items():
+ args = spec.get("args", []) if isinstance(spec, dict) else []
+ arg_str = " ".join(str(a) for a in args)
+ if str(ws_root) in arg_str or str(ws_root.resolve()) in arg_str:
+ found_paths.append(f"{cfg.name}:{name}")
+
+ if found_paths:
+ console.print(
+ f" [dim]MCP: registered ({', '.join(found_paths)})[/dim]"
+ )
+ else:
+ console.print(
+ " [dim]MCP: no claude_desktop_config.json entry found — run "
+ "`repowise hook install` to register.[/dim]"
+ )
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index 3aee50324..ac8f65eed 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -4,7 +4,12 @@ from __future__ import annotations
import click
-from repowise.cli.helpers import console, find_workspace_root, resolve_repo_path
+from repowise.cli.helpers import (
+ console,
+ find_workspace_root,
+ resolve_command_target,
+ resolve_repo_path,
+)
@click.group("hook")
@@ -12,6 +17,21 @@ def hook_group() -> None:
"""Manage git hooks for automatic wiki sync."""
+def _hook_target(
+ path: str | None,
+ workspace: bool,
+ no_workspace: bool,
+):
+ """Resolve the target for a hook subcommand."""
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace,
+ no_workspace_flag=no_workspace,
+ )
+ target.notice(console, command="hook")
+ return target
+
+
@hook_group.command("install")
@click.argument("path", required=False, default=None)
@click.option(
@@ -19,28 +39,29 @@ def hook_group() -> None:
"-w",
is_flag=True,
default=False,
- help="Install hooks for all repos in the workspace.",
+ help="Force workspace mode (install hooks for every repo in the workspace).",
)
-def hook_install(path: str | None, workspace: bool) -> None:
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
+def hook_install(path: str | None, workspace: bool, no_workspace: bool) -> None:
"""Install a post-commit hook that auto-syncs after every commit."""
from repowise.cli.hooks import install
- repo_path = resolve_repo_path(path)
-
- if workspace:
- ws_root = find_workspace_root(repo_path)
- if ws_root is None:
- raise click.ClickException("No workspace found.")
-
- from repowise.core.workspace import WorkspaceConfig
+ target = _hook_target(path, workspace, no_workspace)
- ws_config = WorkspaceConfig.load(ws_root)
- for entry in ws_config.repos:
- abs_path = (ws_root / entry.path).resolve()
+ if target.is_workspace:
+ assert target.ws_root is not None and target.ws_config is not None
+ for entry in target.ws_config.repos:
+ abs_path = (target.ws_root / entry.path).resolve()
result = install(abs_path)
console.print(f" {entry.alias}: [green]{result}[/green]")
else:
- result = install(repo_path)
+ assert target.repo_path is not None
+ result = install(target.repo_path)
console.print(f"Post-commit hook: [green]{result}[/green]")
@@ -51,28 +72,29 @@ def hook_install(path: str | None, workspace: bool) -> None:
"-w",
is_flag=True,
default=False,
- help="Uninstall hooks from all repos in the workspace.",
+ help="Force workspace mode (uninstall hooks from every repo in the workspace).",
)
-def hook_uninstall(path: str | None, workspace: bool) -> None:
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
+def hook_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:
"""Remove the repowise post-commit hook."""
from repowise.cli.hooks import uninstall
- repo_path = resolve_repo_path(path)
-
- if workspace:
- ws_root = find_workspace_root(repo_path)
- if ws_root is None:
- raise click.ClickException("No workspace found.")
+ target = _hook_target(path, workspace, no_workspace)
- from repowise.core.workspace import WorkspaceConfig
-
- ws_config = WorkspaceConfig.load(ws_root)
- for entry in ws_config.repos:
- abs_path = (ws_root / entry.path).resolve()
+ if target.is_workspace:
+ assert target.ws_root is not None and target.ws_config is not None
+ for entry in target.ws_config.repos:
+ abs_path = (target.ws_root / entry.path).resolve()
result = uninstall(abs_path)
console.print(f" {entry.alias}: {result}")
else:
- result = uninstall(repo_path)
+ assert target.repo_path is not None
+ result = uninstall(target.repo_path)
console.print(f"Post-commit hook: {result}")
@@ -83,28 +105,29 @@ def hook_uninstall(path: str | None, workspace: bool) -> None:
"-w",
is_flag=True,
default=False,
- help="Check hooks for all repos in the workspace.",
+ help="Force workspace mode (report hooks for every repo in the workspace).",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
)
-def hook_status(path: str | None, workspace: bool) -> None:
+def hook_status(path: str | None, workspace: bool, no_workspace: bool) -> None:
"""Check if the repowise post-commit hook is installed."""
from repowise.cli.hooks import status
- repo_path = resolve_repo_path(path)
-
- if workspace:
- ws_root = find_workspace_root(repo_path)
- if ws_root is None:
- raise click.ClickException("No workspace found.")
-
- from repowise.core.workspace import WorkspaceConfig
+ target = _hook_target(path, workspace, no_workspace)
- ws_config = WorkspaceConfig.load(ws_root)
- for entry in ws_config.repos:
- abs_path = (ws_root / entry.path).resolve()
+ if target.is_workspace:
+ assert target.ws_root is not None and target.ws_config is not None
+ for entry in target.ws_config.repos:
+ abs_path = (target.ws_root / entry.path).resolve()
result = status(abs_path)
icon = "[green]✓[/green]" if result == "installed" else "[dim]✗[/dim]"
console.print(f" {icon} {entry.alias}: {result}")
else:
- result = status(repo_path)
+ assert target.repo_path is not None
+ result = status(target.repo_path)
icon = "[green]✓[/green]" if result == "installed" else "[dim]✗[/dim]"
console.print(f" {icon} post-commit: {result}")
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.py
index 7cdc821d1..c323056c9 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py
@@ -620,6 +620,10 @@ def _workspace_init(
total_symbols = 0
total_pages = 0
errors: list[tuple[str, str]] = []
+ # Per-repo docs outcome, surfaced in the completion panel so the user
+ # never has to guess why the web UI is missing pages for some repos.
+ # Maps alias -> (generated_count, skip_reason | None)
+ docs_outcomes: dict[str, tuple[int, str | None]] = {}
for i, repo in enumerate(selected, 1):
console.print(
@@ -666,9 +670,16 @@ def _workspace_init(
# Track per-repo whether the user declined cost so state.docs_enabled
# reflects the actual choice instead of the original init mode.
repo_docs_enabled = not index_only and provider is not None
+ skip_reason: str | None = None
+ if index_only:
+ skip_reason = "index-only mode"
+ elif provider is None:
+ skip_reason = "no provider configured"
if not index_only and provider is not None:
if dry_run:
console.print(" [yellow]Dry run — skipping generation for this repo.[/yellow]\n")
+ skip_reason = "dry run"
+ repo_docs_enabled = False
else:
try:
generated_pages = _run_workspace_generation(
@@ -691,11 +702,19 @@ def _workspace_init(
except CostGateDeclined:
repo_docs_enabled = False
result.generated_pages = []
+ skip_reason = "cost gate declined"
except Exception as gen_exc:
console.print(f" [yellow]Generation failed: {gen_exc}[/yellow]\n")
+ skip_reason = f"generation error: {gen_exc}"
+ repo_docs_enabled = False
else:
console.print()
+ docs_outcomes[repo.alias] = (
+ len(result.generated_pages or []),
+ None if repo_docs_enabled else skip_reason,
+ )
+
# Persist to repo-local DB
run_async(_persist_result(result, repo.path))
@@ -794,6 +813,35 @@ def _workspace_init(
)
console.print()
+ # Honest docs status — print a per-repo summary listing exactly which
+ # repos generated pages and which were skipped, so the user never has
+ # to discover empty Docs/Overview in the web UI on their own.
+ docs_skipped = [
+ (alias, reason) for alias, (count, reason) in docs_outcomes.items() if reason
+ ]
+ docs_generated = [
+ (alias, count) for alias, (count, reason) in docs_outcomes.items() if not reason
+ ]
+ if docs_outcomes:
+ console.print("[bold]Docs status[/bold]")
+ for alias, (count, reason) in docs_outcomes.items():
+ if reason:
+ console.print(
+ f" [yellow]✗[/yellow] {alias:<20} [yellow]skipped[/yellow] [dim]({reason})[/dim]"
+ )
+ else:
+ console.print(
+ f" [green]✓[/green] {alias:<20} [green]{count} pages[/green]"
+ )
+ if docs_skipped:
+ first = docs_skipped[0][0]
+ console.print()
+ console.print(
+ f" Run [bold]repowise update --repo {first} --docs[/bold] "
+ "to generate docs for a skipped repo."
+ )
+ console.print()
+
# Offer to install post-commit hooks
indexed_repos = [
repo for repo in selected
diff --git a/packages/cli/src/repowise/cli/commands/search_cmd.py b/packages/cli/src/repowise/cli/commands/search_cmd.py
index 35ec8718e..2fc0e8c33 100644
--- a/packages/cli/src/repowise/cli/commands/search_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/search_cmd.py
@@ -9,6 +9,7 @@ from repowise.cli.helpers import (
console,
ensure_repowise_dir,
get_db_url_for_repo,
+ resolve_command_target,
resolve_repo_path,
run_async,
)
@@ -24,22 +25,112 @@ from repowise.cli.helpers import (
help="Search mode.",
)
@click.option("--limit", type=int, default=10, help="Max results.")
+ "--repo",
+ "repo_alias",
+ default=None,
+ help="Workspace repo alias to search (implies workspace mode).",
+)
+ "--all",
+ "search_all",
+ is_flag=True,
+ default=False,
+ help="In workspace mode, fan out across every indexed repo.",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
def search_command(
query: str,
path: str | None,
mode: str,
limit: int,
+ repo_alias: str | None,
+ search_all: bool,
+ no_workspace: bool,
) -> None:
- """Search wiki pages by keyword, meaning, or symbol name."""
- repo_path = resolve_repo_path(path)
- ensure_repowise_dir(repo_path)
-
- if mode == "fulltext":
- _search_fulltext(repo_path, query, limit)
- elif mode == "semantic":
- _search_semantic(repo_path, query, limit)
- elif mode == "symbol":
- _search_symbol(repo_path, query, limit)
+ """Search wiki pages by keyword, meaning, or symbol name.
+
+ In workspace mode, defaults to the primary repo; pass --repo <alias>
+ for a specific one or --all to search across every indexed repo.
+ """
+ from pathlib import Path
+
+ target = resolve_command_target(
+ path=path,
+ no_workspace_flag=no_workspace,
+ repo_alias=repo_alias,
+ )
+ target.notice(console, command=f"search ({mode})")
+
+ repo_paths: list[Path] = []
+ if target.is_workspace:
+ assert target.ws_root is not None and target.ws_config is not None
+ if search_all:
+ repo_paths = [
+ (target.ws_root / e.path).resolve() for e in target.ws_config.repos
+ ]
+ elif target.repo_filter is not None:
+ picked = target.resolve_repo_alias(target.repo_filter)
+ if picked is None:
+ raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")
+ repo_paths = [picked]
+ else:
+ primary = target.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ repo_paths = [primary]
+ else:
+ assert target.repo_path is not None
+ repo_paths = [target.repo_path]
+
+ repo_paths = [p for p in repo_paths if (p / ".repowise").is_dir()]
+ if not repo_paths:
+ console.print("[yellow]No indexed repos to search. Run 'repowise init' first.[/yellow]")
+ return
+
+ if len(repo_paths) == 1:
+ repo_path = repo_paths[0]
+ ensure_repowise_dir(repo_path)
+ if mode == "fulltext":
+ _search_fulltext(repo_path, query, limit)
+ elif mode == "semantic":
+ _search_semantic(repo_path, query, limit)
+ elif mode == "symbol":
+ _search_symbol(repo_path, query, limit)
+ return
+
+ # Multi-repo fan-out — gather, sort by score, render once.
+ all_results: list = []
+ for rp in repo_paths:
+ try:
+ if mode == "fulltext":
+ results = _collect_fulltext(rp, query, limit)
+ elif mode == "semantic":
+ results = _collect_semantic(rp, query, limit)
+ else: # symbol
+ results = _collect_symbol(rp, query, limit)
+ except Exception as exc:
+ console.print(f"[yellow]search failed for {rp.name}: {exc}[/yellow]")
+ continue
+ for r in results:
+ all_results.append((rp.name, r))
+
+ if not all_results:
+ console.print("[yellow]No results across the workspace.[/yellow]")
+ return
+
+ if mode == "symbol":
+ _render_symbol_rows(all_results, query, limit, multi=True)
+ else:
+ # Sort by score desc, slice to limit
+ all_results.sort(key=lambda pair: getattr(pair[1], "score", 0.0), reverse=True)
+ all_results = all_results[:limit]
+ _display_results_multi(all_results, f"{mode.capitalize()} search: '{query}' (workspace)")
def _search_fulltext(repo_path, query: str, limit: int) -> None:
@@ -164,3 +255,133 @@ def _display_results(results, title: str) -> None:
console.print("[yellow]No results found.[/yellow]")
else:
console.print(table)
+
+
+# ---------------------------------------------------------------------------
+# Multi-repo (workspace fan-out) helpers
+# ---------------------------------------------------------------------------
+
+
+def _collect_fulltext(repo_path, query: str, limit: int):
+ async def _run():
+ from repowise.core.persistence import FullTextSearch, create_engine
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ fts = FullTextSearch(engine)
+ results = await fts.search(query, limit=limit)
+ await engine.dispose()
+ return results
+
+ return run_async(_run())
+
+
+def _collect_semantic(repo_path, query: str, limit: int):
+ async def _run():
+ from pathlib import Path
+
+ from repowise.core.persistence import FullTextSearch, MockEmbedder, create_engine
+
+ lance_dir = Path(repo_path) / ".repowise" / "lancedb"
+ if lance_dir.exists():
+ try:
+ from repowise.cli.commands.init_cmd import _resolve_embedder
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+
+ embedder_name = _resolve_embedder(None)
+ if embedder_name == "gemini":
+ from repowise.core.providers.embedding.gemini import GeminiEmbedder
+
+ embedder = GeminiEmbedder()
+ elif embedder_name == "openai":
+ from repowise.core.providers.embedding.openai import OpenAIEmbedder
+
+ embedder = OpenAIEmbedder()
+ else:
+ embedder = MockEmbedder()
+ store = LanceDBVectorStore(str(lance_dir), embedder=embedder)
+ results = await store.search(query, limit=limit)
+ await store.close()
+ return results
+ except Exception:
+ pass
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ fts = FullTextSearch(engine)
+ results = await fts.search(query, limit=limit)
+ await engine.dispose()
+ return results
+
+ return run_async(_run())
+
+
+def _collect_symbol(repo_path, query: str, limit: int):
+ async def _run():
+ from sqlalchemy import text as sa_text
+
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ result = await session.execute(
+ sa_text(
+ "SELECT name, qualified_name, kind, file_path, start_line "
+ "FROM wiki_symbols WHERE name LIKE :pattern LIMIT :limit"
+ ),
+ {"pattern": f"%{query}%", "limit": limit},
+ )
+ rows = result.fetchall()
+ await engine.dispose()
+ return rows
+
+ return run_async(_run())
+
+
+def _display_results_multi(pairs, title: str) -> None:
+ """Render fulltext/semantic results when fanned out across multiple repos."""
+ table = Table(title=title)
+ table.add_column("Score", justify="right", style="green")
+ table.add_column("Repo", style="magenta")
+ table.add_column("Title", style="cyan")
+ table.add_column("Type")
+ table.add_column("Path")
+ table.add_column("Snippet", max_width=50)
+
+ for repo_name, r in pairs:
+ table.add_row(
+ f"{r.score:.3f}",
+ repo_name,
+ r.title or "",
+ r.page_type or "",
+ r.target_path or "",
+ (r.snippet or "")[:50],
+ )
+ console.print(table)
+
+
+def _render_symbol_rows(pairs, query: str, limit: int, *, multi: bool) -> None:
+ """Render symbol rows; ``pairs`` is a list of ``(repo_name, row)`` tuples."""
+ title = f"Symbol search: '{query}' (workspace)" if multi else f"Symbol search: '{query}'"
+ table = Table(title=title)
+ table.add_column("Name", style="cyan")
+ if multi:
+ table.add_column("Repo", style="magenta")
+ table.add_column("Qualified Name")
+ table.add_column("Kind")
+ table.add_column("File")
+ table.add_column("Line", justify="right")
+
+ for repo_name, row in pairs[:limit]:
+ cells = [str(row[0])]
+ if multi:
+ cells.append(repo_name)
+ cells += [str(row[1]), str(row[2]), str(row[3]), str(row[4])]
+ table.add_row(*cells)
+
+ if not pairs:
+ console.print(f"[yellow]No symbols matching '{query}'[/yellow]")
+ else:
+ console.print(table)
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 70fa1d4d9..85abdc7b9 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -9,11 +9,13 @@ import click
from rich.table import Table
from repowise.cli.helpers import (
+ CommandTarget,
console,
find_workspace_root,
get_db_url_for_repo,
get_repowise_dir,
load_state,
+ resolve_command_target,
resolve_repo_path,
run_async,
)
@@ -84,6 +86,49 @@ def _query_repo_counts(repo_path: Path) -> tuple[int, int]:
return 0, 0
+def _query_page_count(repo_path: Path) -> int:
+ """Return the number of generated wiki pages for a repo, or 0."""
+
+ async def _query() -> int:
+ from sqlalchemy import func as sa_func
+ from sqlalchemy import select as sa_select
+
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.models import Page, Repository
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ sf = create_session_factory(engine)
+ try:
+ async with get_session(sf) as session:
+ repo_result = await session.execute(
+ sa_select(Repository.id).where(Repository.local_path == str(repo_path))
+ )
+ repo_id = repo_result.scalar_one_or_none()
+ if repo_id is None:
+ return 0
+ count_result = await session.execute(
+ sa_select(sa_func.count())
+ .select_from(Page)
+ .where(Page.repository_id == repo_id)
+ )
+ return int(count_result.scalar_one() or 0)
+ finally:
+ await engine.dispose()
+
+ db_path = get_repowise_dir(repo_path) / "wiki.db"
+ if not db_path.exists():
+ return 0
+ try:
+ return run_async(_query())
+ except Exception:
+ return 0
+
+
def _format_relative_time(iso_timestamp: str | None) -> str:
"""Format an ISO 8601 timestamp as a relative time string."""
if not iso_timestamp:
@@ -108,30 +153,30 @@ def _format_relative_time(iso_timestamp: str | None) -> str:
return iso_timestamp[:10] if len(iso_timestamp) >= 10 else iso_timestamp
-def _workspace_status(start_path: Path) -> None:
+def _workspace_status(target: "CommandTarget") -> None:
"""Show status for all repos in a workspace."""
- from repowise.cli.helpers import get_head_commit as _get_head
- from repowise.core.workspace import WorkspaceConfig, check_repo_staleness
+ from repowise.core.workspace import check_repo_staleness
- ws_root = find_workspace_root(start_path)
- if ws_root is None:
+ ws_root = target.ws_root
+ ws_config = target.ws_config
+ if ws_root is None or ws_config is None:
console.print(
"[yellow]No .repowise-workspace.yaml found. "
"Run 'repowise init <workspace-dir>' first.[/yellow]"
)
return
- ws_config = WorkspaceConfig.load(ws_root)
-
table = Table(title=f"Workspace: {ws_root.name}")
table.add_column("Repo", style="cyan", min_width=16)
table.add_column("Files", justify="right")
table.add_column("Symbols", justify="right")
+ table.add_column("Docs", justify="right")
table.add_column("Indexed", style="dim")
table.add_column("HEAD", style="dim")
table.add_column("Status")
total_stale = 0
+ no_docs: list[str] = [] # aliases with index but no generated pages
for entry in ws_config.repos:
abs_path = (ws_root / entry.path).resolve()
@@ -141,11 +186,25 @@ def _workspace_status(start_path: Path) -> None:
label += " [bold](primary)[/bold]"
if not repowise_dir.exists():
- table.add_row(label, "-", "-", "-", "-", "[yellow]not indexed[/yellow]")
+ table.add_row(label, "-", "-", "-", "-", "-", "[yellow]not indexed[/yellow]")
continue
file_count, symbol_count = _query_repo_counts(abs_path)
indexed_ago = _format_relative_time(entry.indexed_at)
+ page_count = _query_page_count(abs_path)
+ docs_state = load_state(abs_path)
+ docs_enabled = docs_state.get("docs_enabled")
+
+ # Render the Docs column in plain English so the user instantly
+ # knows whether the LLM-generated wiki exists for this repo.
+ if page_count > 0:
+ docs_cell = f"[green]{page_count}[/green]"
+ elif docs_enabled is False:
+ docs_cell = "[yellow]skipped[/yellow]"
+ no_docs.append(entry.alias)
+ else:
+ docs_cell = "[yellow]0[/yellow]"
+ no_docs.append(entry.alias)
# Check staleness by comparing stored commit to current HEAD
stored_commit = entry.last_commit_at_index
@@ -164,7 +223,13 @@ def _workspace_status(start_path: Path) -> None:
status = "[yellow]empty[/yellow]"
table.add_row(
- label, str(file_count), f"{symbol_count:,}", indexed_ago, head_short, status
+ label,
+ str(file_count),
+ f"{symbol_count:,}",
+ docs_cell,
+ indexed_ago,
+ head_short,
+ status,
)
console.print(table)
@@ -177,6 +242,20 @@ def _workspace_status(start_path: Path) -> None:
summary += f". [yellow]{total_stale} stale[/yellow]"
console.print(summary)
+ # Honest "no docs" tip — print the exact remediation command so the
+ # user never has to dig through docs to figure out what to do next.
+ if no_docs:
+ console.print()
+ console.print(
+ f"[yellow]Note:[/yellow] {len(no_docs)} repo(s) have no generated docs: "
+ f"[cyan]{', '.join(no_docs)}[/cyan]"
+ )
+ first = no_docs[0]
+ console.print(
+ f" Run [bold]repowise update --repo {first} --docs[/bold] "
+ "to generate them (requires an LLM provider)."
+ )
+
# ---------------------------------------------------------------------------
# CLI command
@@ -190,16 +269,32 @@ def _workspace_status(start_path: Path) -> None:
"-w",
is_flag=True,
default=False,
- help="Show status for all repos in the workspace.",
+ help="Force workspace mode (show all repos in the workspace).",
)
-def status_command(path: str | None, workspace: bool) -> None:
- """Show wiki sync state and page statistics."""
- repo_path = resolve_repo_path(path)
-
- if workspace:
- _workspace_status(repo_path)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
+def status_command(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Show wiki sync state and page statistics.
+
+ Auto-detects workspace mode when invoked from a workspace root.
+ """
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace,
+ no_workspace_flag=no_workspace,
+ )
+ target.notice(console, command="status")
+
+ if target.is_workspace:
+ _workspace_status(target)
return
+ repo_path = target.repo_path
+ assert repo_path is not None
repowise_dir = get_repowise_dir(repo_path)
if not repowise_dir.exists():
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index a488da339..9adb920c6 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -8,6 +8,7 @@ import click
from rich.table import Table
from repowise.cli.helpers import (
+ CommandTarget,
acquire_update_lock,
console,
ensure_repowise_dir,
@@ -16,6 +17,7 @@ from repowise.cli.helpers import (
load_config,
load_state,
release_update_lock,
+ resolve_command_target,
resolve_provider,
resolve_repo_path,
run_async,
@@ -76,24 +78,24 @@ def _resolve_index_only_mode(
def _workspace_update(
- start_path: "Path",
+ target: "CommandTarget",
*,
- repo_alias: str | None = None,
dry_run: bool = False,
) -> None:
- """Update stale repos in a workspace."""
- from pathlib import Path
+ """Update stale repos in a workspace.
- from repowise.core.workspace import WorkspaceConfig, check_repo_staleness, update_workspace
-
- ws_root = find_workspace_root(start_path)
- if ws_root is None:
- raise click.ClickException(
- "No .repowise-workspace.yaml found. "
- "Run 'repowise init <workspace-dir>' first."
- )
+ Takes a resolved :class:`CommandTarget` so the caller has full control
+ over how the workspace was located (auto-detected vs explicit flag).
+ """
+ from repowise.core.workspace import check_repo_staleness, update_workspace
- ws_config = WorkspaceConfig.load(ws_root)
+ ws_root = target.ws_root
+ ws_config = target.ws_config
+ repo_alias = target.repo_filter
+ if ws_root is None or ws_config is None:
+ # Defensive: callers should always pass a workspace-mode target,
+ # but guard against misuse so the error message is clear.
+ raise click.ClickException("_workspace_update called without a workspace target.")
# Show staleness summary first
console.print(f"[bold]repowise update[/bold] — workspace: {ws_root.name}")
@@ -185,13 +187,19 @@ def _workspace_update(
"-w",
is_flag=True,
default=False,
- help="Update all stale repos in the workspace.",
+ help="Force workspace mode (update all stale repos in the workspace).",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
)
@click.option(
"--repo",
"repo_alias",
default=None,
- help="Update only this repo alias within the workspace.",
+ help="Update only this repo alias within the workspace (implies --workspace).",
)
@click.option(
"--index-only",
@@ -223,20 +231,36 @@ def update_command(
cascade_budget: int | None,
dry_run: bool,
workspace: bool,
+ no_workspace: bool,
repo_alias: str | None,
index_only: bool = False,
docs_flag: bool | None = None,
concurrency: int = 5,
) -> None:
- """Incrementally update wiki pages for files changed since last sync."""
+ """Incrementally update wiki pages for files changed since last sync.
+
+ Auto-detects workspace mode when invoked from a workspace root or when a
+ workspace exists upstream of the working directory. Use --no-workspace to
+ force single-repo mode and --workspace to force workspace mode.
+ """
start = time.monotonic()
- repo_path = resolve_repo_path(path)
- # --- Workspace mode ---
- if workspace or repo_alias:
- _workspace_update(repo_path, repo_alias=repo_alias, dry_run=dry_run)
+ # --- Resolve target up front (single repo or workspace) ---
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace,
+ no_workspace_flag=no_workspace,
+ repo_alias=repo_alias,
+ )
+ target.notice(console, command="update")
+
+ if target.is_workspace:
+ _workspace_update(target, dry_run=dry_run)
return
+ # --- Single-repo path from here on. ---
+ repo_path = target.repo_path
+ assert repo_path is not None # single mode always sets repo_path
ensure_repowise_dir(repo_path)
# Load saved API keys from .repowise/.env (won't overwrite existing env vars)
@@ -249,8 +273,21 @@ def update_command(
head = get_head_commit(repo_path)
if base_ref is None:
+ # Helpful diagnostic when the user landed here from a workspace
+ # directory that was never indexed as a single repo. The auto-detect
+ # path normally catches this earlier, but --no-workspace or an
+ # explicit path can still route us here.
+ hint = ""
+ upstream_ws = find_workspace_root(repo_path)
+ if upstream_ws is not None:
+ hint = (
+ f"\nA workspace was detected at {upstream_ws}. "
+ "Did you mean: repowise update --workspace?"
+ )
raise click.ClickException(
- "No previous sync found. Run 'repowise init' first or pass --since."
+ f"No previous sync found for {repo_path}. "
+ "Run 'repowise init' there first, or pass --since <ref>."
+ + hint
)
if head and head == base_ref:
diff --git a/packages/cli/src/repowise/cli/commands/watch_cmd.py b/packages/cli/src/repowise/cli/commands/watch_cmd.py
index e58e3fb73..784049585 100644
--- a/packages/cli/src/repowise/cli/commands/watch_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/watch_cmd.py
@@ -12,6 +12,7 @@ from repowise.cli.helpers import (
console,
ensure_repowise_dir,
find_workspace_root,
+ resolve_command_target,
resolve_repo_path,
run_async,
)
@@ -244,7 +245,13 @@ def _watch_workspace(
"-w",
is_flag=True,
default=False,
- help="Watch all repos in the workspace.",
+ help="Force workspace mode (watch all repos in the workspace).",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
)
def watch_command(
path: str | None,
@@ -252,17 +259,22 @@ def watch_command(
model: str | None,
debounce_ms: int,
workspace: bool,
+ no_workspace: bool,
) -> None:
- """Watch for file changes and auto-update wiki pages."""
- repo_path = resolve_repo_path(path)
-
- if workspace:
- ws_root = find_workspace_root(repo_path)
- if ws_root is None:
- raise click.ClickException(
- "No .repowise-workspace.yaml found. "
- "Run 'repowise init <workspace-dir>' first."
- )
- _watch_workspace(ws_root, debounce_ms)
+ """Watch for file changes and auto-update wiki pages.
+
+ Auto-detects workspace mode when invoked from a workspace root.
+ """
+ target = resolve_command_target(
+ path=path,
+ workspace_flag=workspace,
+ no_workspace_flag=no_workspace,
+ )
+ target.notice(console, command="watch")
+
+ if target.is_workspace:
+ assert target.ws_root is not None
+ _watch_workspace(target.ws_root, debounce_ms)
else:
- _watch_single_repo(repo_path, provider_name, model, debounce_ms)
+ assert target.repo_path is not None
+ _watch_single_repo(target.repo_path, provider_name, model, debounce_ms)
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 02dce318d..b95eed4e6 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -213,16 +213,45 @@ def _format_relative_time(iso_timestamp: str | None) -> str:
@click.argument("path")
@click.option("--alias", default=None, help="Short name for the repo (default: directory name).")
@click.option(
- "--index",
+ "--index/--no-index",
"run_index",
- is_flag=True,
- default=False,
- help="Run indexing on the repo after adding it.",
+ default=True,
+ show_default=True,
+ help="Run full indexing on the repo after adding it (graph, git, dead code).",
)
-def workspace_add(path: str, alias: str | None, run_index: bool) -> None:
- """Add a repo to the workspace.
+ "--docs/--no-docs",
+ "run_docs",
+ default=None,
+ help=(
+ "Generate LLM documentation pages after indexing. Defaults to ON when a "
+ "provider is configured (in the primary repo's config or via env), OFF "
+ "otherwise. Skipped silently when --no-index is passed."
+ ),
+)
[email protected]("--provider", "provider_name", default=None, help="LLM provider name (overrides primary's).")
[email protected]("--model", default=None, help="Model identifier (overrides primary's).")
[email protected]("--concurrency", type=int, default=5, help="Max concurrent LLM calls during doc generation.")
+def workspace_add(
+ path: str,
+ alias: str | None,
+ run_index: bool,
+ run_docs: bool | None,
+ provider_name: str | None,
+ model: str | None,
+ concurrency: int,
+) -> None:
+ """Add a repo to the workspace and (by default) index + generate docs for it.
PATH is a relative or absolute path to a git repository.
+
+ Defaults are designed so the repo immediately appears with complete
+ intelligence in the web UI and MCP server:
+ - ``--index`` (default ON) runs the full ingestion pipeline
+ - ``--docs`` (auto) generates wiki pages when a provider is
+ available, otherwise skips with a notice
+ Use ``--no-index`` to only register the entry without indexing, or
+ ``--no-docs`` to index without LLM generation.
"""
from repowise.core.workspace.config import RepoEntry
@@ -267,8 +296,87 @@ def workspace_add(path: str, alias: str | None, run_index: bool) -> None:
ws_config.save(ws_root)
console.print(f"[green]✓[/green] Added repo '{alias}' ({rel_path}) to workspace.")
- if run_index:
- _run_index_for_repo(repo_path, alias, ws_root, ws_config)
+ if not run_index:
+ console.print(
+ "[yellow]Skipping index[/yellow] (--no-index). "
+ f"Run [bold]repowise update --repo {alias}[/bold] to index later."
+ )
+ return
+
+ # Resolve whether docs should run.
+ resolved_docs, docs_skip_reason = _resolve_docs_flag(
+ run_docs=run_docs,
+ provider_name=provider_name,
+ ws_root=ws_root,
+ ws_config=ws_config,
+ )
+
+ _run_index_for_repo(
+ repo_path,
+ alias,
+ ws_root,
+ ws_config,
+ generate_docs=resolved_docs,
+ provider_name=provider_name,
+ model=model,
+ concurrency=concurrency,
+ docs_skip_reason=docs_skip_reason,
+ )
+
+
+def _resolve_docs_flag(
+ *,
+ run_docs: bool | None,
+ provider_name: str | None,
+ ws_root: Path,
+ ws_config: "WorkspaceConfig", # type: ignore[name-defined]
+) -> tuple[bool, str | None]:
+ """Decide whether ``workspace add`` should generate docs by default.
+
+ Priority:
+ 1. Explicit ``--docs`` or ``--no-docs``.
+ 2. ``--provider`` flag forces docs ON.
+ 3. Primary repo's ``.repowise/config.yaml`` has a provider → docs ON,
+ reusing the same provider settings.
+ 4. ``REPOWISE_PROVIDER`` env var or detectable API key → docs ON.
+ 5. Otherwise docs OFF, with a skip reason for the completion notice.
+ """
+ if run_docs is True:
+ return True, None
+ if run_docs is False:
+ return False, "--no-docs flag"
+ if provider_name is not None:
+ return True, None
+
+ # Check primary repo config
+ from repowise.cli.helpers import load_config
+
+ primary = ws_config.get_primary()
+ if primary is not None:
+ primary_path = (ws_root / primary.path).resolve()
+ cfg = load_config(primary_path)
+ if cfg.get("provider"):
+ return True, None
+
+ # Env-detected provider
+ import os as _os
+
+ env_provider = _os.environ.get("REPOWISE_PROVIDER")
+ if env_provider:
+ return True, None
+ for key in (
+ "ANTHROPIC_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENROUTER_API_KEY",
+ "GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "DEEPSEEK_API_KEY",
+ "OLLAMA_BASE_URL",
+ ):
+ if _os.environ.get(key):
+ return True, None
+
+ return False, "no provider configured"
def _run_index_for_repo(
@@ -276,17 +384,78 @@ def _run_index_for_repo(
alias: str,
ws_root: Path,
ws_config: "WorkspaceConfig", # type: ignore[name-defined]
+ *,
+ generate_docs: bool = False,
+ provider_name: str | None = None,
+ model: str | None = None,
+ concurrency: int = 5,
+ docs_skip_reason: str | None = None,
) -> None:
- """Run the ingestion pipeline on a single repo and update workspace config."""
+ """Run the ingestion pipeline on a single repo, optionally with LLM docs.
+
+ Updates the workspace config entry, persists results to the per-repo
+ DB, writes ``.repowise/state.json`` (so ``repowise update`` knows the
+ base commit), saves provider/model into ``config.yaml`` when docs ran,
+ and re-runs cross-repo hooks so contracts/co-changes are fresh.
+ """
from datetime import datetime, timezone
+ from repowise.cli.helpers import (
+ ensure_repowise_dir,
+ get_head_commit,
+ resolve_provider,
+ save_config,
+ save_state,
+ )
from repowise.core.pipeline.orchestrator import run_pipeline
from repowise.core.workspace.update import run_cross_repo_hooks
console.print(f" Indexing [cyan]{alias}[/cyan]…")
- async def _do_index() -> None:
- result = await run_pipeline(repo_path, generate_docs=False)
+ # Reuse the primary repo's provider/embedder/exclude settings when the
+ # caller hasn't overridden them.
+ primary = ws_config.get_primary()
+ primary_cfg: dict = {}
+ if primary is not None:
+ from repowise.cli.helpers import load_config as _load_cfg
+
+ primary_cfg = _load_cfg((ws_root / primary.path).resolve())
+
+ effective_provider = provider_name or primary_cfg.get("provider")
+ effective_model = model or primary_cfg.get("model")
+ embedder_name = primary_cfg.get("embedder", "mock")
+ exclude_patterns = list(primary_cfg.get("exclude_patterns") or [])
+ commit_limit = primary_cfg.get("commit_limit", 500)
+
+ # Resolve the provider once. If docs were requested but provider
+ # resolution fails, fall back to index-only with a loud notice instead
+ # of silently producing an empty wiki.
+ provider = None
+ if generate_docs:
+ try:
+ provider = resolve_provider(
+ effective_provider, effective_model, repo_path=repo_path,
+ )
+ console.print(
+ f" Provider: [cyan]{provider.provider_name}[/cyan] / "
+ f"Model: [cyan]{provider.model_name}[/cyan]"
+ )
+ except Exception as exc:
+ console.print(
+ f" [yellow]Provider unavailable ({exc}); skipping docs.[/yellow]"
+ )
+ generate_docs = False
+ docs_skip_reason = f"provider failure: {exc}"
+
+ ensure_repowise_dir(repo_path)
+
+ async def _do_index() -> tuple[int, int, int]:
+ result = await run_pipeline(
+ repo_path,
+ commit_depth=int(commit_limit) if commit_limit else 500,
+ exclude_patterns=exclude_patterns or None,
+ generate_docs=False,
+ )
from repowise.core.persistence import (
create_engine,
@@ -302,30 +471,179 @@ def _run_index_for_repo(
engine = create_engine(url)
await init_db(engine)
sf = create_session_factory(engine)
+ page_count = 0
async with get_session(sf) as session:
repo = await upsert_repository(
session, name=result.repo_name, local_path=str(repo_path)
)
await persist_pipeline_result(result, session, repo.id)
+
await engine.dispose()
+ return result.file_count, result.symbol_count, page_count
- # Update workspace entry timestamps
- entry = ws_config.get_repo(alias)
- if entry is not None:
- entry.indexed_at = datetime.now(timezone.utc).isoformat()
- from repowise.cli.helpers import get_head_commit
+ try:
+ file_count, symbol_count, _ = run_async(_do_index())
+ console.print(
+ f" [green]✓[/green] {file_count} files, {symbol_count:,} symbols"
+ )
+ except Exception as exc:
+ console.print(f"[yellow]Warning:[/yellow] Indexing failed for '{alias}': {exc}")
+ return
- entry.last_commit_at_index = get_head_commit(repo_path)
- ws_config.save(ws_root)
+ # Run LLM doc generation through the existing single-repo init pathway
+ # so we get cost gating, cascading, and full parity with `repowise init`.
+ generated_pages = 0
+ if generate_docs and provider is not None:
+ try:
+ generated_pages = _generate_docs_for_added_repo(
+ repo_path=repo_path,
+ provider=provider,
+ embedder_name=embedder_name,
+ concurrency=concurrency,
+ exclude_patterns=exclude_patterns,
+ )
+ console.print(f" [green]✓[/green] Generated {generated_pages} pages")
+ except Exception as exc:
+ console.print(f" [yellow]Doc generation failed: {exc}[/yellow]")
+ docs_skip_reason = f"generation error: {exc}"
+
+ # Persist state.json so `repowise update` has a baseline commit.
+ head = get_head_commit(repo_path)
+ state: dict = {
+ "last_sync_commit": head,
+ "total_pages": generated_pages,
+ "docs_enabled": bool(generate_docs and provider is not None),
+ }
+ if generate_docs and provider is not None:
+ state["provider"] = provider.provider_name
+ state["model"] = provider.model_name
+ save_state(repo_path, state)
+
+ # Persist provider settings into the added repo's config.yaml so future
+ # `repowise update` runs don't have to re-prompt.
+ if generate_docs and provider is not None:
+ save_config(
+ repo_path,
+ provider.provider_name,
+ provider.model_name,
+ embedder_name,
+ exclude_patterns=exclude_patterns or None,
+ commit_limit=int(commit_limit) if commit_limit else None,
+ )
- # Cross-repo hooks
- await run_cross_repo_hooks(ws_config, ws_root, [alias])
+ # Update workspace config entry
+ entry = ws_config.get_repo(alias)
+ if entry is not None:
+ entry.indexed_at = datetime.now(timezone.utc).isoformat()
+ entry.last_commit_at_index = head
+ ws_config.save(ws_root)
+ # Cross-repo hooks — best effort; never fail the add command.
try:
- run_async(_do_index())
- console.print(f"[green]✓[/green] Indexed '{alias}' successfully.")
+ run_async(run_cross_repo_hooks(ws_config, ws_root, [alias]))
except Exception as exc:
- console.print(f"[yellow]Warning:[/yellow] Indexing failed for '{alias}': {exc}")
+ console.print(f"[yellow]Cross-repo hook update skipped: {exc}[/yellow]")
+
+ # Honest completion notice — exact remediation command for the
+ # docs-skipped case.
+ if not state["docs_enabled"]:
+ reason = docs_skip_reason or "docs disabled"
+ console.print(
+ f"\n[yellow]Note:[/yellow] '{alias}' indexed without docs ({reason})."
+ )
+ console.print(
+ f" Run [bold]repowise update --repo {alias} --docs[/bold] "
+ "to generate documentation."
+ )
+
+
+def _generate_docs_for_added_repo(
+ *,
+ repo_path: Path,
+ provider: object,
+ embedder_name: str,
+ concurrency: int,
+ exclude_patterns: list[str],
+) -> int:
+ """Generate wiki pages for a newly-added workspace repo.
+
+ Lives in this module (rather than importing from init_cmd) to avoid
+ circular imports — init_cmd is large and pulls in CLI UI helpers that
+ would explode the import graph. Uses the same generation primitives
+ as `repowise init`.
+ """
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.generation import (
+ ContextAssembler,
+ GenerationConfig,
+ PageGenerator,
+ )
+ from repowise.core.ingestion import (
+ ASTParser,
+ FileTraverser,
+ GraphBuilder,
+ )
+ from repowise.core.persistence import (
+ FullTextSearch,
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_page_from_generated,
+ upsert_repository,
+ )
+
+ # Re-parse files. The pipeline persisted graph data already; for doc
+ # generation we need parsed files in-memory.
+ traverser = FileTraverser(repo_path, extra_exclude_patterns=exclude_patterns or None)
+ file_infos = list(traverser.traverse())
+ repo_structure = traverser.get_repo_structure()
+ parser = ASTParser()
+ graph_builder = GraphBuilder()
+ parsed_files = []
+ source_map: dict = {}
+ for fi in file_infos:
+ try:
+ source = Path(fi.abs_path).read_bytes()
+ parsed = parser.parse_file(fi, source)
+ parsed_files.append(parsed)
+ source_map[fi.path] = source
+ graph_builder.add_file(parsed)
+ except Exception:
+ continue
+ graph_builder.build()
+
+ config = GenerationConfig(max_concurrency=concurrency)
+ assembler = ContextAssembler(config)
+ generator = PageGenerator(provider, assembler, config, language=config.language)
+
+ async def _do() -> int:
+ pages = await generator.generate_all(
+ parsed_files,
+ source_map,
+ graph_builder,
+ repo_structure,
+ repo_path.name,
+ )
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session, name=repo_path.name, local_path=str(repo_path),
+ )
+ for p in pages:
+ await upsert_page_from_generated(session, p, repo.id)
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+ for p in pages:
+ await fts.index(p.page_id, p.title, p.content)
+ await engine.dispose()
+ return len(pages)
+
+ return run_async(_do())
# ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 5da955232..7dd4461d3 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -5,8 +5,10 @@ from __future__ import annotations
import asyncio
import json
import os
+import sys
+from dataclasses import dataclass
from pathlib import Path
-from typing import Any, TypeVar
+from typing import Any, Literal, TypeVar
import click
from rich.console import Console
@@ -513,3 +515,303 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:
)
return warnings
+
+
+# ---------------------------------------------------------------------------
+# Command target resolution — auto-detect single-repo vs workspace mode
+# ---------------------------------------------------------------------------
+#
+# Many CLI commands (``update``, ``status``, ``watch``, ``generate-claude-md``,
+# ``doctor``, ``costs``, ``search``, ``dead-code``, ``decision``, hooks) need
+# to decide whether the user means "this one repo" or "the surrounding
+# workspace". Historically each command did its own ad-hoc detection (or
+# none), which produced the Phase A bug where ``repowise update`` from a
+# workspace root errored with a misleading "No previous sync found" message
+# and left a stray ``.repowise/`` directory behind.
+#
+# ``resolve_command_target`` is the single source of truth. Every command
+# should call it before doing any work. See ``docs/WORKSPACE_ROBUSTNESS.md``
+# for the UX principles.
+
+
+@dataclass
+class CommandTarget:
+ """Resolved target for a CLI invocation — single repo or workspace.
+
+ Attributes:
+ mode: ``"single"`` or ``"workspace"``.
+ repo_path: For single mode, the resolved repo path. For workspace
+ mode, ``None`` (use ``ws_root`` + ``ws_config`` instead, or the
+ ``primary_path()`` helper).
+ ws_root: Workspace root path. Set in workspace mode; also set in
+ single mode when a workspace exists *upstream* of the chosen
+ repo, so commands can surface that context.
+ ws_config: Loaded workspace config (workspace mode only).
+ repo_filter: Optional alias filter for workspace mode (e.g.
+ ``--repo backend``). ``None`` means "all repos".
+ reason: Short human-readable explanation of why this target was
+ chosen. Surfaced via :meth:`notice`.
+ auto_detected: ``True`` when the workspace context was inferred
+ rather than requested via an explicit flag. Used to decide
+ whether to print a transparency notice.
+ """
+
+ mode: Literal["single", "workspace"]
+ repo_path: Path | None = None
+ ws_root: Path | None = None
+ ws_config: Any | None = None # WorkspaceConfig (avoid hard import here)
+ repo_filter: str | None = None
+ reason: str = ""
+ auto_detected: bool = False
+
+ # ------------------------------------------------------------------
+ # Convenience accessors
+ # ------------------------------------------------------------------
+
+ @property
+ def is_workspace(self) -> bool:
+ return self.mode == "workspace"
+
+ def primary_path(self) -> Path | None:
+ """Return the workspace's primary repo path, if known."""
+ if self.ws_config is None or self.ws_root is None:
+ return None
+ primary = self.ws_config.get_primary()
+ if primary is None:
+ return None
+ return (self.ws_root / primary.path).resolve()
+
+ def resolve_repo_alias(self, alias: str | None) -> Path | None:
+ """Resolve an alias to an absolute repo path within the workspace.
+
+ Returns ``None`` if the workspace is not loaded or the alias is
+ unknown. Used by commands that accept ``--repo <alias>``.
+ """
+ if self.ws_config is None or self.ws_root is None or alias is None:
+ return None
+ entry = self.ws_config.get_repo(alias)
+ if entry is None:
+ return None
+ return (self.ws_root / entry.path).resolve()
+
+ # ------------------------------------------------------------------
+ # Notice rendering — every command should call this so users always
+ # know which mode they ended up in.
+ # ------------------------------------------------------------------
+
+ def notice(self, console_obj: Console, *, command: str = "") -> None:
+ """Print a one-line transparency notice describing the chosen target.
+
+ - Always printed when ``auto_detected`` is True.
+ - Also printed when in workspace mode (even if flagged explicitly)
+ so the repo list is visible at the top of the command output.
+ - Silent when single-repo mode was explicitly requested.
+ """
+ if self.mode == "workspace":
+ ws_root = self.ws_root.name if self.ws_root else "?"
+ repos = len(self.ws_config.repos) if self.ws_config else 0
+ if self.repo_filter:
+ console_obj.print(
+ f"[dim][workspace][/dim] {command or 'running'} on "
+ f"[cyan]{self.repo_filter}[/cyan] within "
+ f"[cyan]{ws_root}[/cyan] ({repos} repos)"
+ )
+ else:
+ console_obj.print(
+ f"[dim][workspace][/dim] {command or 'running'} across "
+ f"[cyan]{repos}[/cyan] repos in [cyan]{ws_root}[/cyan]"
+ )
+ if self.reason and self.auto_detected:
+ console_obj.print(f"[dim] ({self.reason})[/dim]")
+ return
+
+ # Single-repo mode — only narrate when the resolution was non-obvious.
+ if self.auto_detected and self.ws_root is not None:
+ # A workspace exists upstream but we chose single-repo anyway.
+ console_obj.print(
+ f"[dim][single-repo][/dim] targeting "
+ f"[cyan]{self.repo_path}[/cyan] "
+ f"(workspace also detected at [cyan]{self.ws_root}[/cyan]; "
+ f"pass --workspace to run across all repos)"
+ )
+
+
+class WorkspaceNotFound(click.ClickException):
+ """Raised when ``--workspace`` was requested but no workspace was found."""
+
+
+def resolve_command_target(
+ *,
+ path: str | None = None,
+ workspace_flag: bool = False,
+ no_workspace_flag: bool = False,
+ repo_alias: str | None = None,
+) -> CommandTarget:
+ """Resolve whether a command should operate on a single repo or workspace.
+
+ The resolution rules (first match wins):
+
+ 1. ``--no-workspace`` → single-repo targeting ``path`` (or cwd). Hard
+ override for users who want the old behavior.
+ 2. ``--workspace`` or ``--repo <alias>`` → workspace mode. Raises
+ :class:`WorkspaceNotFound` if no workspace can be located.
+ 3. Explicit ``path`` argument:
+ - If the path itself contains ``.repowise-workspace.yaml`` →
+ workspace mode (treats the path as the workspace root).
+ - Otherwise → single-repo mode targeting that path. We do *not*
+ auto-promote to workspace when the user has explicitly typed a
+ path — explicit beats implicit.
+ 4. No ``path``, no flags → start from cwd and:
+ - If cwd is itself a workspace root → workspace mode.
+ - If cwd has its own ``.repowise/state.json`` (i.e. it's a repo
+ that has been indexed before) → single-repo mode, even if a
+ workspace exists upstream. cd-into-the-repo is the strongest
+ signal of user intent.
+ - If a workspace exists upstream of cwd → workspace mode.
+ - Otherwise → single-repo mode (cwd, even if not indexed).
+
+ The returned :class:`CommandTarget` carries a ``reason`` string and an
+ ``auto_detected`` flag so commands can render a transparent notice.
+ """
+ if workspace_flag and no_workspace_flag:
+ raise click.UsageError("--workspace and --no-workspace are mutually exclusive.")
+
+ if repo_alias is not None and no_workspace_flag:
+ raise click.UsageError("--repo <alias> implies workspace mode, but --no-workspace was passed.")
+
+ explicit_path = path is not None
+ base_path = resolve_repo_path(path)
+
+ # Local import — avoids a circular import (core.workspace pulls in providers
+ # which pull in CLI helpers in some edge cases).
+ from repowise.core.workspace.config import (
+ WORKSPACE_CONFIG_FILENAME,
+ WorkspaceConfig,
+ )
+
+ def _load_ws(root: Path) -> Any | None:
+ try:
+ return WorkspaceConfig.load(root)
+ except Exception:
+ return None
+
+ # ----- Rule 1: explicit --no-workspace -----
+ if no_workspace_flag:
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ reason="forced via --no-workspace",
+ auto_detected=False,
+ )
+
+ # ----- Rule 2: --workspace or --repo -----
+ if workspace_flag or repo_alias is not None:
+ ws_root = find_workspace_root(base_path)
+ if ws_root is None:
+ raise WorkspaceNotFound(
+ "No .repowise-workspace.yaml found at or above "
+ f"{base_path}. Run 'repowise init <workspace-dir>' to "
+ "create a workspace, or drop the --workspace flag."
+ )
+ ws_config = _load_ws(ws_root)
+ if ws_config is None:
+ raise WorkspaceNotFound(
+ f"Found workspace config at {ws_root} but couldn't load it. "
+ "Is it valid YAML?"
+ )
+ if repo_alias is not None and ws_config.get_repo(repo_alias) is None:
+ available = ", ".join(ws_config.repo_aliases()) or "(none)"
+ raise click.UsageError(
+ f"Unknown repo alias '{repo_alias}' in workspace. "
+ f"Available: {available}"
+ )
+ reason = "via --workspace flag" if workspace_flag else f"via --repo {repo_alias}"
+ return CommandTarget(
+ mode="workspace",
+ ws_root=ws_root,
+ ws_config=ws_config,
+ repo_filter=repo_alias,
+ reason=reason,
+ auto_detected=False,
+ )
+
+ # ----- Rule 3: explicit path argument -----
+ if explicit_path:
+ # Is the path itself a workspace root?
+ if (base_path / WORKSPACE_CONFIG_FILENAME).is_file():
+ ws_config = _load_ws(base_path)
+ if ws_config is not None:
+ return CommandTarget(
+ mode="workspace",
+ ws_root=base_path,
+ ws_config=ws_config,
+ reason="path argument is a workspace root",
+ auto_detected=True,
+ )
+ # Otherwise treat as single-repo. Surface workspace context if any.
+ upstream = find_workspace_root(base_path)
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ ws_root=upstream,
+ reason="explicit path argument",
+ auto_detected=False,
+ )
+
+ # ----- Rule 4: no path, no flags -----
+ # 4a: cwd is itself a workspace root
+ if (base_path / WORKSPACE_CONFIG_FILENAME).is_file():
+ ws_config = _load_ws(base_path)
+ if ws_config is not None:
+ return CommandTarget(
+ mode="workspace",
+ ws_root=base_path,
+ ws_config=ws_config,
+ reason="cwd is the workspace root",
+ auto_detected=True,
+ )
+
+ # 4b: cwd is an indexed repo — respect that even if a workspace exists upstream
+ cwd_state = get_repowise_dir(base_path) / STATE_FILENAME
+ if cwd_state.exists():
+ upstream = find_workspace_root(base_path.parent if base_path.parent != base_path else None)
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ ws_root=upstream,
+ reason="cwd has its own .repowise/state.json (cd-into-repo wins)",
+ auto_detected=upstream is not None,
+ )
+
+ # 4c: workspace exists upstream of cwd → workspace mode
+ upstream = find_workspace_root(base_path)
+ if upstream is not None:
+ ws_config = _load_ws(upstream)
+ if ws_config is not None:
+ return CommandTarget(
+ mode="workspace",
+ ws_root=upstream,
+ ws_config=ws_config,
+ reason=f"workspace detected upstream at {upstream}",
+ auto_detected=True,
+ )
+
+ # 4d: plain single-repo mode (likely uninitialized).
+ return CommandTarget(
+ mode="single",
+ repo_path=base_path,
+ reason="no workspace nearby",
+ auto_detected=False,
+ )
+
+
+def is_interactive_session() -> bool:
+ """Best-effort check for an interactive TTY.
+
+ Centralized so commands can share one definition; some test runners
+ fake stdin in ways that break ``sys.stdin.isatty()``.
+ """
+ try:
+ return sys.stdin.isatty()
+ except (AttributeError, ValueError):
+ return False
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 0b1027efc..294a227d0 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -29,10 +29,11 @@ class RepoUpdateResult:
alias: str
updated: bool # True if an update was performed
- skipped_reason: str | None = None # "up_to_date", "not_indexed", etc.
+ skipped_reason: str | None = None # "up_to_date", "missing_directory", etc.
file_count: int = 0
symbol_count: int = 0
error: str | None = None
+ first_time_indexed: bool = False # True if this run was a first-time index
# ---------------------------------------------------------------------------
@@ -74,6 +75,56 @@ def count_commits_between(repo_path: Path, base: str, head: str) -> int:
return 0
+def read_state_commit(repo_path: Path) -> str | None:
+ """Return ``last_sync_commit`` from ``<repo>/.repowise/state.json`` or None."""
+ import json as _json
+
+ state_path = repo_path / ".repowise" / "state.json"
+ if not state_path.is_file():
+ return None
+ try:
+ data = _json.loads(state_path.read_text(encoding="utf-8"))
+ sha = data.get("last_sync_commit")
+ return str(sha) if sha else None
+ except Exception:
+ return None
+
+
+def sync_workspace_state_from_disk(
+ workspace_root: Path,
+ ws_config: WorkspaceConfig,
+ *,
+ save_if_changed: bool = True,
+) -> list[str]:
+ """Refresh ``WorkspaceConfig`` entries from each repo's on-disk
+ ``state.json``.
+
+ A child repo can be updated outside the workspace orchestrator (the
+ user runs ``repowise update`` inside the child dir directly), which
+ drifts ``RepoEntry.last_commit_at_index`` away from the actual
+ ``state.json`` value. Call this before any workspace-level decision
+ that reads from ``ws_config`` so we never act on stale info.
+
+ Returns the list of aliases that changed.
+ """
+ changed: list[str] = []
+ for entry in ws_config.repos:
+ abs_path = (workspace_root / entry.path).resolve()
+ if not abs_path.is_dir():
+ continue
+ disk_commit = read_state_commit(abs_path)
+ if disk_commit is not None and disk_commit != entry.last_commit_at_index:
+ entry.last_commit_at_index = disk_commit
+ changed.append(entry.alias)
+ if changed and save_if_changed:
+ try:
+ ws_config.save(workspace_root)
+ except Exception:
+ # Saving is best-effort — the in-memory sync still happened.
+ _log.warning("Could not persist synced workspace config", exc_info=True)
+ return changed
+
+
def check_repo_staleness(
repo_path: Path,
last_commit: str | None,
@@ -200,7 +251,8 @@ async def update_workspace(
List of :class:`RepoUpdateResult` for each repo.
"""
results: list[RepoUpdateResult] = []
- stale_repos: list[tuple[str, Path, str]] = [] # (alias, path, new_head)
+ # (alias, path, new_head, first_time)
+ stale_repos: list[tuple[str, Path, str, bool]] = []
# Step 1: Determine which repos are stale
entries = ws_config.repos
@@ -211,6 +263,12 @@ async def update_workspace(
raise ValueError(f"Unknown repo '{repo_filter}'. Available: {available}")
entries = [entry]
+ # Step 0: Sync ``last_commit_at_index`` from each repo's state.json so
+ # the workspace config doesn't drift when a child repo is updated
+ # outside the workspace orchestrator (e.g. ``repowise update`` run
+ # inside the child dir directly).
+ sync_workspace_state_from_disk(workspace_root, ws_config)
+
for entry in entries:
abs_path = (workspace_root / entry.path).resolve()
if not abs_path.is_dir():
@@ -240,13 +298,13 @@ async def update_workspace(
))
continue
- if not (abs_path / ".repowise").is_dir():
- results.append(RepoUpdateResult(
- alias=entry.alias, updated=False, skipped_reason="not_indexed",
- ))
- continue
-
- stale_repos.append((entry.alias, abs_path, current_head or ""))
+ # First-time indexing path: previously this short-circuited with
+ # ``skipped_reason="not_indexed"``, leaving newly-added workspace
+ # repos in a half-broken state. Now we run the full pipeline; the
+ # `.repowise/` dir is created on demand by ``update_single_repo_index``
+ # (resolve_db_url) and ``state.json`` is written below.
+ first_time = not (abs_path / ".repowise").is_dir()
+ stale_repos.append((entry.alias, abs_path, current_head or "", first_time))
if dry_run or not stale_repos:
return results
@@ -254,17 +312,24 @@ async def update_workspace(
# Step 2: Update stale repos (parallel with concurrency limit)
semaphore = asyncio.Semaphore(_MAX_CONCURRENT_UPDATES)
- async def _update_one(alias: str, path: Path, new_head: str) -> RepoUpdateResult:
+ async def _update_one(
+ alias: str, path: Path, new_head: str, first_time: bool
+ ) -> RepoUpdateResult:
async with semaphore:
if on_repo_start:
on_repo_start(alias)
+ # Ensure the .repowise/ dir exists before the pipeline runs so
+ # first-time indexing has a place to put wiki.db and state.json.
+ (path / ".repowise").mkdir(parents=True, exist_ok=True)
+
result = await update_single_repo_index(
path,
commit_depth=commit_depth,
exclude_patterns=exclude_patterns,
)
result.alias = alias
+ result.first_time_indexed = first_time and result.updated
# Update state.json with new commit
if result.updated and new_head:
@@ -277,6 +342,15 @@ async def update_workspace(
except Exception:
pass
state["last_sync_commit"] = new_head
+ # Mark first-time so downstream tooling (status, doctor) can
+ # distinguish a never-indexed repo from one that's been
+ # updated at least once.
+ if first_time and "docs_enabled" not in state:
+ state["docs_enabled"] = False
+ state["docs_skip_reason"] = (
+ "first-time index via update; run "
+ "`repowise update --repo " + alias + " --docs` to generate docs"
+ )
state_path.parent.mkdir(parents=True, exist_ok=True)
state_path.write_text(
_json.dumps(state, indent=2), encoding="utf-8",
@@ -295,7 +369,10 @@ async def update_workspace(
return result
update_results = await asyncio.gather(
- *[_update_one(alias, path, head) for alias, path, head in stale_repos],
+ *[
+ _update_one(alias, path, head, first_time)
+ for alias, path, head, first_time in stale_repos
+ ],
return_exceptions=True,
)
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 19632ba26..b70623c63 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -174,6 +174,13 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
app.state.cross_repo_enricher = None
app.state.workspace_sessions = {} # repo_id → session_factory
app.state.workspace_engines = [] # engines to dispose on shutdown
+ # Per-repo FTS instances keyed by repo_id, used by the search router
+ # to fan out across every workspace repo (single-repo FTS lives on
+ # app.state.fts and stays as the primary).
+ app.state.workspace_fts = {} # repo_id → FullTextSearch
+ # repo_id → vector store (LanceDB-backed) for per-repo semantic search.
+ # Populated lazily by the search router on first use, then cached.
+ app.state.workspace_vector_stores = {} # repo_id → VectorStore
try:
from pathlib import Path as _Path
@@ -211,9 +218,12 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
continue
# Skip if this is the primary DB we already connected to
- # (the main engine already serves this repo)
+ # (the main engine already serves this repo) — but still
+ # register the primary's FTS under its repo_id so the
+ # search fan-out can include it.
db_url_posix = repo_db.as_posix()
if db_url and db_url_posix in db_url.replace("\\", "/"):
+ app.state.workspace_fts[repo_id] = fts
continue
repo_engine = create_engine(f"sqlite+aiosqlite:///{db_url_posix}")
@@ -222,6 +232,20 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
app.state.workspace_sessions[repo_id] = repo_sf
app.state.workspace_engines.append(repo_engine)
+ # Build a per-repo FTS instance so the search router can
+ # fan out queries across every workspace repo. Without
+ # this, full-text search only ever sees the primary DB.
+ try:
+ repo_fts = FullTextSearch(repo_engine)
+ await repo_fts.ensure_index()
+ app.state.workspace_fts[repo_id] = repo_fts
+ except Exception:
+ logger.debug(
+ "workspace_fts_init_failed",
+ extra={"repo_id": repo_id},
+ exc_info=True,
+ )
+
if app.state.workspace_sessions:
logger.info(
"workspace_repo_dbs_loaded",
@@ -255,6 +279,13 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
# Shutdown
scheduler.shutdown(wait=False)
await vector_store.close()
+ # Close cached per-repo vector stores (LanceDB connections).
+ try:
+ from repowise.server.search_helpers import close_workspace_vector_stores
+
+ await close_workspace_vector_stores(app)
+ except Exception:
+ logger.debug("workspace_vector_store_close_failed", exc_info=True)
# Dispose workspace repo engines first
for ws_engine in getattr(app.state, "workspace_engines", []):
try:
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 4ea2208fa..3bf4728a6 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -59,8 +59,12 @@ async def list_repos(
) -> list[RepoResponse]:
"""List all registered repositories.
- In workspace mode, aggregates repos from the primary DB and all
- workspace repo DBs so every indexed repo appears in the sidebar.
+ In workspace mode, aggregates indexed repos from the primary DB and
+ every workspace repo DB, AND includes synthetic entries for
+ workspace repos that haven't been indexed yet (status="needs_index")
+ or whose directory has gone missing (status="missing_dir"). This is
+ what powers the web UI sidebar — silently dropping unindexed repos
+ used to cause the "I only see the primary" Discord report.
"""
result = await session.execute(select(Repository).order_by(Repository.updated_at.desc()))
repos = list(result.scalars().all())
@@ -83,9 +87,84 @@ async def list_repos(
except Exception:
pass
- # Sort by updated_at descending
+ # Sort indexed repos by updated_at descending
repos.sort(key=lambda r: r.updated_at or r.created_at, reverse=True)
- return [RepoResponse.from_orm(r) for r in repos]
+ responses = [RepoResponse.from_orm(r) for r in repos]
+
+ # Augment with workspace metadata. We do this in a second pass (rather
+ # than during from_orm) because the workspace context lives on
+ # app.state, not on the Repository row.
+ ws_config = getattr(request.app.state, "workspace_config", None)
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ if ws_config is None or ws_root is None:
+ return responses
+
+ from pathlib import Path as _P
+ import json as _json
+
+ ws_root_path = _P(ws_root)
+ # Map local_path → alias entry for quick attach on indexed rows.
+ by_path: dict[str, object] = {
+ str((ws_root_path / e.path).resolve()): e for e in ws_config.repos
+ }
+
+ # Attach alias + status + docs status to already-indexed rows.
+ indexed_aliases: set[str] = set()
+ for resp in responses:
+ entry = by_path.get(str(_P(resp.local_path).resolve()))
+ if entry is None:
+ continue
+ resp.workspace_alias = entry.alias
+ resp.is_primary = bool(entry.is_primary)
+ resp.workspace_status = "indexed"
+ indexed_aliases.add(entry.alias)
+
+ # docs_enabled is recorded per-repo in state.json. Read it once
+ # per response — cheap, and never failing.
+ state_path = _P(resp.local_path) / ".repowise" / "state.json"
+ if state_path.is_file():
+ try:
+ state = _json.loads(state_path.read_text(encoding="utf-8"))
+ resp.docs_enabled = bool(state.get("docs_enabled", True))
+ resp.docs_skip_reason = state.get("docs_skip_reason")
+ except Exception:
+ pass
+
+ # Synthesize entries for repos in the workspace that aren't indexed yet.
+ from datetime import datetime, UTC as _UTC
+
+ now = datetime.now(_UTC)
+ for entry in ws_config.repos:
+ if entry.alias in indexed_aliases:
+ continue
+ abs_path = (ws_root_path / entry.path).resolve()
+ if abs_path.is_dir():
+ status = "needs_index"
+ else:
+ status = "missing_dir"
+ # Synthetic, stable, prefixed ID so the frontend can route to a
+ # CTA card without colliding with real repo UUIDs.
+ synthetic_id = f"ws:{entry.alias}"
+ responses.append(
+ RepoResponse(
+ id=synthetic_id,
+ name=entry.alias,
+ url="",
+ local_path=str(abs_path),
+ default_branch="main",
+ head_commit=None,
+ settings={},
+ created_at=now,
+ updated_at=now,
+ workspace_alias=entry.alias,
+ workspace_status=status,
+ is_primary=bool(entry.is_primary),
+ docs_enabled=False,
+ docs_skip_reason="not indexed yet",
+ )
+ )
+
+ return responses
@router.get("/{repo_id}", response_model=RepoResponse)
diff --git a/packages/server/src/repowise/server/routers/search.py b/packages/server/src/repowise/server/routers/search.py
index ceb436ef8..cb25ea4b5 100644
--- a/packages/server/src/repowise/server/routers/search.py
+++ b/packages/server/src/repowise/server/routers/search.py
@@ -1,8 +1,13 @@
-"""/api/search — Semantic and full-text search."""
+"""/api/search — Semantic and full-text search.
+
+In workspace mode the router fans out across every loaded repo's FTS
+and vector store so a single query covers the whole workspace. Pass
+``repo_id`` to scope a query to one repo.
+"""
from __future__ import annotations
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, Query, Request
from repowise.server.deps import get_fts, get_vector_store, verify_api_key
from repowise.server.schemas import SearchResultResponse
@@ -13,29 +18,169 @@ router = APIRouter(
)
+def _to_response(r) -> SearchResultResponse:
+ """Convert a SearchResult dataclass into the API schema."""
+ return SearchResultResponse(
+ page_id=r.page_id,
+ title=r.title,
+ page_type=r.page_type,
+ target_path=r.target_path,
+ score=r.score,
+ snippet=r.snippet,
+ search_type=r.search_type,
+ )
+
+
@router.get("", response_model=list[SearchResultResponse])
async def search(
+ request: Request,
query: str = Query(..., min_length=1, description="Search query"),
search_type: str = Query("semantic", description="semantic or fulltext"),
limit: int = Query(10, ge=1, le=100),
- vector_store=Depends(get_vector_store), # noqa: B008
+ repo_id: str | None = Query(
+ None,
+ description=(
+ "Scope to one workspace repo. Accepts a real repo_id from "
+ "/api/repos, or the synthetic 'ws:<alias>' ID for an "
+ "unindexed entry (returns empty)."
+ ),
+ ),
fts=Depends(get_fts), # noqa: B008
+ vector_store=Depends(get_vector_store), # noqa: B008
) -> list[SearchResultResponse]:
- """Search wiki pages by semantic similarity or full-text match."""
+ """Search wiki pages by semantic similarity or full-text match.
+
+ Behavior matrix:
+ - Single-repo mode: uses the primary FTS / vector store as before.
+ - Workspace mode + ``repo_id``: scopes to that repo's FTS / vector
+ store; falls back to the primary if the repo isn't loaded yet.
+ - Workspace mode without ``repo_id``: fans out across every loaded
+ repo's index and merges results by score.
+ """
if search_type == "fulltext":
- results = await fts.search(query, limit=limit)
+ results = await _fulltext(request, query, limit, repo_id=repo_id, primary_fts=fts)
else:
- results = await vector_store.search(query, limit=limit)
-
- return [
- SearchResultResponse(
- page_id=r.page_id,
- title=r.title,
- page_type=r.page_type,
- target_path=r.target_path,
- score=r.score,
- snippet=r.snippet,
- search_type=r.search_type,
+ results = await _semantic(
+ request, query, limit, repo_id=repo_id, primary_vs=vector_store
)
- for r in results
- ]
+
+ return [_to_response(r) for r in results]
+
+
+# ---------------------------------------------------------------------------
+# Fulltext fan-out
+# ---------------------------------------------------------------------------
+
+
+async def _fulltext(request: Request, query: str, limit: int, *, repo_id, primary_fts):
+ """Run a fulltext search against the appropriate FTS instance(s)."""
+ ws_fts: dict = getattr(request.app.state, "workspace_fts", {}) or {}
+
+ # Single-repo mode (no workspace_fts registry) → use the primary FTS.
+ if not ws_fts:
+ return await primary_fts.search(query, limit=limit)
+
+ # Workspace mode with explicit repo_id.
+ if repo_id is not None:
+ # Synthetic IDs ("ws:<alias>") point at unindexed entries — no
+ # FTS data, so return an empty list rather than fall back to the
+ # primary and confuse the user.
+ if repo_id.startswith("ws:"):
+ return []
+ target_fts = ws_fts.get(repo_id)
+ if target_fts is None:
+ # Unknown repo_id — fall back to primary so callers don't
+ # silently get nothing.
+ return await primary_fts.search(query, limit=limit)
+ return await target_fts.search(query, limit=limit)
+
+ # Workspace mode, no filter → fan out across every loaded FTS,
+ # merge by score, and cap at limit.
+ all_results = []
+ for fts_inst in ws_fts.values():
+ try:
+ per_repo = await fts_inst.search(query, limit=limit)
+ except Exception:
+ continue
+ all_results.extend(per_repo)
+ all_results.sort(key=lambda r: r.score, reverse=True)
+ return all_results[:limit]
+
+
+# ---------------------------------------------------------------------------
+# Semantic fan-out
+# ---------------------------------------------------------------------------
+
+
+async def _semantic(request: Request, query: str, limit: int, *, repo_id, primary_vs):
+ """Run a semantic search across the appropriate vector store(s)."""
+ from repowise.server.search_helpers import resolve_workspace_vector_store
+
+ ws_config = getattr(request.app.state, "workspace_config", None)
+ if ws_config is None:
+ # Single-repo mode.
+ return await primary_vs.search(query, limit=limit)
+
+ if repo_id is not None:
+ if repo_id.startswith("ws:"):
+ return []
+ vs = await resolve_workspace_vector_store(request.app, repo_id)
+ if vs is None:
+ return await primary_vs.search(query, limit=limit)
+ return await vs.search(query, limit=limit)
+
+ # Fan-out: iterate over every workspace repo with an indexed wiki.db
+ # and try to load its persisted LanceDB store. Repos without one
+ # fall back to FTS so the user still gets some signal.
+ from pathlib import Path as _P
+
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ if ws_root is None:
+ return await primary_vs.search(query, limit=limit)
+ ws_root_path = _P(ws_root)
+
+ all_results = []
+ workspace_fts = getattr(request.app.state, "workspace_fts", {}) or {}
+
+ for entry in ws_config.repos:
+ repo_path = (ws_root_path / entry.path).resolve()
+ db_path = repo_path / ".repowise" / "wiki.db"
+ if not db_path.exists():
+ continue
+ # Resolve repo_id from the per-repo DB once (cached on app.state).
+ import sqlite3 as _sql
+
+ try:
+ with _sql.connect(str(db_path)) as conn:
+ row = conn.execute(
+ "SELECT id FROM repositories LIMIT 1"
+ ).fetchone()
+ except Exception:
+ row = None
+ rid = row[0] if row else None
+
+ # Try the vector store first.
+ per_repo = []
+ vs = None
+ if rid is not None:
+ try:
+ vs = await resolve_workspace_vector_store(request.app, rid)
+ except Exception:
+ vs = None
+ if vs is not None:
+ try:
+ per_repo = await vs.search(query, limit=limit)
+ except Exception:
+ per_repo = []
+ # Fall back to FTS when no vector data is available — better
+ # than silently returning nothing on workspaces that haven't
+ # built LanceDB indexes yet.
+ if not per_repo and rid in workspace_fts:
+ try:
+ per_repo = await workspace_fts[rid].search(query, limit=limit)
+ except Exception:
+ per_repo = []
+ all_results.extend(per_repo)
+
+ all_results.sort(key=lambda r: r.score, reverse=True)
+ return all_results[:limit]
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index eae476637..a31fbba27 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -7,6 +7,7 @@ startup from ``.repowise-workspace/`` JSON files) — no DB access needed.
from __future__ import annotations
+import asyncio
import logging
import sqlite3
from pathlib import Path
@@ -15,7 +16,9 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request
from repowise.server.deps import (
get_cross_repo_enricher,
+ get_db_session,
get_workspace_config,
+ resolve_session_factory,
verify_api_key,
)
from repowise.server.schemas import (
@@ -79,7 +82,8 @@ def _query_repo_stats(db_path: Path) -> dict:
"""Query basic stats from a repo's wiki.db using raw sqlite3.
Returns a dict with repo_id, file_count, symbol_count, page_count,
- doc_coverage_pct, hotspot_count. All values default to 0/None on error.
+ doc_coverage_pct, hotspot_count, status, docs_enabled, and
+ docs_skip_reason. All values default to sensible neutrals on error.
"""
result: dict = {
"repo_id": None,
@@ -88,9 +92,27 @@ def _query_repo_stats(db_path: Path) -> dict:
"page_count": 0,
"doc_coverage_pct": 0.0,
"hotspot_count": 0,
+ "status": "needs_index",
+ "docs_enabled": False,
+ "docs_skip_reason": None,
}
+ # Surface docs lifecycle from state.json so the UI shows a coherent
+ # picture even when only indexing (no docs) ran.
+ try:
+ import json as _json
+
+ state_path = db_path.parent / "state.json"
+ if state_path.is_file():
+ state = _json.loads(state_path.read_text(encoding="utf-8"))
+ result["docs_enabled"] = bool(state.get("docs_enabled", False))
+ result["docs_skip_reason"] = state.get("docs_skip_reason")
+ except Exception:
+ pass
if not db_path.exists():
+ if not db_path.parent.parent.is_dir():
+ result["status"] = "missing_dir"
return result
+ result["status"] = "indexed"
try:
conn = sqlite3.connect(str(db_path))
c = conn.cursor()
@@ -433,3 +455,163 @@ async def get_workspace_graph(
)
return WorkspaceGraphResponse(nodes=nodes, edges=edges)
+
+
+# ---------------------------------------------------------------------------
+# POST /api/workspace/sync
+# ---------------------------------------------------------------------------
+
+
[email protected]("/sync", status_code=202)
+async def sync_workspace(
+ request: Request,
+ repo_alias: str | None = Query(
+ None,
+ description="If set, only sync this repo alias (still fans through the job system).",
+ ),
+ full_resync: bool = Query(False, description="Trigger a full resync instead of incremental."),
+ ws_config=Depends(get_workspace_config),
+):
+ """Fan out a sync to every (stale or unindexed) repo in the workspace.
+
+ Returns one :class:`WorkspaceSyncResult` per attempted repo with the
+ decision (accepted / skipped / error) so the web UI can render
+ progress without polling for each repo individually.
+
+ Uses the same job machinery as ``POST /api/repos/{id}/sync`` so the
+ scheduler, cost ledger, and live-progress hooks all work without
+ special cases.
+ """
+ from repowise.server.schemas import (
+ WorkspaceSyncResponse,
+ WorkspaceSyncResult,
+ )
+
+ _require_workspace(ws_config)
+
+ from repowise.core.persistence import crud
+ from repowise.core.persistence.database import get_session
+ from repowise.core.persistence.models import GenerationJob
+ from repowise.server.routers.repos import _launch_job_task
+ from sqlalchemy import select
+
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ if ws_root is None:
+ raise HTTPException(status_code=500, detail="Workspace root missing on app state")
+ ws_root_path = Path(ws_root)
+
+ results: list[WorkspaceSyncResult] = []
+
+ # Resolve aliases → entries to operate on.
+ if repo_alias is not None:
+ entry = ws_config.get_repo(repo_alias)
+ if entry is None:
+ raise HTTPException(
+ status_code=404,
+ detail=f"Unknown repo alias '{repo_alias}' in workspace.",
+ )
+ entries = [entry]
+ else:
+ entries = list(ws_config.repos)
+
+ for entry in entries:
+ repo_path = (ws_root_path / entry.path).resolve()
+ db_path = repo_path / ".repowise" / "wiki.db"
+
+ # Not indexed yet → no row to write a job against. Surface this
+ # as "skipped" so the UI can show a clear "run `repowise update
+ # --repo <alias>` from the CLI" hint. (A future enhancement is
+ # to support remote first-time indexing; see Phase C.)
+ if not db_path.exists():
+ results.append(
+ WorkspaceSyncResult(
+ alias=entry.alias,
+ status="skipped",
+ reason="not indexed yet (run `repowise update --repo " + entry.alias + "` from the CLI)",
+ )
+ )
+ continue
+
+ # Discover repo_id from the per-repo DB.
+ try:
+ with sqlite3.connect(str(db_path)) as conn:
+ row = conn.execute(
+ "SELECT id FROM repositories LIMIT 1"
+ ).fetchone()
+ except Exception as exc:
+ results.append(
+ WorkspaceSyncResult(
+ alias=entry.alias,
+ status="error",
+ reason=f"could not read repo id: {exc}",
+ )
+ )
+ continue
+
+ if not row:
+ results.append(
+ WorkspaceSyncResult(
+ alias=entry.alias,
+ status="error",
+ reason="repository row missing in wiki.db",
+ )
+ )
+ continue
+ repo_id = row[0]
+
+ session_factory = resolve_session_factory(request.app.state, repo_id)
+
+ async def _create_job() -> tuple[str | None, str | None]:
+ """Create a pending job row, returning (job_id, error)."""
+ try:
+ async with get_session(session_factory) as session:
+ # Prevent concurrent runs on the same repo.
+ active = await session.execute(
+ select(GenerationJob.id)
+ .where(GenerationJob.repository_id == repo_id)
+ .where(GenerationJob.status.in_(["pending", "running"]))
+ .limit(1)
+ )
+ if active.scalar_one_or_none() is not None:
+ return None, "a sync is already running for this repo"
+
+ config_data = {"mode": "full_resync"} if full_resync else None
+ job = await crud.upsert_generation_job(
+ session,
+ repository_id=repo_id,
+ status="pending",
+ config=config_data,
+ )
+ await session.commit()
+ return job.id, None
+ except Exception as exc: # noqa: BLE001
+ return None, str(exc)
+
+ job_id, err = await _create_job()
+ if err is not None:
+ results.append(
+ WorkspaceSyncResult(
+ alias=entry.alias,
+ repo_id=repo_id,
+ status="skipped" if "already running" in err else "error",
+ reason=err,
+ )
+ )
+ continue
+
+ _launch_job_task(request, job_id, repo_id)
+ results.append(
+ WorkspaceSyncResult(
+ alias=entry.alias,
+ repo_id=repo_id,
+ job_id=job_id,
+ status="accepted",
+ )
+ )
+
+ return WorkspaceSyncResponse(
+ results=results,
+ accepted=sum(1 for r in results if r.status == "accepted"),
+ skipped=sum(1 for r in results if r.status == "skipped"),
+ errors=sum(1 for r in results if r.status == "error"),
+ )
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index f3cb64699..f8a8ae3c7 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -50,6 +50,16 @@ class RepoResponse(BaseModel):
settings: dict
created_at: datetime
updated_at: datetime
+ # Workspace context — populated when the server is running in
+ # workspace mode. ``status`` indicates whether the repo has been
+ # indexed yet; the web UI uses it to render "needs index" CTA cards
+ # instead of silently dropping unindexed workspace repos from the
+ # sidebar. Always ``None`` in single-repo mode.
+ workspace_alias: str | None = None
+ workspace_status: str | None = None
+ is_primary: bool | None = None
+ docs_enabled: bool | None = None
+ docs_skip_reason: str | None = None
@classmethod
def from_orm(cls, obj: object) -> RepoResponse:
@@ -940,6 +950,20 @@ class WorkspaceRepoEntry(BaseModel):
page_count: int = 0
doc_coverage_pct: float = 0.0
hotspot_count: int = 0
+ # Lifecycle status — surfaced so the web UI can render "needs index"
+ # or "missing directory" affordances instead of silently dropping the
+ # repo from the sidebar.
+ # "indexed" — has .repowise/wiki.db with at least one Repository row
+ # "needs_index" — directory exists but no .repowise/wiki.db yet
+ # "missing_dir" — workspace config references a path that no longer exists
+ status: str = "indexed"
+ # Whether docs were generated for this repo. False means a user
+ # action ("repowise update --repo <alias> --docs") is required to
+ # populate the Docs/Overview tabs in the web UI.
+ docs_enabled: bool = True
+ # Optional skip reason captured in state.json — surfaced as a
+ # transparency hint when docs are disabled.
+ docs_skip_reason: str | None = None
class WorkspaceCrossRepoSummary(BaseModel):
@@ -964,6 +988,21 @@ class WorkspaceResponse(BaseModel):
contract_summary: WorkspaceContractSummary | None = None
+class WorkspaceSyncResult(BaseModel):
+ alias: str
+ job_id: str | None = None
+ repo_id: str | None = None
+ status: str # "accepted", "skipped", "error"
+ reason: str | None = None
+
+
+class WorkspaceSyncResponse(BaseModel):
+ results: list[WorkspaceSyncResult]
+ accepted: int = 0
+ skipped: int = 0
+ errors: int = 0
+
+
class WorkspaceContractEntry(BaseModel):
contract_id: str
contract_type: str
diff --git a/packages/server/src/repowise/server/search_helpers.py b/packages/server/src/repowise/server/search_helpers.py
new file mode 100644
index 000000000..3fb95025f
--- /dev/null
+++ b/packages/server/src/repowise/server/search_helpers.py
@@ -0,0 +1,129 @@
+"""Helpers for search fan-out across workspace repos.
+
+These live in a separate module so they can be reused by other routers
+(chat, MCP-over-HTTP, future workspace endpoints) without each one
+re-implementing LanceDB rehydration / lazy caching.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger("repowise.server.search_helpers")
+
+# Asyncio lock per repo_id, used to prevent two concurrent semantic
+# search requests from both opening the LanceDB store. The first one in
+# allocates; everyone else awaits the cached result.
+_vector_store_locks: dict[str, asyncio.Lock] = {}
+
+
+async def resolve_workspace_vector_store(app, repo_id: str) -> Any | None:
+ """Return a vector store for the given workspace ``repo_id``.
+
+ Cached on ``app.state.workspace_vector_stores`` after first
+ resolution. Returns ``None`` if:
+ - We're not in workspace mode.
+ - The repo_id isn't in the workspace config.
+ - The repo has no ``lancedb/`` directory on disk yet.
+
+ The store uses the same embedder as the primary vector store, so a
+ workspace built with the gemini embedder keeps its embeddings
+ compatible across fan-out queries.
+ """
+ cache: dict | None = getattr(app.state, "workspace_vector_stores", None)
+ if cache is None:
+ return None
+ if repo_id in cache:
+ return cache[repo_id]
+
+ lock = _vector_store_locks.setdefault(repo_id, asyncio.Lock())
+ async with lock:
+ # Double-checked locking — another coroutine may have populated
+ # the cache while we waited on the lock.
+ if repo_id in cache:
+ return cache[repo_id]
+
+ ws_config = getattr(app.state, "workspace_config", None)
+ ws_root = getattr(app.state, "workspace_root", None)
+ if ws_config is None or ws_root is None:
+ return None
+
+ # Locate the repo's directory by repo_id. We don't carry an
+ # alias→repo_id map directly, so scan once. Workspace sizes are
+ # small (typically <20 repos), so the linear scan is fine.
+ import sqlite3
+
+ repo_path: Path | None = None
+ ws_root_path = Path(ws_root)
+ for entry in ws_config.repos:
+ candidate = (ws_root_path / entry.path).resolve()
+ db_path = candidate / ".repowise" / "wiki.db"
+ if not db_path.exists():
+ continue
+ try:
+ with sqlite3.connect(str(db_path)) as conn:
+ row = conn.execute(
+ "SELECT id FROM repositories LIMIT 1"
+ ).fetchone()
+ if row and row[0] == repo_id:
+ repo_path = candidate
+ break
+ except Exception:
+ continue
+ if repo_path is None:
+ return None
+
+ lance_dir = repo_path / ".repowise" / "lancedb"
+ if not lance_dir.is_dir():
+ return None
+
+ # Build the store with the same embedder used by the primary
+ # vector store. Falls back to mock when the primary is also
+ # mock — keeps unit tests deterministic.
+ try:
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+
+ embedder = _resolve_embedder(app)
+ store = LanceDBVectorStore(str(lance_dir), embedder=embedder)
+ cache[repo_id] = store
+ return store
+ except Exception:
+ logger.debug(
+ "lancedb_open_failed",
+ extra={"repo_id": repo_id, "path": str(lance_dir)},
+ exc_info=True,
+ )
+ return None
+
+
+def _resolve_embedder(app):
+ """Pull the same embedder the primary vector store was built with.
+
+ ``InMemoryVectorStore`` and ``LanceDBVectorStore`` both expose
+ ``_embedder`` (set in __init__). Falls back to a fresh mock when the
+ primary store doesn't expose one — keeps semantic search "working"
+ against LanceDB stores built with the mock embedder during tests.
+ """
+ primary_vs = getattr(app.state, "vector_store", None)
+ embedder = getattr(primary_vs, "_embedder", None) if primary_vs else None
+ if embedder is None:
+ from repowise.core.providers.embedding.base import MockEmbedder
+
+ embedder = MockEmbedder()
+ return embedder
+
+
+async def close_workspace_vector_stores(app) -> None:
+ """Close every cached workspace vector store. Called on shutdown."""
+ cache: dict | None = getattr(app.state, "workspace_vector_stores", None)
+ if not cache:
+ return
+ for store in list(cache.values()):
+ try:
+ await store.close()
+ except Exception:
+ pass
+ cache.clear()
diff --git a/packages/ui/src/workspace/repo-card.tsx b/packages/ui/src/workspace/repo-card.tsx
index 4f39844c9..40547e881 100644
--- a/packages/ui/src/workspace/repo-card.tsx
+++ b/packages/ui/src/workspace/repo-card.tsx
@@ -13,6 +13,12 @@ interface RepoCardProps {
isPrimary: boolean;
stats: RepoStats | null;
gitSummary: GitSummary | null;
+ /** Workspace status — undefined in single-repo mode. */
+ status?: "indexed" | "needs_index" | "missing_dir" | null;
+ /** Reason docs were skipped (cost gate, no provider, index-only, etc.). */
+ docsSkipReason?: string | null;
+ /** Slot rendered in the card footer — typically a sync/index button. */
+ actions?: React.ReactNode;
}
export function RepoCard({
@@ -24,14 +30,18 @@ export function RepoCard({
isPrimary,
stats,
gitSummary,
+ status,
+ docsSkipReason,
+ actions,
}: RepoCardProps) {
const prefix = linkPrefix ?? `/repos/${repoId}`;
+ const isUnindexed = status === "needs_index" || status === "missing_dir";
const card = (
<Card className={`group transition-colors ${repoId ? "hover:border-[var(--color-accent-primary)]/30 cursor-pointer" : "opacity-60"}`}>
<CardContent className="p-4">
<div className="flex items-start justify-between mb-3">
<div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
<h3 className="text-sm font-semibold text-[var(--color-text-primary)] truncate group-hover:text-[var(--color-accent-primary)] transition-colors">
{name}
</h3>
@@ -40,6 +50,16 @@ export function RepoCard({
default
</Badge>
)}
+ {status === "needs_index" && (
+ <Badge variant="outline" className="text-[10px] shrink-0">
+ needs index
+ </Badge>
+ )}
+ {status === "missing_dir" && (
+ <Badge variant="outdated" className="text-[10px] shrink-0">
+ missing
+ </Badge>
+ )}
</div>
<p className="text-xs text-[var(--color-text-tertiary)] font-mono mt-0.5 truncate" title={`${alias} · ${path}`}>
{alias} &middot; {path}
@@ -70,11 +90,24 @@ export function RepoCard({
</span>
</div>
</div>
+
+ {docsSkipReason && (
+ <p className="mt-3 text-[11px] text-[var(--color-text-tertiary)] leading-snug">
+ <span className="font-medium">Docs skipped:</span> {docsSkipReason}
+ </p>
+ )}
+
+ {actions && (
+ <div className="mt-3 flex items-center gap-2">{actions}</div>
+ )}
</CardContent>
</Card>
);
- if (!repoId) return card;
+ // Disable the navigation wrapper for synthetic / unindexed repos so the
+ // user lands in workspace flow (sync, fix) instead of a broken
+ // per-repo route.
+ if (!repoId || isUnindexed) return card;
return (
<a href={`${prefix}/overview`}>
diff --git a/packages/web/src/app/repos/[id]/search/page.tsx b/packages/web/src/app/repos/[id]/search/page.tsx
index c4a5b8224..8171b72e1 100644
--- a/packages/web/src/app/repos/[id]/search/page.tsx
+++ b/packages/web/src/app/repos/[id]/search/page.tsx
@@ -16,10 +16,19 @@ export default function SearchPage() {
const id = params.id;
const [query, setQuery] = useState("");
const [searchType, setSearchType] = useState<SearchType>("semantic");
+ const [scope, setScope] = useState<"repo" | "workspace">("repo");
+
+ // Synthetic ws:<alias> IDs point at unindexed workspace entries — the
+ // backend short-circuits search on those. Skip the repo_id filter and
+ // gently fall back to workspace scope so the user still sees results.
+ const isSynthetic = id?.startsWith("ws:");
+ const effectiveRepoId =
+ scope === "repo" && !isSynthetic ? id : undefined;
const { results, isLoading, isTyping, error } = useSearch(query, {
search_type: searchType,
limit: 20,
+ repo_id: effectiveRepoId,
});
const showResults = query.trim().length >= 2;
@@ -33,7 +42,7 @@ export default function SearchPage() {
Search
</h1>
<p className="text-sm text-[var(--color-text-secondary)]">
- Full-text and semantic search across all wiki pages.
+ Full-text and semantic search across {scope === "repo" ? "this repo" : "the whole workspace"}.
</p>
</div>
@@ -44,6 +53,36 @@ export default function SearchPage() {
onSearchTypeChange={setSearchType}
/>
+ <div className="flex items-center gap-2 text-xs">
+ <span className="text-[var(--color-text-tertiary)]">Scope:</span>
+ <button
+ type="button"
+ onClick={() => setScope("repo")}
+ disabled={isSynthetic}
+ className={
+ "rounded-md border px-2 py-1 transition-colors " +
+ (scope === "repo" && !isSynthetic
+ ? "border-[var(--color-accent-primary)] bg-[var(--color-accent-primary)]/10 text-[var(--color-text-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] disabled:opacity-50")
+ }
+ title={isSynthetic ? "This repo isn't indexed yet — workspace scope used." : undefined}
+ >
+ This repo
+ </button>
+ <button
+ type="button"
+ onClick={() => setScope("workspace")}
+ className={
+ "rounded-md border px-2 py-1 transition-colors " +
+ (scope === "workspace" || isSynthetic
+ ? "border-[var(--color-accent-primary)] bg-[var(--color-accent-primary)]/10 text-[var(--color-text-primary)]"
+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]")
+ }
+ >
+ Workspace
+ </button>
+ </div>
+
{showResults && error && (
<div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-outdated)]">
Couldn&apos;t run search: {error instanceof Error ? error.message : "unknown error"}
diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsx
index ef6016392..a40bab9ba 100644
--- a/packages/web/src/app/workspace/page.tsx
+++ b/packages/web/src/app/workspace/page.tsx
@@ -19,6 +19,7 @@ import { CoChangeTable } from "@repowise-dev/ui/workspace/co-change-table";
import { ContractTypeBadge } from "@repowise-dev/ui/workspace/contract-type-badge";
import { formatNumber } from "@repowise-dev/ui/lib/format";
import { WorkspaceGraphSection } from "./workspace-graph-section";
+import { SyncButton } from "./sync-buttons";
export const metadata: Metadata = { title: "Workspace" };
@@ -59,24 +60,29 @@ export default async function WorkspaceDashboardPage() {
return (
<div className="p-5 sm:p-8 space-y-8 max-w-[1200px]">
{/* Header */}
- <div>
- <div className="flex items-center gap-2.5 mb-1">
- <Layers className="h-6 w-6 text-[var(--color-accent-primary)]" />
- <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
- {workspace?.workspace_name ?? "Workspace"}
- </h1>
+ <div className="flex items-start justify-between gap-4 flex-wrap">
+ <div>
+ <div className="flex items-center gap-2.5 mb-1">
+ <Layers className="h-6 w-6 text-[var(--color-accent-primary)]" />
+ <h1 className="text-2xl font-semibold text-[var(--color-text-primary)]">
+ {workspace?.workspace_name ?? "Workspace"}
+ </h1>
+ </div>
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ {workspace?.repos.length ?? 0} repositories
+ {workspace?.workspace_root && (
+ <span
+ className="text-[var(--color-text-tertiary)] font-mono break-all"
+ title={workspace.workspace_root}
+ >
+ {" "}&middot; {workspace.workspace_root}
+ </span>
+ )}
+ </p>
</div>
- <p className="text-sm text-[var(--color-text-secondary)]">
- {workspace?.repos.length ?? 0} repositories
- {workspace?.workspace_root && (
- <span
- className="text-[var(--color-text-tertiary)] font-mono break-all"
- title={workspace.workspace_root}
- >
- {" "}&middot; {workspace.workspace_root}
- </span>
- )}
- </p>
+ {(workspace?.repos.length ?? 0) > 0 && (
+ <SyncButton variant="primary" label="Sync workspace" />
+ )}
</div>
{/* Aggregate Stats */}
@@ -114,7 +120,10 @@ export default async function WorkspaceDashboardPage() {
Repositories
</h2>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
- {wsRepos.map((wsRepo) => (
+ {wsRepos.map((wsRepo) => {
+ const status = wsRepo.status ?? (wsRepo.repo_id ? "indexed" : "needs_index");
+ const isUnindexed = status !== "indexed";
+ return (
<RepoCard
key={wsRepo.alias}
repoId={wsRepo.repo_id ?? ""}
@@ -122,6 +131,8 @@ export default async function WorkspaceDashboardPage() {
name={wsRepo.alias}
path={wsRepo.path}
isPrimary={wsRepo.is_primary}
+ status={status}
+ docsSkipReason={wsRepo.docs_skip_reason ?? null}
stats={wsRepo.file_count > 0 ? {
file_count: wsRepo.file_count,
symbol_count: wsRepo.symbol_count,
@@ -137,8 +148,17 @@ export default async function WorkspaceDashboardPage() {
average_churn_percentile: 0,
top_owners: [],
} : null}
+ actions={
+ status !== "missing_dir" ? (
+ <SyncButton
+ alias={wsRepo.alias}
+ label={isUnindexed ? "Index now" : "Sync"}
+ />
+ ) : null
+ }
/>
- ))}
+ );
+ })}
</div>
</section>
diff --git a/packages/web/src/app/workspace/sync-buttons.tsx b/packages/web/src/app/workspace/sync-buttons.tsx
new file mode 100644
index 000000000..f2e97b6a5
--- /dev/null
+++ b/packages/web/src/app/workspace/sync-buttons.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { RefreshCw } from "lucide-react";
+import { syncWorkspace } from "@/lib/api/workspace";
+import type { WorkspaceSyncResult } from "@/lib/api/types";
+
+type SyncState =
+ | { kind: "idle" }
+ | { kind: "running" }
+ | { kind: "ok"; results: WorkspaceSyncResult[] }
+ | { kind: "error"; message: string };
+
+interface SyncButtonProps {
+ alias?: string;
+ label?: string;
+ variant?: "primary" | "ghost";
+ fullResync?: boolean;
+}
+
+/**
+ * Trigger /api/workspace/sync for the entire workspace (alias undefined)
+ * or a single repo. Shows inline status; refreshes the route on success
+ * so the new repo data shows up.
+ */
+export function SyncButton({
+ alias,
+ label,
+ variant = "ghost",
+ fullResync = false,
+}: SyncButtonProps) {
+ const [state, setState] = useState<SyncState>({ kind: "idle" });
+ const [, startTransition] = useTransition();
+ const router = useRouter();
+
+ const handleClick = async () => {
+ setState({ kind: "running" });
+ try {
+ const resp = await syncWorkspace({
+ repoAlias: alias,
+ fullResync,
+ });
+ setState({ kind: "ok", results: resp.results });
+ startTransition(() => router.refresh());
+ } catch (e) {
+ setState({
+ kind: "error",
+ message: e instanceof Error ? e.message : "unknown error",
+ });
+ }
+ };
+
+ const buttonText =
+ label ?? (alias ? "Sync this repo" : "Sync workspace");
+
+ const baseClass =
+ "inline-flex items-center gap-1.5 rounded-md text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed";
+ const variantClass =
+ variant === "primary"
+ ? "bg-[var(--color-accent-primary)] text-[var(--color-bg-base)] hover:bg-[var(--color-accent-primary)]/90 px-3 py-1.5"
+ : "border border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] px-2.5 py-1";
+
+ return (
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={handleClick}
+ disabled={state.kind === "running"}
+ className={`${baseClass} ${variantClass}`}
+ aria-label={buttonText}
+ >
+ <RefreshCw
+ className={`h-3 w-3 ${state.kind === "running" ? "animate-spin" : ""}`}
+ />
+ {state.kind === "running" ? "Syncing…" : buttonText}
+ </button>
+ {state.kind === "ok" && (
+ <span className="text-[11px] text-[var(--color-text-tertiary)]">
+ {summarizeResults(state.results)}
+ </span>
+ )}
+ {state.kind === "error" && (
+ <span className="text-[11px] text-[var(--color-outdated)]">
+ {state.message}
+ </span>
+ )}
+ </div>
+ );
+}
+
+function summarizeResults(results: WorkspaceSyncResult[]): string {
+ if (results.length === 0) return "no repos";
+ const accepted = results.filter((r) => r.status === "accepted").length;
+ const skipped = results.filter((r) => r.status === "skipped").length;
+ const errored = results.filter((r) => r.status === "error").length;
+ const parts: string[] = [];
+ if (accepted) parts.push(`${accepted} queued`);
+ if (skipped) parts.push(`${skipped} skipped`);
+ if (errored) parts.push(`${errored} error`);
+ return parts.join(", ");
+}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index fa5859429..9f55a7ebe 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -191,6 +191,55 @@ export function Sidebar({ repos = [], activeRepoId, workspace }: SidebarProps) {
const isExpanded = expandedRepos.has(repo.id);
const isActive = derivedActiveRepoId === repo.id;
const navItems = repoNavItems(repo.id);
+ const needsIndex =
+ repo.workspace_status === "needs_index" ||
+ repo.id.startsWith("ws:");
+ const isMissing = repo.workspace_status === "missing_dir";
+
+ if (needsIndex || isMissing) {
+ // Synthetic / unindexed workspace entry — show as a
+ // disabled row with a status hint. The Index/Sync
+ // CTA lives in the Workspace dashboard.
+ if (isIconOnly) {
+ return (
+ <Tooltip key={repo.id}>
+ <TooltipTrigger asChild>
+ <div
+ className="flex w-full items-center justify-center rounded-md p-2 text-[var(--color-text-tertiary)] opacity-60"
+ aria-label={`${repo.name} (${isMissing ? "missing" : "needs index"})`}
+ >
+ <Circle className="h-2.5 w-2.5 stroke-current" />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ {repo.workspace_alias ?? repo.name}
+ {" — "}
+ {isMissing ? "directory missing" : "needs indexing"}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+ return (
+ <Link
+ key={repo.id}
+ href="/workspace"
+ className="flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-sm text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)]"
+ title={
+ isMissing
+ ? "Directory missing — open Workspace to remove or fix"
+ : "Not indexed yet — open Workspace to index"
+ }
+ >
+ <Circle className="h-2 w-2 shrink-0 stroke-current" />
+ <span className="flex-1 truncate text-left font-medium">
+ {repo.workspace_alias ?? repo.name}
+ </span>
+ <span className="shrink-0 rounded-full bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ {isMissing ? "missing" : "index"}
+ </span>
+ </Link>
+ );
+ }
if (isIconOnly) {
return (
diff --git a/packages/web/src/lib/api/search.ts b/packages/web/src/lib/api/search.ts
index 2d3b62204..d7c60afc4 100644
--- a/packages/web/src/lib/api/search.ts
+++ b/packages/web/src/lib/api/search.ts
@@ -3,11 +3,19 @@ import type { SearchResultResponse } from "./types";
export async function search(
query: string,
- opts?: { search_type?: "semantic" | "fulltext"; limit?: number },
+ opts?: {
+ search_type?: "semantic" | "fulltext";
+ limit?: number;
+ repo_id?: string;
+ },
): Promise<SearchResultResponse[]> {
- return apiGet<SearchResultResponse[]>("/api/search", {
+ const params: Record<string, string | number> = {
query,
search_type: opts?.search_type ?? "semantic",
limit: opts?.limit ?? 10,
- });
+ };
+ if (opts?.repo_id) {
+ params.repo_id = opts.repo_id;
+ }
+ return apiGet<SearchResultResponse[]>("/api/search", params);
}
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index 9d3d97f20..b849f5a60 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -35,6 +35,14 @@ export interface RepoResponse {
settings: Record<string, unknown>;
created_at: string;
updated_at: string;
+ // Workspace mode (optional — only populated when the server runs in
+ // workspace mode). Unindexed repos appear as synthetic rows with
+ // `id="ws:<alias>"` and `workspace_status === "needs_index"`.
+ workspace_alias?: string | null;
+ workspace_status?: "indexed" | "needs_index" | "missing_dir" | null;
+ is_primary?: boolean | null;
+ docs_enabled?: boolean | null;
+ docs_skip_reason?: string | null;
}
// ---------------------------------------------------------------------------
@@ -644,6 +652,22 @@ export interface WorkspaceRepoEntry {
page_count: number;
doc_coverage_pct: number;
hotspot_count: number;
+ // Phase B server augmentation
+ status?: "indexed" | "needs_index" | "missing_dir" | null;
+ docs_enabled?: boolean | null;
+ docs_skip_reason?: string | null;
+}
+
+export interface WorkspaceSyncResult {
+ alias: string;
+ repo_id: string | null;
+ status: "accepted" | "skipped" | "error";
+ job_id: string | null;
+ reason: string | null;
+}
+
+export interface WorkspaceSyncResponse {
+ results: WorkspaceSyncResult[];
}
export interface WorkspaceCrossRepoSummary {
diff --git a/packages/web/src/lib/api/workspace.ts b/packages/web/src/lib/api/workspace.ts
index 082c4b359..11230ad8a 100644
--- a/packages/web/src/lib/api/workspace.ts
+++ b/packages/web/src/lib/api/workspace.ts
@@ -1,9 +1,10 @@
-import { apiGet } from "./client";
+import { apiGet, apiPost } from "./client";
import type {
WorkspaceResponse,
WorkspaceContractsResponse,
WorkspaceCoChangesResponse,
WorkspaceGraphResponse,
+ WorkspaceSyncResponse,
} from "./types";
export async function getWorkspace(): Promise<WorkspaceResponse> {
@@ -41,3 +42,23 @@ export async function getWorkspaceCoChanges(opts?: {
export async function getWorkspaceGraph(): Promise<WorkspaceGraphResponse> {
return apiGet<WorkspaceGraphResponse>("/api/workspace/graph");
}
+
+/**
+ * Trigger a re-sync (re-index) of the workspace. Pass ``repoAlias`` to
+ * scope to one repo; otherwise the server fans out across every loaded
+ * workspace repo. Returns one result per repo (accepted / skipped / error).
+ */
+export async function syncWorkspace(opts?: {
+ repoAlias?: string;
+ fullResync?: boolean;
+}): Promise<WorkspaceSyncResponse> {
+ const params: Record<string, string> = {};
+ if (opts?.repoAlias) params.repo_alias = opts.repoAlias;
+ if (opts?.fullResync) params.full_resync = "true";
+ return apiPost<WorkspaceSyncResponse>(
+ "/api/workspace/sync",
+ undefined,
+ undefined,
+ params,
+ );
+}
diff --git a/packages/web/src/lib/hooks/use-search.ts b/packages/web/src/lib/hooks/use-search.ts
index a3b81ed4d..85be4628f 100644
--- a/packages/web/src/lib/hooks/use-search.ts
+++ b/packages/web/src/lib/hooks/use-search.ts
@@ -7,13 +7,26 @@ import type { SearchResultResponse } from "@/lib/api/types";
export function useSearch(
query: string,
- opts?: { search_type?: "semantic" | "fulltext"; limit?: number; debounce?: number },
+ opts?: {
+ search_type?: "semantic" | "fulltext";
+ limit?: number;
+ debounce?: number;
+ repo_id?: string;
+ },
) {
const debounced = useDebounce(query, opts?.debounce ?? 300);
- const key = debounced.trim().length >= 2 ? `search:${debounced}:${opts?.search_type}` : null;
+ const key =
+ debounced.trim().length >= 2
+ ? `search:${debounced}:${opts?.search_type}:${opts?.repo_id ?? "all"}`
+ : null;
const { data, error, isLoading } = useSWR<SearchResultResponse[]>(
key,
- () => search(debounced, { search_type: opts?.search_type, limit: opts?.limit }),
+ () =>
+ search(debounced, {
+ search_type: opts?.search_type,
+ limit: opts?.limit,
+ repo_id: opts?.repo_id,
+ }),
{ revalidateOnFocus: false },
);
return {
diff --git a/tests/unit/cli/test_command_target.py b/tests/unit/cli/test_command_target.py
new file mode 100644
index 000000000..54db4656a
--- /dev/null
+++ b/tests/unit/cli/test_command_target.py
@@ -0,0 +1,223 @@
+"""Unit tests for ``resolve_command_target`` — the workspace/single-repo router.
+
+Covers every decision branch listed in the docstring of
+``repowise.cli.helpers.resolve_command_target`` so the workspace
+auto-detection contract stays stable across refactors.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import click
+import pytest
+
+from repowise.cli.helpers import (
+ CommandTarget,
+ WorkspaceNotFound,
+ resolve_command_target,
+)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def fake_workspace(tmp_path: Path) -> Path:
+ """Build a workspace root with two child repos.
+
+ Layout:
+ tmp/
+ .repowise-workspace.yaml
+ backend/.git
+ backend/.repowise/state.json
+ frontend/.git
+ """
+ ws_root = tmp_path
+ backend = ws_root / "backend"
+ frontend = ws_root / "frontend"
+ (backend / ".git").mkdir(parents=True)
+ (frontend / ".git").mkdir(parents=True)
+
+ # Backend has been indexed (has its own state.json) — frontend has not.
+ (backend / ".repowise").mkdir()
+ (backend / ".repowise" / "state.json").write_text(
+ json.dumps({"last_sync_commit": "abc123", "docs_enabled": True}),
+ encoding="utf-8",
+ )
+
+ (ws_root / ".repowise-workspace.yaml").write_text(
+ "version: 1\n"
+ "default_repo: backend\n"
+ "repos:\n"
+ " - path: backend\n"
+ " alias: backend\n"
+ " is_primary: true\n"
+ " - path: frontend\n"
+ " alias: frontend\n",
+ encoding="utf-8",
+ )
+ return ws_root
+
+
+def chdir(monkeypatch):
+ """Convenience: chdir helper that uses monkeypatch.chdir."""
+
+ def _chdir(path: Path) -> None:
+ monkeypatch.chdir(path)
+
+ return _chdir
+
+
+# ---------------------------------------------------------------------------
+# Rule 1: --no-workspace forces single-repo mode
+# ---------------------------------------------------------------------------
+
+
+def test_no_workspace_flag_forces_single(fake_workspace, chdir):
+ chdir(fake_workspace)
+ target = resolve_command_target(no_workspace_flag=True)
+ assert target.mode == "single"
+ assert target.repo_path == fake_workspace
+ assert target.auto_detected is False
+
+
+def test_workspace_and_no_workspace_conflict(fake_workspace, chdir):
+ chdir(fake_workspace)
+ with pytest.raises(click.UsageError):
+ resolve_command_target(workspace_flag=True, no_workspace_flag=True)
+
+
+def test_repo_with_no_workspace_conflict(fake_workspace, chdir):
+ chdir(fake_workspace)
+ with pytest.raises(click.UsageError):
+ resolve_command_target(repo_alias="backend", no_workspace_flag=True)
+
+
+# ---------------------------------------------------------------------------
+# Rule 2: --workspace / --repo
+# ---------------------------------------------------------------------------
+
+
+def test_workspace_flag_loads_config(fake_workspace, chdir):
+ chdir(fake_workspace)
+ target = resolve_command_target(workspace_flag=True)
+ assert target.mode == "workspace"
+ assert target.ws_root == fake_workspace
+ assert target.ws_config is not None
+ assert target.auto_detected is False
+ assert target.repo_filter is None
+
+
+def test_repo_alias_implies_workspace(fake_workspace, chdir):
+ chdir(fake_workspace)
+ target = resolve_command_target(repo_alias="backend")
+ assert target.mode == "workspace"
+ assert target.repo_filter == "backend"
+
+
+def test_workspace_flag_raises_when_no_workspace(tmp_path, chdir):
+ chdir(tmp_path)
+ with pytest.raises(WorkspaceNotFound):
+ resolve_command_target(workspace_flag=True)
+
+
+def test_unknown_repo_alias_raises(fake_workspace, chdir):
+ chdir(fake_workspace)
+ with pytest.raises(click.UsageError):
+ resolve_command_target(repo_alias="bogus")
+
+
+# ---------------------------------------------------------------------------
+# Rule 3: explicit path argument
+# ---------------------------------------------------------------------------
+
+
+def test_explicit_path_to_workspace_root_auto_promotes(fake_workspace, tmp_path):
+ # Run from somewhere unrelated, but point path at the workspace root.
+ os.chdir(tmp_path)
+ target = resolve_command_target(path=str(fake_workspace))
+ assert target.mode == "workspace"
+ assert target.ws_root == fake_workspace
+ assert target.auto_detected is True
+
+
+def test_explicit_path_to_child_repo_stays_single(fake_workspace):
+ target = resolve_command_target(path=str(fake_workspace / "backend"))
+ assert target.mode == "single"
+ assert target.repo_path == fake_workspace / "backend"
+ # Workspace context surfaced for downstream commands' notice.
+ assert target.ws_root == fake_workspace
+
+
+# ---------------------------------------------------------------------------
+# Rule 4: no path, no flags — auto-detect
+# ---------------------------------------------------------------------------
+
+
+def test_cwd_is_workspace_root_auto_routes(fake_workspace, chdir):
+ chdir(fake_workspace)
+ target = resolve_command_target()
+ assert target.mode == "workspace"
+ assert target.auto_detected is True
+ assert "cwd is the workspace root" in target.reason
+
+
+def test_cwd_indexed_child_repo_stays_single(fake_workspace, chdir):
+ """If cwd has its own state.json, cd-into-repo wins over workspace."""
+ chdir(fake_workspace / "backend")
+ target = resolve_command_target()
+ assert target.mode == "single"
+ assert target.repo_path == fake_workspace / "backend"
+ # Workspace context retained for transparency notice.
+ assert target.ws_root == fake_workspace
+
+
+def test_cwd_unindexed_child_routes_to_workspace(fake_workspace, chdir):
+ """If cwd is under a workspace but has no .repowise/state.json, the
+ workspace is the more useful target."""
+ chdir(fake_workspace / "frontend")
+ target = resolve_command_target()
+ assert target.mode == "workspace"
+ assert target.auto_detected is True
+
+
+def test_plain_dir_stays_single(tmp_path, chdir):
+ plain = tmp_path / "plain"
+ plain.mkdir()
+ chdir(plain)
+ target = resolve_command_target()
+ assert target.mode == "single"
+ assert target.repo_path == plain
+ assert target.ws_root is None
+ assert target.auto_detected is False
+
+
+# ---------------------------------------------------------------------------
+# CommandTarget helpers
+# ---------------------------------------------------------------------------
+
+
+def test_primary_path_resolution(fake_workspace, chdir):
+ chdir(fake_workspace)
+ target = resolve_command_target()
+ assert target.primary_path() == fake_workspace / "backend"
+
+
+def test_resolve_repo_alias(fake_workspace, chdir):
+ chdir(fake_workspace)
+ target = resolve_command_target()
+ assert target.resolve_repo_alias("frontend") == fake_workspace / "frontend"
+ assert target.resolve_repo_alias("unknown") is None
+
+
+def test_is_workspace_property(fake_workspace, chdir):
+ chdir(fake_workspace)
+ assert resolve_command_target().is_workspace is True
+ chdir(fake_workspace / "backend")
+ assert resolve_command_target().is_workspace is False
diff --git a/tests/unit/cli/test_doctor_workspace.py b/tests/unit/cli/test_doctor_workspace.py
new file mode 100644
index 000000000..5cb08279b
--- /dev/null
+++ b/tests/unit/cli/test_doctor_workspace.py
@@ -0,0 +1,151 @@
+"""Tests for ``repowise doctor --workspace`` (Phase C2).
+
+Covers workspace-level validation: drift detection between
+``WorkspaceConfig.last_commit_at_index`` and per-repo ``state.json``,
+missing directory entries, and ``--repair`` behavior (drift sync + dead
+entry removal).
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+from click.testing import CliRunner
+
+from repowise.cli.commands.doctor_cmd import (
+ _check_mcp_registered,
+ _run_workspace_checks,
+ doctor_command,
+)
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+
+
+def _git_init(p: Path) -> None:
+ p.mkdir(parents=True, exist_ok=True)
+ subprocess.run(["git", "init"], cwd=str(p), capture_output=True)
+
+
+def _write_state(repo: Path, commit: str) -> None:
+ rdir = repo / ".repowise"
+ rdir.mkdir(exist_ok=True)
+ (rdir / "state.json").write_text(
+ json.dumps({"last_sync_commit": commit}), encoding="utf-8"
+ )
+
+
+def test_workspace_checks_detects_state_drift(tmp_path: Path) -> None:
+ backend = tmp_path / "backend"
+ _git_init(backend)
+ _write_state(backend, "real-sha-from-state")
+
+ cfg = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="backend",
+ alias="backend",
+ last_commit_at_index="stale-sha-in-config",
+ )],
+ )
+ cfg.save(tmp_path)
+
+ issues = _run_workspace_checks(tmp_path, cfg, repair=False)
+ assert any("drift" in i for i in issues), issues
+
+
+def test_workspace_checks_detects_missing_dir(tmp_path: Path) -> None:
+ cfg = WorkspaceConfig(
+ repos=[RepoEntry(path="ghost", alias="ghost")],
+ )
+ cfg.save(tmp_path)
+ issues = _run_workspace_checks(tmp_path, cfg, repair=False)
+ assert any("missing directory" in i for i in issues)
+
+
+def test_workspace_checks_repair_syncs_drift(tmp_path: Path) -> None:
+ backend = tmp_path / "backend"
+ _git_init(backend)
+ real_sha = "abc" * 14 # 42 chars (close enough)
+ _write_state(backend, real_sha)
+
+ cfg = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="backend",
+ alias="backend",
+ last_commit_at_index="OLD",
+ )],
+ )
+ cfg.save(tmp_path)
+
+ _run_workspace_checks(tmp_path, cfg, repair=True)
+ assert cfg.get_repo("backend").last_commit_at_index == real_sha
+
+
+def test_workspace_checks_repair_drops_dead_entries(tmp_path: Path) -> None:
+ backend = tmp_path / "backend"
+ _git_init(backend)
+ _write_state(backend, "deadbeef")
+ cfg = WorkspaceConfig(
+ repos=[
+ RepoEntry(
+ path="backend", alias="backend", last_commit_at_index="deadbeef",
+ ),
+ RepoEntry(path="ghost", alias="ghost"),
+ ],
+ default_repo="backend",
+ )
+ cfg.save(tmp_path)
+
+ _run_workspace_checks(tmp_path, cfg, repair=True)
+ aliases = cfg.repo_aliases()
+ assert "backend" in aliases
+ assert "ghost" not in aliases
+
+
+def test_workspace_checks_clean_workspace_has_no_issues(tmp_path: Path) -> None:
+ backend = tmp_path / "backend"
+ _git_init(backend)
+ sha = "f" * 40
+ _write_state(backend, sha)
+ cfg = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="backend", alias="backend", last_commit_at_index=sha,
+ )],
+ )
+ cfg.save(tmp_path)
+ issues = _run_workspace_checks(tmp_path, cfg, repair=False)
+ assert issues == []
+
+
+def test_doctor_command_workspace_flag_runs(tmp_path: Path) -> None:
+ """CliRunner smoke test — `repowise doctor --workspace` should not
+ crash on a workspace with one indexed repo."""
+ backend = tmp_path / "backend"
+ _git_init(backend)
+ sha = "0" * 40
+ _write_state(backend, sha)
+ # Create empty wiki.db so the per-repo db check has something to bite on.
+ (backend / ".repowise" / "wiki.db").write_bytes(b"")
+
+ cfg = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="backend", alias="backend",
+ is_primary=True, last_commit_at_index=sha,
+ )],
+ default_repo="backend",
+ )
+ cfg.save(tmp_path)
+
+ runner = CliRunner()
+ result = runner.invoke(
+ doctor_command, [str(tmp_path), "--workspace"],
+ )
+ # The per-repo db check may fail because wiki.db is an empty file,
+ # but the workspace doctor wiring must not crash.
+ assert result.exit_code == 0, result.output
+ assert "backend" in result.output
+
+
+def test_check_mcp_registered_does_not_crash(tmp_path: Path) -> None:
+ """Advisory check — never throws even when no claude_desktop_config exists."""
+ _check_mcp_registered(tmp_path)
diff --git a/tests/unit/cli/test_workspace_add_defaults.py b/tests/unit/cli/test_workspace_add_defaults.py
new file mode 100644
index 000000000..b3678b1cf
--- /dev/null
+++ b/tests/unit/cli/test_workspace_add_defaults.py
@@ -0,0 +1,111 @@
+"""Tests for the new ``repowise workspace add`` defaults.
+
+The most important behavior shift in Phase A: ``workspace add`` now runs
+index + docs by default, and surfaces an honest "no docs because ..."
+notice when generation is skipped. These tests pin the decision matrix
+in :func:`_resolve_docs_flag` so the auto-on/auto-off contract doesn't
+silently regress.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.workspace_cmd import _resolve_docs_flag
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+
+
+def ws(tmp_path: Path) -> tuple[Path, WorkspaceConfig]:
+ backend = tmp_path / "backend"
+ (backend / ".git").mkdir(parents=True)
+ (backend / ".repowise").mkdir(parents=True)
+ cfg = WorkspaceConfig(
+ version=1,
+ repos=[RepoEntry(path="backend", alias="backend", is_primary=True)],
+ default_repo="backend",
+ )
+ cfg.save(tmp_path)
+ return tmp_path, cfg
+
+
[email protected](autouse=True)
+def _clear_provider_env(monkeypatch):
+ """Strip every provider key so tests start from a clean slate."""
+ for key in (
+ "REPOWISE_PROVIDER",
+ "ANTHROPIC_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENROUTER_API_KEY",
+ "GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "DEEPSEEK_API_KEY",
+ "OLLAMA_BASE_URL",
+ ):
+ monkeypatch.delenv(key, raising=False)
+
+
+def test_explicit_yes_wins(ws):
+ ws_root, cfg = ws
+ docs, reason = _resolve_docs_flag(
+ run_docs=True, provider_name=None, ws_root=ws_root, ws_config=cfg,
+ )
+ assert docs is True
+ assert reason is None
+
+
+def test_explicit_no_records_reason(ws):
+ ws_root, cfg = ws
+ docs, reason = _resolve_docs_flag(
+ run_docs=False, provider_name=None, ws_root=ws_root, ws_config=cfg,
+ )
+ assert docs is False
+ assert reason == "--no-docs flag"
+
+
+def test_provider_flag_forces_on(ws):
+ ws_root, cfg = ws
+ docs, reason = _resolve_docs_flag(
+ run_docs=None,
+ provider_name="anthropic",
+ ws_root=ws_root,
+ ws_config=cfg,
+ )
+ assert docs is True
+ assert reason is None
+
+
+def test_inherits_primary_config(ws, monkeypatch):
+ ws_root, cfg = ws
+ # Drop a provider into the primary repo's config — that should be
+ # enough to flip the default to docs-on.
+ cfg_path = ws_root / "backend" / ".repowise" / "config.yaml"
+ cfg_path.write_text(
+ "provider: anthropic\nmodel: claude-sonnet-4-5\nembedder: gemini\n",
+ encoding="utf-8",
+ )
+ docs, reason = _resolve_docs_flag(
+ run_docs=None, provider_name=None, ws_root=ws_root, ws_config=cfg,
+ )
+ assert docs is True
+ assert reason is None
+
+
+def test_env_provider_forces_on(ws, monkeypatch):
+ ws_root, cfg = ws
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-fake")
+ docs, reason = _resolve_docs_flag(
+ run_docs=None, provider_name=None, ws_root=ws_root, ws_config=cfg,
+ )
+ assert docs is True
+
+
+def test_no_provider_anywhere_returns_off(ws):
+ ws_root, cfg = ws
+ docs, reason = _resolve_docs_flag(
+ run_docs=None, provider_name=None, ws_root=ws_root, ws_config=cfg,
+ )
+ assert docs is False
+ assert reason == "no provider configured"
diff --git a/tests/unit/cli/test_workspace_autodetect_e2e.py b/tests/unit/cli/test_workspace_autodetect_e2e.py
new file mode 100644
index 000000000..ea655740f
--- /dev/null
+++ b/tests/unit/cli/test_workspace_autodetect_e2e.py
@@ -0,0 +1,133 @@
+"""End-to-end-ish tests for the workspace auto-detect rewiring.
+
+These run real Click commands through :class:`CliRunner` so we catch
+regressions where the auto-detect helper was wired up incorrectly (e.g.
+stray ``.repowise/`` directories left behind, wrong workspace path
+resolved, error messages that hide the real fix).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands.status_cmd import status_command
+from repowise.cli.commands.update_cmd import update_command
+
+
+def _build_workspace(root: Path) -> None:
+ backend = root / "backend"
+ frontend = root / "frontend"
+ (backend / ".git").mkdir(parents=True)
+ (frontend / ".git").mkdir(parents=True)
+ (backend / ".repowise").mkdir()
+ (backend / ".repowise" / "state.json").write_text(
+ json.dumps({"last_sync_commit": "abc123", "docs_enabled": True}),
+ )
+ (root / ".repowise-workspace.yaml").write_text(
+ "version: 1\n"
+ "default_repo: backend\n"
+ "repos:\n"
+ " - path: backend\n"
+ " alias: backend\n"
+ " is_primary: true\n"
+ " - path: frontend\n"
+ " alias: frontend\n"
+ )
+
+
+def test_update_from_workspace_root_does_not_create_stray_repowise(
+ tmp_path: Path, monkeypatch
+):
+ """Regression: running ``repowise update`` from a workspace root used
+ to leave a stray ``<workspace>/.repowise/`` behind before erroring."""
+ _build_workspace(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ runner = CliRunner()
+ # Workspace mode auto-routes — the actual update call would try to
+ # spawn a real pipeline, so we intercept _workspace_update.
+ called = {}
+
+ def _fake_workspace_update(target, *, dry_run):
+ called["target"] = target
+ called["dry_run"] = dry_run
+
+ monkeypatch.setattr(
+ "repowise.cli.commands.update_cmd._workspace_update",
+ _fake_workspace_update,
+ )
+
+ result = runner.invoke(update_command, [], catch_exceptions=False)
+
+ assert result.exit_code == 0, result.output
+ assert called["target"].mode == "workspace"
+ assert called["target"].ws_root.resolve() == tmp_path.resolve()
+ # Critical: no stray .repowise/ directory created at the workspace root.
+ assert not (tmp_path / ".repowise").exists()
+
+
+def test_update_from_child_repo_stays_single(tmp_path: Path, monkeypatch):
+ _build_workspace(tmp_path)
+ monkeypatch.chdir(tmp_path / "backend")
+
+ runner = CliRunner()
+ called = {}
+
+ def _fake_workspace_update(*args, **kwargs):
+ called["workspace"] = True
+
+ monkeypatch.setattr(
+ "repowise.cli.commands.update_cmd._workspace_update",
+ _fake_workspace_update,
+ )
+
+ # The full single-repo path tries to do real work; we monkeypatch the
+ # downstream pipeline so the command can short-circuit. Easiest: stub
+ # the heavy imports by making get_head_commit return the same SHA so
+ # the "Already up to date" branch fires.
+ monkeypatch.setattr(
+ "repowise.cli.commands.update_cmd.get_head_commit",
+ lambda _p: "abc123",
+ )
+
+ result = runner.invoke(update_command, [], catch_exceptions=False)
+ assert result.exit_code == 0, result.output
+ assert "workspace" not in called
+ assert "Already up to date" in result.output or "single-repo" in result.output
+
+
+def test_update_with_no_workspace_flag_overrides_autodetect(
+ tmp_path: Path, monkeypatch
+):
+ """``--no-workspace`` from a workspace root should run the single-repo
+ code path on the workspace root and emit the helpful workspace hint."""
+ _build_workspace(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ runner = CliRunner()
+ result = runner.invoke(
+ update_command,
+ ["--no-workspace"],
+ catch_exceptions=False,
+ )
+ # Workspace root has no .repowise/state.json so single-repo update
+ # rightly errors — but the message must guide the user to --workspace.
+ assert result.exit_code != 0
+ assert "--workspace" in result.output
+
+
+def test_status_autodetects_workspace_with_docs_summary(tmp_path: Path, monkeypatch):
+ _build_workspace(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ runner = CliRunner()
+ result = runner.invoke(status_command, [], catch_exceptions=False)
+
+ assert result.exit_code == 0, result.output
+ # The honest docs summary should mention the un-doc'd repo.
+ assert "backend" in result.output
+ assert "frontend" in result.output
diff --git a/tests/unit/server/test_workspace_sidebar.py b/tests/unit/server/test_workspace_sidebar.py
new file mode 100644
index 000000000..89e20ec6b
--- /dev/null
+++ b/tests/unit/server/test_workspace_sidebar.py
@@ -0,0 +1,254 @@
+"""Tests for Phase B server endpoints — sidebar completeness, FTS fan-out,
+``/api/search`` ``repo_id`` filter, and the new ``/api/workspace/sync``
+job-fan-out endpoint.
+
+The fixtures here build a minimal "workspace mode" by populating
+``app.state.workspace_config`` + ``app.state.workspace_root`` directly,
+since spinning up a real ``lifespan()`` would require on-disk repos and
+multi-engine fixtures the rest of the suite doesn't use.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from pathlib import Path
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.search import FullTextSearch
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _build_workspace_dir(tmp_path: Path) -> tuple[Path, WorkspaceConfig]:
+ """Create a workspace root with two child repos.
+
+ backend/ is "indexed" (has .repowise/wiki.db) and frontend/ is not.
+ The wiki.db is created with the bare schema so we can later attach a
+ fresh SQLAlchemy engine and have :func:`init_db` accept it.
+ """
+ ws_root = tmp_path / "ws"
+ backend = ws_root / "backend"
+ frontend = ws_root / "frontend"
+ for d in (backend / ".git", frontend / ".git"):
+ d.mkdir(parents=True)
+ (backend / ".repowise").mkdir()
+ (backend / ".repowise" / "wiki.db").write_bytes(b"") # placeholder
+ (backend / ".repowise" / "state.json").write_text(
+ json.dumps(
+ {
+ "last_sync_commit": "abc",
+ "docs_enabled": False,
+ "docs_skip_reason": "cost gate declined",
+ }
+ )
+ )
+
+ cfg = WorkspaceConfig(
+ version=1,
+ repos=[
+ RepoEntry(path="backend", alias="backend", is_primary=True),
+ RepoEntry(path="frontend", alias="frontend"),
+ ],
+ default_repo="backend",
+ )
+ cfg.save(ws_root)
+ return ws_root, cfg
+
+
+async def _build_repo_engine(repo_path: Path):
+ """Create an in-memory engine pretending to be the per-repo DB and
+ seed it with one Repository row + a couple of pages so FTS queries
+ return something."""
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ sf = async_sessionmaker(engine, expire_on_commit=False)
+ from repowise.core.persistence import upsert_repository
+ from repowise.core.persistence.database import get_session
+
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session, name=repo_path.name, local_path=str(repo_path)
+ )
+ await session.commit()
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+ # Index a single page directly into FTS — we don't need a real
+ # wiki_pages row for the search router tests.
+ await fts.index("p1", "Auth module", "Authentication and JWT verification flow.")
+ return engine, sf, fts, repo.id
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+async def workspace_app(tmp_path, app):
+ """Augment the standard ``app`` fixture with workspace state."""
+ ws_root, ws_config = _build_workspace_dir(tmp_path)
+
+ # Build one real-ish "backend" engine, register it as a workspace
+ # session, and patch its FTS into the registry.
+ backend_path = ws_root / "backend"
+ engine, sf, fts, repo_id = await _build_repo_engine(backend_path)
+
+ # The primary engine in the conftest fixture has no repository row;
+ # for these tests we want the primary list_repos query to return the
+ # backend repo. Simplest fix: swap the primary session_factory for
+ # the backend's, so /api/repos sees the seeded backend repo.
+ app.state.session_factory = sf
+ app.state.engine = engine
+ app.state.fts = fts
+
+ app.state.workspace_config = ws_config
+ app.state.workspace_root = str(ws_root)
+ app.state.workspace_sessions = {repo_id: sf}
+ app.state.workspace_engines = [engine]
+ app.state.workspace_fts = {repo_id: fts}
+ app.state.workspace_vector_stores = {}
+
+ yield app, ws_root, ws_config, repo_id
+
+
+# ---------------------------------------------------------------------------
+# B1 — sidebar shows indexed + unindexed + status
+# ---------------------------------------------------------------------------
+
+
+async def test_list_repos_includes_unindexed_workspace_entries(
+ workspace_app, client: AsyncClient
+):
+ """Frontend pulled /api/repos and used to silently drop unindexed
+ workspace repos. Now they must appear as ``ws:<alias>`` synthetic
+ rows with status="needs_index"."""
+ _, ws_root, ws_config, _ = workspace_app
+
+ resp = await client.get("/api/repos")
+ assert resp.status_code == 200
+ items = resp.json()
+
+ by_alias = {r.get("workspace_alias"): r for r in items if r.get("workspace_alias")}
+ assert "backend" in by_alias
+ assert "frontend" in by_alias
+
+ assert by_alias["backend"]["workspace_status"] == "indexed"
+ assert by_alias["backend"]["is_primary"] is True
+ assert by_alias["backend"]["docs_enabled"] is False
+ assert "cost gate declined" in (by_alias["backend"]["docs_skip_reason"] or "")
+
+ assert by_alias["frontend"]["workspace_status"] == "needs_index"
+ assert by_alias["frontend"]["id"].startswith("ws:")
+ assert by_alias["frontend"]["docs_enabled"] is False
+
+
+# ---------------------------------------------------------------------------
+# B2 — search fans across workspace, accepts repo_id filter
+# ---------------------------------------------------------------------------
+
+
+async def test_search_fulltext_fans_across_workspace(workspace_app, client: AsyncClient):
+ _, _, _, repo_id = workspace_app
+
+ resp = await client.get(
+ "/api/search",
+ params={"query": "JWT", "search_type": "fulltext", "limit": 5},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert len(body) >= 1
+ assert any("Auth" in r["title"] for r in body)
+
+
+async def test_search_with_repo_id_scopes_to_one_repo(workspace_app, client: AsyncClient):
+ _, _, _, repo_id = workspace_app
+ resp = await client.get(
+ "/api/search",
+ params={"query": "JWT", "search_type": "fulltext", "repo_id": repo_id},
+ )
+ assert resp.status_code == 200
+ assert len(resp.json()) >= 1
+
+
+async def test_search_with_synthetic_repo_id_returns_empty(workspace_app, client: AsyncClient):
+ """Synthetic ``ws:<alias>`` IDs point at unindexed repos — search
+ must return [] rather than silently fall back to the primary."""
+ resp = await client.get(
+ "/api/search",
+ params={"query": "JWT", "search_type": "fulltext", "repo_id": "ws:frontend"},
+ )
+ assert resp.status_code == 200
+ assert resp.json() == []
+
+
+# ---------------------------------------------------------------------------
+# B4 — /api/workspace/sync — wire up the conftest router include first
+# ---------------------------------------------------------------------------
+
+
+async def workspace_app_with_workspace_router(workspace_app):
+ """The shared ``_create_test_app`` doesn't include the workspace
+ router, so add it here for the few tests that need it."""
+ app, *rest = workspace_app
+ from repowise.server.routers import workspace as ws_router
+
+ # Including the same router twice is harmless — FastAPI dedupes by
+ # path, but to keep the test isolation tidy we check membership.
+ if not any(r.path.startswith("/api/workspace") for r in app.routes):
+ app.include_router(ws_router.router)
+ return (app, *rest)
+
+
+async def test_workspace_sync_endpoint_skips_unindexed(
+ workspace_app_with_workspace_router, client: AsyncClient
+):
+ app, ws_root, ws_config, repo_id = workspace_app_with_workspace_router
+ # Repo path resolution needs the fake wiki.db to point at the right
+ # repo_id; the endpoint uses sqlite3.connect on disk to discover it.
+ # We seeded a placeholder; replace with a real schema containing the
+ # repo_id we generated in the fixture.
+ db_path = ws_root / "backend" / ".repowise" / "wiki.db"
+ conn = sqlite3.connect(str(db_path))
+ conn.execute(
+ "CREATE TABLE repositories (id TEXT PRIMARY KEY, name TEXT, local_path TEXT)"
+ )
+ conn.execute(
+ "INSERT INTO repositories(id, name, local_path) VALUES (?, ?, ?)",
+ (repo_id, "backend", str(ws_root / "backend")),
+ )
+ conn.commit()
+ conn.close()
+
+ resp = await client.post("/api/workspace/sync")
+ assert resp.status_code == 202, resp.text
+ body = resp.json()
+
+ # frontend has no wiki.db → skipped with helpful reason.
+ aliases = {r["alias"]: r for r in body["results"]}
+ assert aliases["frontend"]["status"] == "skipped"
+ assert "not indexed" in aliases["frontend"]["reason"]
+ # backend got a job (or was accepted) — exact value depends on
+ # whether the dummy job table is wired, but it must not error.
+ assert aliases["backend"]["status"] in {"accepted", "error", "skipped"}
+
+
+async def test_workspace_sync_unknown_alias_404s(
+ workspace_app_with_workspace_router, client: AsyncClient
+):
+ resp = await client.post("/api/workspace/sync", params={"repo_alias": "bogus"})
+ assert resp.status_code == 404
diff --git a/tests/unit/workspace/test_round_trip_e2e.py b/tests/unit/workspace/test_round_trip_e2e.py
new file mode 100644
index 000000000..ab251acc8
--- /dev/null
+++ b/tests/unit/workspace/test_round_trip_e2e.py
@@ -0,0 +1,153 @@
+"""End-to-end round-trip test for workspace robustness (Phase C3).
+
+Spins up three sibling git repos, runs ``update_workspace`` (first-time
+indexing path from C1), verifies the state model is consistent, adds a
+fourth repo manually, and re-runs the update. Then checks that the
+workspace config tracks ``last_commit_at_index`` correctly and that
+state.json drift detection works.
+
+Deliberately doesn't exercise LLM doc generation — that's covered by
+``test_workspace_cmd.py`` and would require a provider in CI. The
+contract this test enforces is the *plumbing*: ``.repowise/`` dirs
+created, ``state.json`` written, workspace config kept in sync.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+from repowise.core.workspace.update import (
+ sync_workspace_state_from_disk,
+ update_workspace,
+)
+
+
+def _git_repo(parent: Path, name: str, file_content: str = "x") -> Path:
+ p = parent / name
+ p.mkdir(parents=True)
+ subprocess.run(["git", "init"], cwd=str(p), capture_output=True)
+ subprocess.run(
+ ["git", "config", "user.email", "[email protected]"], cwd=str(p), capture_output=True,
+ )
+ subprocess.run(
+ ["git", "config", "user.name", "T"], cwd=str(p), capture_output=True,
+ )
+ (p / "main.py").write_text(f"# {name}\nprint('{file_content}')\n")
+ subprocess.run(["git", "add", "."], cwd=str(p), capture_output=True)
+ subprocess.run(
+ ["git", "commit", "-m", "initial"], cwd=str(p), capture_output=True,
+ )
+ return p
+
+
+def _head(p: Path) -> str:
+ r = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=str(p), capture_output=True, text=True,
+ )
+ return r.stdout.strip()
+
+
+def test_three_repo_workspace_round_trip(tmp_path: Path) -> None:
+ """Workspace with 3 sibling repos: first-time indexing fills every
+ repo's .repowise/ dir and state.json, the workspace config tracks
+ last_commit_at_index, and subsequent updates are idempotent
+ (skipped_reason=up_to_date)."""
+ a = _git_repo(tmp_path, "alpha", "alpha")
+ b = _git_repo(tmp_path, "beta", "beta")
+ g = _git_repo(tmp_path, "gamma", "gamma")
+
+ cfg = WorkspaceConfig(
+ repos=[
+ RepoEntry(path="alpha", alias="alpha", is_primary=True),
+ RepoEntry(path="beta", alias="beta"),
+ RepoEntry(path="gamma", alias="gamma"),
+ ],
+ default_repo="alpha",
+ )
+ cfg.save(tmp_path)
+
+ # First-time index across the workspace (no .repowise/ dirs yet).
+ results = asyncio.run(update_workspace(tmp_path, cfg))
+ by_alias = {r.alias: r for r in results}
+ assert set(by_alias) == {"alpha", "beta", "gamma"}
+
+ # Every repo got a .repowise/ dir + state.json + workspace config sync.
+ for repo_path, alias in [(a, "alpha"), (b, "beta"), (g, "gamma")]:
+ assert (repo_path / ".repowise").is_dir(), f"{alias} missing .repowise/"
+ state = json.loads((repo_path / ".repowise" / "state.json").read_text())
+ assert state["last_sync_commit"] == _head(repo_path)
+ entry = cfg.get_repo(alias)
+ assert entry is not None
+ assert entry.last_commit_at_index == _head(repo_path)
+ # First-time indexed repos get a clear "no docs yet" marker.
+ if by_alias[alias].first_time_indexed:
+ assert state.get("docs_enabled") is False
+ assert "docs_skip_reason" in state
+
+ # Second pass should be a no-op for all three.
+ results2 = asyncio.run(update_workspace(tmp_path, cfg))
+ assert all(r.skipped_reason == "up_to_date" for r in results2)
+
+
+def test_drift_recovery(tmp_path: Path) -> None:
+ """When a child repo is updated outside the workspace orchestrator,
+ ``sync_workspace_state_from_disk`` brings the workspace config back
+ into agreement with the on-disk state.json on the next update call."""
+ a = _git_repo(tmp_path, "alpha")
+ cfg = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="alpha", alias="alpha",
+ last_commit_at_index="stale-stale-stale",
+ )],
+ default_repo="alpha",
+ )
+ cfg.save(tmp_path)
+
+ # Pretend the user ran `repowise update` inside alpha directly,
+ # writing a state.json that the workspace config doesn't know about.
+ (a / ".repowise").mkdir(exist_ok=True)
+ (a / ".repowise" / "state.json").write_text(
+ json.dumps({"last_sync_commit": _head(a)})
+ )
+
+ changed = sync_workspace_state_from_disk(tmp_path, cfg)
+ assert changed == ["alpha"]
+ assert cfg.get_repo("alpha").last_commit_at_index == _head(a)
+
+
+def test_add_fourth_repo_round_trip(tmp_path: Path) -> None:
+ """After the initial workspace is indexed, programmatically adding a
+ new entry and running update_workspace indexes the new repo only."""
+ a = _git_repo(tmp_path, "alpha")
+ b = _git_repo(tmp_path, "beta")
+ cfg = WorkspaceConfig(
+ repos=[
+ RepoEntry(path="alpha", alias="alpha", is_primary=True),
+ RepoEntry(path="beta", alias="beta"),
+ ],
+ default_repo="alpha",
+ )
+ cfg.save(tmp_path)
+ asyncio.run(update_workspace(tmp_path, cfg))
+
+ # Add a third repo to the workspace.
+ g = _git_repo(tmp_path, "gamma")
+ cfg.add_repo(RepoEntry(path="gamma", alias="gamma"))
+ cfg.save(tmp_path)
+
+ results = asyncio.run(update_workspace(tmp_path, cfg))
+ by_alias = {r.alias: r for r in results}
+ # alpha + beta unchanged, gamma freshly indexed.
+ assert by_alias["alpha"].skipped_reason == "up_to_date"
+ assert by_alias["beta"].skipped_reason == "up_to_date"
+ assert by_alias["gamma"].updated or by_alias["gamma"].error
+ if by_alias["gamma"].updated:
+ assert by_alias["gamma"].first_time_indexed
+ assert (g / ".repowise").is_dir()
diff --git a/tests/unit/workspace/test_update.py b/tests/unit/workspace/test_update.py
index c2c8a4824..363232169 100644
--- a/tests/unit/workspace/test_update.py
+++ b/tests/unit/workspace/test_update.py
@@ -15,11 +15,86 @@ from repowise.core.workspace.update import (
check_repo_staleness,
count_commits_between,
get_head_commit,
+ read_state_commit,
run_cross_repo_hooks,
+ sync_workspace_state_from_disk,
update_workspace,
)
+# ---------------------------------------------------------------------------
+# sync_workspace_state_from_disk — Phase C1
+# ---------------------------------------------------------------------------
+
+
+class TestSyncWorkspaceStateFromDisk:
+ def test_picks_up_drifted_state_json(self, tmp_path: Path) -> None:
+ """When a child repo is updated outside the workspace orchestrator,
+ the workspace config drifts. sync_workspace_state_from_disk pulls
+ the real value from state.json."""
+ repo = _make_git_repo(tmp_path, "backend")
+ new_sha = "deadbeef" * 5 # 40 chars
+ _write_state(repo, new_sha)
+
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="backend",
+ alias="backend",
+ last_commit_at_index="stale-sha",
+ )],
+ )
+ ws_config.save(tmp_path)
+
+ changed = sync_workspace_state_from_disk(tmp_path, ws_config)
+ assert changed == ["backend"]
+ assert ws_config.get_repo("backend").last_commit_at_index == new_sha
+
+ def test_no_change_when_in_sync(self, tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path, "backend")
+ sha = "a" * 40
+ _write_state(repo, sha)
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="backend", alias="backend", last_commit_at_index=sha,
+ )],
+ )
+ ws_config.save(tmp_path)
+ assert sync_workspace_state_from_disk(tmp_path, ws_config) == []
+
+ def test_missing_dir_skipped(self, tmp_path: Path) -> None:
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(path="ghost", alias="ghost")],
+ )
+ assert sync_workspace_state_from_disk(tmp_path, ws_config) == []
+
+ def test_missing_state_json_skipped(self, tmp_path: Path) -> None:
+ _make_git_repo(tmp_path, "backend")
+ ws_config = WorkspaceConfig(
+ repos=[RepoEntry(
+ path="backend", alias="backend", last_commit_at_index="old",
+ )],
+ )
+ # No state.json written → entry preserved unchanged
+ assert sync_workspace_state_from_disk(tmp_path, ws_config) == []
+ assert ws_config.get_repo("backend").last_commit_at_index == "old"
+
+
+class TestReadStateCommit:
+ def test_returns_commit(self, tmp_path: Path) -> None:
+ repo = tmp_path / "r"
+ repo.mkdir()
+ _write_state(repo, "abc123")
+ assert read_state_commit(repo) == "abc123"
+
+ def test_missing_returns_none(self, tmp_path: Path) -> None:
+ assert read_state_commit(tmp_path) is None
+
+ def test_malformed_returns_none(self, tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "state.json").write_text("not json{")
+ assert read_state_commit(tmp_path) is None
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -255,8 +330,9 @@ class TestUpdateWorkspace:
with pytest.raises(ValueError, match="Unknown repo"):
asyncio.run(_run())
- def test_not_indexed_skipped(self, tmp_path: Path) -> None:
- """Repos without .repowise/ should be skipped."""
+ def test_first_time_index_runs_pipeline(self, tmp_path: Path) -> None:
+ """Repos without .repowise/ now get first-time indexing rather
+ than being silently skipped (Phase C1)."""
repo = _make_git_repo(tmp_path, "backend")
# No .repowise/ dir, no state.json
@@ -270,7 +346,14 @@ class TestUpdateWorkspace:
import asyncio
results = asyncio.run(_run())
assert len(results) == 1
- assert results[0].skipped_reason == "not_indexed"
+ # The pipeline ran (may have errored due to empty repo, but the
+ # important contract is: we did NOT short-circuit with skipped_reason).
+ assert results[0].skipped_reason != "not_indexed"
+ # Either the pipeline succeeded (updated=True, first_time flagged)
+ # or it errored — both prove we didn't bail early.
+ if results[0].updated:
+ assert results[0].first_time_indexed is True
+ assert (repo / ".repowise").is_dir()
def test_dry_run(self, tmp_path: Path) -> None:
"""Dry run should not perform any updates."""