Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
docs: restructure and refresh user-facing documentation (#741)
Raghav Chamadiya3a154329ce44
diff --git a/README.md b/README.mdindex cf4541612..f9ed45fef 100644--- a/README.md+++ b/README.md@@ -544,7 +544,7 @@ pricing: **[docs/COMMERCIAL.md](docs/COMMERCIAL.md)** · [Get in touch →](httprepowise init [PATH] # index codebase (one-time; --index-only skips LLM)repowise serve [PATH] # MCP server + local dashboardrepowise update [PATH] # incremental update (<30s; --workspace for all repos)-repowise query "<q>" # ask anything from the terminal+repowise search "<q>" # search the wiki (fulltext / semantic / symbol)repowise health # code-health KPIs + lowest-scoring filesrepowise risk main..HEAD # score a branch / PR range for defect riskrepowise dead-code # unreachable-code reportdiff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex 9fa04e0f2..af2ee44bb 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -2,6 +2,10 @@Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](QUICKSTART.md).+Command list (in `--help` order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `search`, `distill`, `expand`, `saved`, `corrections`, `export`, `hook`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).++**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. The exceptions: `init` (unless `--index-only` or `--mode fast`), `update` (unless `--index-only` or `--no-docs`), `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `health`, `risk`, `decision`, `coverage`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.+## 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:@@ -13,7 +17,7 @@ Most commands auto-detect whether you're in a workspace root and route according| `--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`.+The commands that grew these flags: `update`, `status`, `watch`, `doctor`, `costs`, `search`, `dead-code`, `decision`, `coverage`, `generate-claude-md`, `hook install/status/uninstall`.---@@ -39,18 +43,18 @@ repowise init .**What it does (4 phases):**-1. **Ingestion** — walks every file, parses AST with tree-sitter, builds a two-tier dependency graph (file + symbol nodes), indexes git history (churn, hotspots, ownership, bus factor)-2. **Analysis** — detects dead code, extracts architectural decisions from inline markers, READMEs, and git history. Runs Leiden community detection and execution flow tracing.-3. **Generation** — sends structured prompts to the LLM, generates file-level, module-level, and repo-level wiki pages-4. **Persistence** — stores everything in `.repowise/wiki.db`, builds search indexes, generates editor instruction files, registers MCP server and hooks+1. **Ingestion**, walks every file, parses AST with tree-sitter, builds a two-tier dependency graph (file + symbol nodes), indexes git history (churn, hotspots, ownership, bus factor)+2. **Analysis**, detects dead code, extracts architectural decisions from inline markers, READMEs, and git history. Runs Leiden community detection and execution flow tracing.+3. **Generation**, sends structured prompts to the LLM, generates file-level, module-level, and repo-level wiki pages+4. **Persistence**, stores everything in `.repowise/wiki.db`, builds search indexes, generates editor instruction files, registers MCP server and hooksIn workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (co-changes, contracts, package deps), workspace CLAUDE.md generation.**Interactive modes.** Running a bare `repowise init` on a TTY (no `--provider`, `--index-only`, or `--yes`) opens a menu:-1. **Everything** — index + AI docs. After picking a provider you can answer **"Customize?"** to tune any setting before the run.-2. **Index only** — graph, git, code health, dead code; no LLM, no cost. Answer **"Customize indexing?"** to set exclude patterns, commit limit, skip-tests/infra, submodules, and fast mode.-3. **Advanced** — full control. First choose **"Generate AI docs?"**; the prompts then split into an **Indexing** section (always) and a **Generation** section (provider, concurrency, embedder, wiki style, onboarding, decision harvesting, tiering — only when docs are on).+1. **Everything**, index + AI docs. After picking a provider you can answer **"Customize?"** to tune any setting before the run.+2. **Index only**, graph, git, code health, dead code; no LLM, no cost. Answer **"Customize indexing?"** to set exclude patterns, commit limit, skip-tests/infra, submodules, and fast mode.+3. **Advanced**, full control. First choose **"Generate AI docs?"**; the prompts then split into an **Indexing** section (always) and a **Generation** section (provider, concurrency, embedder, wiki style, onboarding, decision harvesting, tiering, only when docs are on).All three reach the indexing knobs; the LLM-only knobs appear only when docs are enabled. Passing any of the flags below (or `--yes`) skips the menu and runs non-interactively.@@ -60,31 +64,33 @@ All three reach the indexing knobs; the LLM-only knobs appear only when docs are|------|-------------|| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `opencode`, `mock` || `--model` | Model name override (e.g., `claude-sonnet-4-6`) |-| `--embedder` | Embedder for semantic search: `gemini`, `openai`, `mock` |+| `--embedder` | Embedder for semantic search: `gemini`, `openai`, `openrouter`, `ollama`, `mock` (default: auto-detect) || `--index-only` | Skip LLM generation. Only parse, build graph, and index git. Free. |-| `--mode` | Pipeline depth: `standard` (default) or `fast` (graph + essential-git only — no per-file blame/co-change, no LLM — for very large repos; upgrade later with `update --full`). |-| `--no-workspace` | Force single-repo mode even when invoked from a workspace root (indexes only the target PATH instead of fanning out across workspace repos). |-| `--wiki-style` | Documentation voice/density: `comprehensive` (default), `caveman` (token-condensed, AI-first), `reference` (API-manual), `tutorial` (beginner-friendly). Interactive full runs prompt when omitted. Saved to config so `update` keeps the style. See [WIKI_STYLES.md](WIKI_STYLES.md). |-| `--dry-run` | Show generation plan and cost estimate without running. |-| `--test-run` | Generate docs for only the top 10 files (by PageRank). |-| `--skip-tests` | Exclude test files from doc generation. |-| `--skip-infra` | Exclude infrastructure files (Dockerfiles, Makefiles, Terraform). |-| `--exclude / -x` | Gitignore-style exclusion patterns. Repeatable. |-| `--include-submodules` | Include git submodule directories. |-| `--concurrency` | Max concurrent LLM calls (default: 10). |-| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` (default: `auto`). |+| `--mode` | Pipeline depth: `standard` (default) or `fast` (graph + essential-git only, no per-file blame/co-change, no LLM, for very large repos; upgrade later with `update --full`) |+| `--skip-tests` | Exclude test files from doc generation |+| `--skip-infra` | Exclude infrastructure files (Dockerfiles, Makefiles, Terraform) |+| `--exclude` / `-x` | Gitignore-style exclusion pattern. Repeatable. |+| `--include-submodules` | Include git submodule directories (excluded by default) |+| `--concurrency` | Max concurrent LLM calls (default: 10) |+| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` (default: `auto`) || `--coverage` | Documentation coverage as a fraction of repo files (e.g. `0.10`, `0.20`, `0.50`). Bypasses the interactive coverage chooser. |-| `--onboarding / --no-onboarding` | Generate the curated Onboarding collection (up to 8 overview pages). Default: on; slots without enough signal are skipped. |-| `--harvest-decisions / --no-harvest-decisions` | Harvest architectural decisions during page generation (verified against source before storage). Default: on. |-| `--resume` | Resume from the last checkpoint if interrupted. |-| `--force` | Regenerate all pages even if they exist. |-| `--commit-limit` | Max commits to analyze per file (default: 500, max: 10000). |-| `--follow-renames` | Track file renames in git history. |-| `--no-claude-md` | Don't generate `CLAUDE.md`. |-| `--distill-hook / --no-distill-hook` | Install or skip the Distill command-rewrite hook (Claude Code PreToolUse). Strictly opt-in: interactive runs prompt (default No); `--no-distill-hook` also gates the repo off in config so a globally installed hook stays inert here. In workspace mode the verdict (prompt or flag) applies to every selected repo. See [DISTILL.md](DISTILL.md). |-| `--agents / --no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. |-| `--codex / --no-codex` | Generate or skip project-local Codex MCP/hooks setup. Interactive runs prompt when Codex CLI is installed and logged in; non-interactive runs require `--codex`. |-| `--yes / -y` | Skip confirmation prompts. |+| `--coverage-report` | Test-coverage report to ingest (LCOV / Cobertura / Clover). Repeatable. Auto-discovered when omitted. Distinct from `--coverage`, which controls documentation breadth. |+| `--onboarding` / `--no-onboarding` | Generate the curated Onboarding collection (up to 8 overview pages). Default: on; slots without enough signal are skipped. |+| `--harvest-decisions` / `--no-harvest-decisions` | Harvest architectural decisions during page generation (verified against source before storage). Default: on. |+| `--wiki-style` | Documentation voice/density: `comprehensive` (default), `caveman` (token-condensed, AI-first), `reference` (API-manual), `tutorial` (beginner-friendly). Interactive full runs prompt when omitted. Saved to config so `update` keeps the style. See [WIKI_STYLES.md](WIKI_STYLES.md). |+| `--resume` | Resume from the last checkpoint if interrupted |+| `--force` | Regenerate all pages even if they exist |+| `--commit-limit` | Max commits to analyze per file (default: 500, capped at 10000) |+| `--follow-renames` | Track file renames in git history |+| `--no-claude-md` | Don't generate `CLAUDE.md` |+| `--agents` / `--no-agents` | Generate or skip managed `AGENTS.md` for Codex. Persists the preference. |+| `--codex` / `--no-codex` | Generate or skip project-local Codex MCP/hooks setup. Interactive runs prompt when Codex CLI is installed and logged in; non-interactive runs require `--codex`. |+| `--distill-hook` / `--no-distill-hook` | Install or skip the Distill command-rewrite hook (Claude Code PreToolUse). Strictly opt-in: interactive runs prompt (default No); `--no-distill-hook` also gates the repo off in config so a globally installed hook stays inert here. In workspace mode the verdict applies to every selected repo. See [DISTILL.md](DISTILL.md). |+| `--yes` / `-y` | Skip confirmation prompts |+| `--dry-run` | Show generation plan and cost estimate without running |+| `--test-run` | Generate docs for only the top 10 files (by PageRank) |+| `--all` | In multi-repo mode, index every detected repo without prompting |+| `--no-workspace` | Force single-repo mode even when invoked from a workspace root (indexes only the target PATH instead of fanning out across workspace repos) |**Examples:**@@ -111,8 +117,8 @@ repowise init . --no-workspace # force single-repo, even### `repowise update [PATH]`Incrementally refresh the index for files changed since the last sync: the-dependency graph, git metadata, health and dead-code findings, and — when the-graph shape changed — the knowledge graph (layers, guided tour, entry points)+dependency graph, git metadata, health and dead-code findings, and, when the+graph shape changed, the knowledge graph (layers, guided tour, entry points)plus the exported `knowledge-graph.json`. In docs mode it also regenerates theaffected wiki pages. Index-only updates carry forward the previously generatedlayer names and node summaries, so no LLM call is ever made without docs mode.@@ -121,7 +127,7 @@ If any best-effort step fails (git metadata, decisions, dead code, ...), therun still exits 0 but lists the degraded steps in the completion panel (and inthe `done` event's `degraded` array with `--progress json`); the next updateretries them. In docs mode each regenerated page is persisted as it completes,-so an interrupted run never pays for the finished pages again — the rerun's+so an interrupted run never pays for the finished pages again, the rerun'sprompt-hash check skips them.**Options:**@@ -134,17 +140,20 @@ prompt-hash check skips them.| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`/`none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` || `--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 |+| `--workspace` / `-w` | 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 |-| `--full` | Upgrade a fast (`--mode fast`) index to a full one — see below. Single-repo only. |-| `--agents / --no-agents` | Generate or skip managed `AGENTS.md` after update. Persists the preference. |+| `--index-only` | Refresh the index only, skip doc regeneration for this run |+| `--docs` / `--no-docs` | Regenerate wiki pages for changed files, or skip doc regeneration entirely |+| `--full` | Upgrade a fast (`--mode fast`) index to a full one, see below. Single-repo only; errors in workspace mode. |+| `--no-cost-tracking` | Don't record LLM spend for this run |+| `--agents` / `--no-agents` | Generate or skip managed `AGENTS.md` after update. Persists the preference. || `-v`, `--verbose` | Show the full changed-file list and per-phase internals (cascade budget, decision-marker/evolution counts, best-effort skip warnings, detailed generation report). Off by default for a compact summary. || `--progress` | `rich` (default) for the interactive progress bar, or `json` for newline-delimited JSON events on stdout (for driving update from another process) |-**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.+**First-time indexing:** `update --workspace` 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.-**Upgrading a fast index to full (`--full`):** a repo first indexed with `repowise init --mode fast` has the full dependency graph + metrics persisted, but only the *essential* git tier (last commits, no per-file blame or co-change) and no LLM docs. `repowise update --full` upgrades it **incrementally**: it backfills the git tier to FULL (per-file blame + repo-wide co-change) using a resumable, checkpointed worker, then generates the docs that fast mode skipped. Crucially, it **reuses the persisted graph** — the dependency graph is rehydrated from SQL rather than re-parsed and re-resolved, so the expensive import/call/heritage resolution and centrality computation the fast index already did are not repeated. This is measurably cheaper than re-running a full `init`. The backfill is resumable: if it is interrupted, re-running `repowise update --full` picks it up. A provider is required (the fast index made no LLM calls), so pass `--provider`/`--model` or have one configured.+**Upgrading a fast index to full (`--full`):** a repo first indexed with `repowise init --mode fast` has the full dependency graph + metrics persisted, but only the *essential* git tier (last commits, no per-file blame or co-change) and no LLM docs. `repowise update --full` upgrades it **incrementally**: it backfills the git tier to FULL (per-file blame + repo-wide co-change) using a resumable, checkpointed worker, then generates the docs that fast mode skipped. Crucially, it **reuses the persisted graph**, the dependency graph is rehydrated from SQL rather than re-parsed and re-resolved, so the expensive import/call/heritage resolution and centrality computation the fast index already did are not repeated. This is measurably cheaper than re-running a full `init`. The backfill is resumable: if it is interrupted, re-running `repowise update --full` picks it up. A provider is required (the fast index made no LLM calls), so pass `--provider`/`--model` or have one configured. Single-repo only; it errors if run in workspace mode.**Examples:**@@ -165,9 +174,9 @@ repowise update --full --provider anthropic # upgrade a fast index to full### `repowise restyle [STYLE] [PATH]`Switch a repo's wiki **style** and regenerate every page in the new voice. Reuses-the existing index — the dependency graph and git metadata are rehydrated from+the existing index, the dependency graph and git metadata are rehydrated fromSQL (no re-resolution, no re-blame), so only the per-file parse + LLM generation-run. Requires a full (docs-enabled) index and a provider.+run. Requires a full (docs-enabled) index and a provider; fails on index-only repos.With no `STYLE`, prints the current style and the available choices.@@ -175,6 +184,16 @@ Styles only differ in voice and density; the markdown structure (headings,sections) stays the same, so search, the table of contents, and cross-links keepworking. See [WIKI_STYLES.md](WIKI_STYLES.md).+**Options:**++| Flag | Description |+|------|-------------|+| `--provider` | Override LLM provider for this run |+| `--model` | Override model |+| `--concurrency` | Max concurrent LLM calls (default: 12) |+| `--reasoning` | Reasoning mode for supported providers |+| `--yes` / `-y` | Skip the confirmation prompt |+```bashrepowise restyle # show current style + optionsrepowise restyle caveman # condensed, AI-first@@ -205,7 +224,7 @@ Start the API server and web UI.| Flag | Description ||------|-------------|-| `--port` | API server port (default: 7337) |+| `--port` | API server port (default: 7337; env `REPOWISE_PORT`) || `--host` | Host to bind to (default: 127.0.0.1) || `--workers` | Uvicorn workers (default: 1) || `--ui-port` | Web UI port (default: 3000) |@@ -219,9 +238,11 @@ repowise serve --port 8080 --ui-port 8081repowise serve --refresh-ui # bypass cache, pull latest UI tarball```+The web UI needs Node >= 20; without it `serve` falls back to API-only.+**Web UI sources, in order of precedence:**-1. **Local monorepo build** at `packages/web/.next/standalone/...` — used when the CLI is run from inside a checkout. The bundle's mtime is compared against source under `packages/web/`, `packages/ui/src/`, and `packages/types/src/`; if any source is newer the bundle is rebuilt with `npm run build` (or skipped if `npm` is unavailable).+1. **Local monorepo build** at `packages/web/.next/standalone/...`, used when the CLI is run from inside a checkout. The bundle's mtime is compared against source under `packages/web/`, `packages/ui/src/`, and `packages/types/src/`; if any source is newer the bundle is rebuilt with `npm run build` (or skipped if `npm` is unavailable).2. **Cached download** at `~/.repowise/web/`, keyed by the CLI version in `.version`.3. **Fresh download** of `repowise-web.tar.gz` from the GitHub release matching the CLI version.@@ -240,7 +261,7 @@ Watch for file changes and auto-update wiki pages. Press `Ctrl+C` to stop.| `--provider` | LLM provider || `--model` | Model override || `--debounce` | Delay in ms after last change (default: 2000) |-| `--workspace` | Watch all workspace repos |+| `--workspace` / `-w` | Watch all workspace repos || `--no-workspace` | Force single-repo mode || `--repo` | Watch a single workspace repo by alias |@@ -277,16 +298,9 @@ repowise search "rate limit" --repo backend # workspace, one reporepowise search "rate limit" --all # workspace, fan-out```------### `repowise query QUESTION [PATH]`--Ask a question about your codebase from the terminal.--```bash-repowise query "how does authentication work?"-repowise query "what files handle payment processing?"-```+For question answering and synthesized explanations (not keyword lookup), use+the MCP `get_answer` tool from your editor, or the **Chat** tab in the web UI+(`repowise serve`), there is no dedicated CLI command for this.---@@ -318,8 +332,10 @@ Detect dead and unused code.| `--safe-only` | Only show findings marked safe to delete || `--kind` | Filter: `unreachable_file`, `unused_export`, `unused_internal`, `zombie_package` || `--format` | Output: `table` (default), `json`, `md` |-| `--include-internals` | Include private/underscore symbols |-| `--include-zombie-packages` | Include unused declared packages |+| `--include-internals` / `--no-include-internals` | Include private/underscore symbols (default: off) |+| `--include-zombie-packages` / `--no-include-zombie-packages` | Include unused declared packages (default: on) |+| `--no-unreachable` | Skip unreachable-file findings |+| `--no-unused-exports` | Skip unused-export findings || `--repo` | In workspace mode, target a specific repo (defaults to primary) || `--workspace` / `--no-workspace` | Force workspace / single-repo mode |@@ -328,7 +344,6 @@ repowise dead-coderepowise dead-code --safe-only --min-confidence 0.8repowise dead-code --format jsonrepowise dead-code --repo backend # workspace, single repo-repowise dead-code resolve <id> # mark resolved / false positive```---@@ -336,8 +351,9 @@ repowise dead-code resolve <id> # mark resolved / false positive### `repowise risk [REVSPEC]`Just-in-time change-risk scoring for a commit or diff range. Scores the defect-risk of a change from the same calibrated signals the code-health layer uses —-no LLM calls. `REVSPEC` defaults to `HEAD`; pass a `base..head` range to score a+risk of a change from the same calibrated signals the code-health layer uses -+no LLM calls, and it works without `repowise init` (pure git + learned+constants). `REVSPEC` defaults to `HEAD`; pass a `base..head` range to score awhole branch / PR as one change.The headline is **repo-relative**: the change's percentile and review priority@@ -368,7 +384,7 @@ See [`docs/CHANGE_RISK.md`](./CHANGE_RISK.md) for the scoring model.### `repowise health [PATH]`-Compute per-file code-health scores from 25 deterministic markers (McCabe complexity, nesting, brain methods, LCOM4 cohesion, god classes, native clone detection, untested hotspots, coverage gradient, function/ownership/churn/change-entropy organizational risk, test-quality smells, and more). Zero LLM calls — pure Python over tree-sitter + git data. See [`docs/CODE_HEALTH.md`](./CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](./architecture/code-health.md) for the internals.+Compute per-file code-health scores from 25 deterministic markers (McCabe complexity, nesting, brain methods, LCOM4 cohesion, god classes, native clone detection, untested hotspots, coverage gradient, function/ownership/churn/change-entropy organizational risk, test-quality smells, and more). Zero LLM calls by default, pure Python over tree-sitter + git data. See [`docs/CODE_HEALTH.md`](./CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](./architecture/code-health.md) for the internals.**Options:**@@ -377,11 +393,13 @@ Compute per-file code-health scores from 25 deterministic markers (McCabe comple| `--file <path>` | Deep-dive a single file (relative path) || `--module <prefix>` | Restrict the report to files whose path starts with this prefix || `--refactoring-targets` | Print structured, graph-aware refactoring plans (Extract Class / Helper / Move Method / Break Cycle), ranked `impact × centrality × blast radius`. See [REFACTORING.md](REFACTORING.md) |+| `--generate-code <selector>` | Generate an actual refactoring patch for one target. The only `health` flag that calls an LLM; needs a configured provider. || `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) |-| `--coverage <path>` | Ingest a coverage report (LCOV / Cobertura / Clover). Repeat for multiple files |+| `--badge` | Print a shields.io-compatible badge URL/JSON for the repo's health score |+| `--coverage <path>` | Ingest a coverage report (LCOV / Cobertura / Clover). Repeatable. || `--coverage-format` | Override coverage-format auto-detection: `lcov`, `cobertura`, `clover` || `--format` | Output: `table` (default), `json`, `md` |-| `--safe-only` | Confidence ≥ 0.8 only (placeholder for v1 markers) |+| `--safe-only` | Documented no-op placeholder for a future confidence filter; has no effect today || `--repo` | In workspace mode, target a specific repo (defaults to primary) || `--no-workspace` | Force single-repo mode |@@ -390,12 +408,13 @@ repowise health # KPIs + lowest-scoring firepowise health --file packages/server/.../app.py # one file in detailrepowise health --module packages/server # restrict to a directoryrepowise health --refactoring-targets # ranked by impact / effort+repowise health --generate-code packages/server/app.py::handler # LLM patch for one targetrepowise health --trend # snapshot history + alertsrepowise health --coverage coverage.lcov # ingest coveragerepowise health --format json | jq .kpis # machine-readable```-`repowise init` and `repowise update` populate the health tables automatically —+`repowise init` and `repowise update` populate the health tables automatically -no separate command needed. `repowise status` shows a one-line summary(`Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: <path>)`).@@ -428,6 +447,37 @@ repowise decision health [PATH] # health dashboard---+### `repowise coverage`++Ingest and inspect test-coverage reports. Coverage is auto-discovered and+ingested during `init` / `update`; this group is the manual path, point it at+a report (or let it auto-discover one) to populate per-file line/branch+coverage, which clears `untested_hotspot` findings for files that are tested+regardless of where their tests live.++**Subcommands:**++```bash+repowise coverage add [PATHS...] # ingest one or more reports+repowise coverage status # show currently ingested coverage+```++**`add` options:**++| Flag | Description |+|------|-------------|+| `--path` | Repo path (defaults to cwd / workspace primary) |+| `--format` | Force a parser instead of auto-detecting: `lcov`, `cobertura`, `clover`, `repowise-json` |++```bash+repowise coverage add # discover coverage/lcov.info etc.+repowise coverage add coverage/lcov.info+repowise coverage add web.lcov api.lcov # merged, hit wins+repowise coverage status+```++---+### `repowise distill <command>`Run a command and print a compact, reversible rendering of its output. Noise@@ -467,7 +517,7 @@ repowise expand a1b2c3d4e5f6 -q "FAILED"### `repowise saved [PATH]`-Report tokens (and estimated dollars) saved by `repowise distill` — direct+Report tokens (and estimated dollars) saved by `repowise distill`, directinvocations and hook rewrites. Covers the distill command/hook path only; MCPresponse truncation is not part of this ledger.@@ -476,18 +526,21 @@ response truncation is not part of this ledger.| `--by` | Grouping: `filter` (default), `day`, `source` || `--since` | Only count savings since this ISO date || `--model` | Pricing model for the dollar estimate (input-token rate; default `claude-sonnet-4-6`) |+| `--missed` | Report commands that looked distillable but weren't rewritten |+| `--missed-days` | Window in days for `--missed` (default 7.0) |```bashrepowise saved # per-filter rollup + totalsrepowise saved --by day # daily rolluprepowise saved --since 2026-06-01+repowise saved --missed # what's slipping past the hook```---### `repowise corrections [PATH]`-Mine local agent transcripts for recurring command fumbles — consecutive runs+Mine local agent transcripts for recurring command fumbles, consecutive runsof the same base command where the first failed and a later variant succeeded(wrong tool, wrong path, unknown flag, missing argument). Report-only bydefault; entirely local. See [DISTILL.md](DISTILL.md#repowise-corrections--recurring-command-fumbles).@@ -528,6 +581,26 @@ repowise costs --repo backend # one workspace repo---+### `repowise export [PATH]`++Export wiki pages to files.++**Options:**++| Flag | Description |+|------|-------------|+| `--format` | `markdown` (default), `html`, `json` |+| `--output / -o` | Output directory (default: `.repowise/export`) |+| `--full` | Include decisions, dead code, hotspots, provenance metadata (JSON only) |++```bash+repowise export+repowise export --format json --full+repowise export --format html -o ./wiki/+```++---+## Workspace Commands### `repowise workspace list`@@ -538,7 +611,7 @@ 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.+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 ||------|-------------|@@ -546,6 +619,7 @@ Add a new repo to an existing workspace and index it.| `--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 |+| `--concurrency` | Max concurrent LLM calls for this repo's generation || `--primary` | Mark this repo as the workspace default |```bash@@ -558,10 +632,19 @@ repowise workspace add ../shared --no-index # register onlyRemove a repo from the workspace (does not delete files).-### `repowise workspace scan`+### `repowise workspace scan [PATH]`Re-scan the workspace directory for new repos not yet added.+| Flag | Description |+|------|-------------|+| `--yes` / `-y` | Auto-add all discovered repos without prompting |++```bash+repowise workspace scan+repowise workspace scan --yes+```+### `repowise workspace set-default <alias>`Change which repo is the default for MCP queries.@@ -570,6 +653,11 @@ Change which repo is the default for MCP queries.Explain the cross-repo contract link count: per-repo provider/consumer counts, unmatched consumers grouped by reason, and orphan providers (declared but never consumed).+| Flag | Description |+|------|-------------|+| `--repo` | Limit the report to one repo alias |+| `--json` | Emit raw diagnostics JSON |+```bashrepowise workspace diagnostics # human-readable reportrepowise workspace diagnostics --json # raw JSON@@ -580,11 +668,28 @@ repowise workspace diagnostics --repo api # limit to one repo aliasArchitecture lint: check the declared `conformance:` rules against the system graph and detect dependency cycles. Exits non-zero on any finding, so it gates CI.+| Flag | Description |+|------|-------------|+| `--json` | Emit the raw conformance report as JSON |+```bashrepowise workspace check # human-readable report; exit 1 on findingsrepowise workspace check --json # raw report JSON```+### `repowise workspace metrics [PATH]`++Architecture-complexity metrics over the system graph built by `repowise update --workspace`: propagation cost (how coupled the whole system is), the cyclic core (which services form circular dependency groups), and a single deterministic 1-10 score. Uses structural edges only (co-change is excluded); declared conformance violations, if any, are folded into the score. Requires a system graph, run `repowise update --workspace` first.++| Flag | Description |+|------|-------------|+| `--json` | Emit the raw metrics as JSON |++```bash+repowise workspace metrics+repowise workspace metrics --json+```+See [Workspaces](WORKSPACES.md) for the full multi-repo guide.---@@ -624,8 +729,8 @@ See [Auto-Sync](AUTO_SYNC.md) for all sync methods (hooks, file watcher, webhookManage the Distill command-rewrite hooks (Claude Code + Codex PreToolUse).When installed, noisy agent commands (tests, builds, git status/log/diff,-searches, listings) are rewritten to `repowise distill <command>` — pending-your approval by default — so the agent sees a compact, errors-first+searches, listings) are rewritten to `repowise distill <command>`, pending+your approval by default, so the agent sees a compact, errors-firstrendering.```bash@@ -636,16 +741,16 @@ repowise hook rewrite uninstall # removes only the repowise entries````install` also re-enables the target's `distill.commands` config if a prior-`repowise init` opt-out had gated it off — the target repo by default, or+`repowise init` opt-out had gated it off, the target repo by default, orevery workspace repo with `--workspace`/`-w` (accepts an optional `PATH` and`--no-workspace`, like `repowise hook install`). `uninstall` removes theglobal hook entries plus the repo's AGENTS.md awareness section and leavesper-repo config untouched. Per-repo posture (`permission: ask | allow`,per-family overrides) lives under `distill.commands` in-`.repowise/config.yaml` — see [DISTILL.md](DISTILL.md#configuration).+`.repowise/config.yaml`, see [DISTILL.md](DISTILL.md#configuration).When `~/.codex` exists, `install` also writes a Codex hook entry to-`~/.codex/hooks.json` (Codex ≥ 0.137 only — older builds can't apply a+`~/.codex/hooks.json` (Codex ≥ 0.137 only, older builds can't apply arewrite) and maintains an "Output Distillation" section in the repo's`AGENTS.md` that works without any hook. Codex cannot show a rewrittencommand for approval, so there rewrites fire only for families set to@@ -668,27 +773,45 @@ If `PATH` is omitted, `repowise mcp` first walks upward from the current directo|------|-------------|| `--transport` | `stdio` (default, for editors), `streamable-http` (for HTTP clients), or `sse` (legacy) || `--port` | Port for HTTP/SSE transports (default: 7338) |+| `--tools` | Override which tools are exposed. A comma-separated list is an explicit allowlist; prefix names with `+`/`-` to adjust the default set (e.g. `+get_dependency_path,-get_dead_code`). Overrides the `mcp.tools` config block. |+| `--all` | Expose every available tool, including opt-in and workspace tools |```bashrepowise mcp --transport stdio # for Claude Code, Codex, Cursor, etc.repowise mcp --transport streamable-http # for HTTP clientsrepowise mcp --transport sse --port 7338 # legacy SSE+repowise mcp --tools "+get_dependency_path,-get_dead_code"+repowise mcp --all```-See [MCP Tools](MCP_TOOLS.md) for all 9 exposed tools.+See [MCP Tools](MCP_TOOLS.md) for all exposed tools.---### `repowise generate-claude-md [PATH]`-Generate or update `CLAUDE.md` with codebase intelligence. Custom instructions at the top are preserved.+Generate or update `CLAUDE.md` with codebase intelligence. Custom instructions above the Repowise markers are preserved; the managed section between markers is auto-updated from the index.++**Options:**++| Flag | Description |+|------|-------------|+| `--output` | Write to a custom path (default: `.claude/CLAUDE.md`) |+| `--stdout` | Print generated content to stdout instead of writing a file |+| `--workspace` / `-w` | 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` | Force single-repo mode even when invoked from a workspace |++Auto-detects workspace mode when invoked from a workspace root.```bashrepowise generate-claude-mdrepowise generate-claude-md -o custom-path.mdrepowise generate-claude-md --stdout+repowise generate-claude-md --workspace # workspace-level CLAUDE.md```+`repowise init` and `repowise update` keep it current automatically; you rarely need to run this directly.+---### `AGENTS.md`@@ -697,29 +820,16 @@ repowise generate-claude-md --stdout----### `repowise export [PATH]`+### `repowise reindex [PATH]`-Export wiki pages to files.+Rebuild the vector search index by re-embedding all wiki pages. No LLM calls, only embedding API calls.**Options:**| Flag | Description ||------|-------------|-| `--format` | `markdown` (default), `html`, `json` |-| `--output / -o` | Output directory (default: `.repowise/export`) |-| `--full` | Include decisions, dead code, hotspots, provenance metadata (JSON only) |--```bash-repowise export-repowise export --format json --full-repowise export --format html -o ./wiki/-```-------### `repowise reindex [PATH]`--Rebuild vector search index from existing wiki pages.+| `--embedder` | `gemini`, `openai`, `openrouter`, `ollama`, `mock`, or `auto` (default: auto) |+| `--batch-size` | Embedding batch size (default: 32) |```bashrepowise reindex@@ -735,7 +845,9 @@ Run health checks on the wiki setup. Auto-detects workspace mode; in workspace m| 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 |+| `--workspace` / `-w` | Force workspace mode |+| `--no-workspace` | Force single-repo mode |+| `--format` | Output: `table` (default) or `json` |```bashrepowise doctor # auto-detects@@ -752,8 +864,7 @@ shows both the `repowise` resolved on your `PATH` and the command that launchedthe current process, since these can differ. This check is advisory: it neverupdates anything automatically and does not fail `doctor` when PyPI isunreachable. After upgrading, **restart Claude/Codex/Cursor or any MCP client**-so it picks up the new executable. (A standalone `repowise version --check` may-be added later.)+so it picks up the new executable.**Distill checks.** `doctor` also validates the `distill:` config block(unknown keys, bad permission values, unknown filter names, non-positive store@@ -787,6 +898,57 @@ non-blocking notice when a newer release is available on PyPI. See---+### `repowise telemetry`++Inspect and control anonymous, opt-out usage telemetry.++```bash+repowise telemetry status # show whether telemetry is enabled, and why+repowise telemetry enable+repowise telemetry disable+```++---++### `repowise login`++Sign in to your hosted repowise.dev account. This is unrelated to LLM provider+keys (`--provider`/`--model` elsewhere), it adds the hosted layer: your+indexed repos on repowise.dev, reindex from local tools, and account status in+`doctor`. Every local feature works without signing in.++Sign-in is browser-based OAuth with PKCE by default: the command opens the+hosted consent page and stores tokens at `~/.repowise/credentials.json`.++| Flag | Description |+|------|-------------|+| `--with-token` | Paste a personal API key (`rw_live_...`) instead of using the browser. Reads from stdin when piped, otherwise prompts. For SSH/headless machines. |+| `--device-name` | Label this machine in your connected apps (default: hostname) |++```bash+repowise login # browser sign-in+repowise login --with-token # headless, paste an API key+repowise login --device-name "build-box"+```++### `repowise logout`++Sign out of your Repowise account on this machine (best-effort server-side revocation, local credentials always removed).++```bash+repowise logout+```++### `repowise whoami`++Show the Repowise account this machine is signed in to.++```bash+repowise whoami+```++---+### `repowise delete [REPO_ID]`Delete a repository's index and all stored intelligence (wiki, graph, embeddings,@@ -807,4 +969,8 @@ repowise delete <repo-id> --force # delete a specific repo's index, no pr### `repowise augment`-Hook-driven context enrichment engine. Not meant to be called manually — invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment and stale-wiki checks; Codex uses it for `SessionStart`, `UserPromptSubmit`, and `PostToolUse` lifecycle guidance.+Hook-driven context enrichment engine. Not meant to be called manually, invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment and stale-wiki checks; Codex uses it for `SessionStart`, `UserPromptSubmit`, and `PostToolUse` lifecycle guidance.++### `repowise-augment` / `repowise-rewrite`++Two separate console scripts (not `repowise` subcommands) installed alongside the CLI: `repowise-augment` is an import-isolated entry point for the Claude Code/Codex augment hooks above; `repowise-rewrite` backs the Distill command-rewrite hook (`repowise hook rewrite install`). Neither is meant to be run by hand.diff --git a/docs/CONFIG.md b/docs/CONFIG.mdindex 6f082e9a9..77796bd55 100644--- a/docs/CONFIG.md+++ b/docs/CONFIG.md@@ -11,13 +11,14 @@ repo root on first `init`.```.repowise/-├── wiki.db # SQLite database: all pages, symbols, graph, git metadata, decisions-├── lancedb/ # Vector search index (LanceDB)-├── omissions/ # Distill omission store + savings ledger (omissions.db)-├── config.yaml # Provider, model, embedder, exclude patterns-├── state.json # Last sync commit, page counts, token usage-├── mcp.json # MCP server configuration-└── .env # API keys (gitignored automatically)+├── wiki.db # SQLite database: all pages, symbols, graph, git metadata, decisions+├── lancedb/ # Vector search index (LanceDB)+├── omissions/ # Distill omission store + savings ledger (omissions.db)+├── config.yaml # Provider, model, embedder, exclude patterns, distill/mcp/refactoring blocks+├── health-rules.json # Per-file code-health marker overrides+├── state.json # Last sync commit, page counts, token usage+├── mcp.json # MCP server configuration+└── .env # API keys (gitignored automatically)```repowise adds `.repowise/` to your `.gitignore` automatically. The directory@@ -30,31 +31,66 @@ should not be committed; it's a local cache, not a source of truth.The main configuration file. Created after first `init`, updated when you passflags like `--commit-limit`, `--follow-renames`, or `--wiki-style`.+> **No schema validation.** `config.yaml` is loaded as a plain YAML dict.+> Unknown or misspelled keys are silently ignored, they won't error and won't+> take effect. The only part that's validated is the `distill:` block, and+> only when you run `repowise doctor`. If a setting doesn't seem to be taking+> effect, check spelling and indentation first.+```yaml-provider: anthropic # LLM provider-model: claude-sonnet-4-6 # Model identifier-embedder: gemini # Embedding provider-reasoning: auto # auto | off | minimal-wiki_style: comprehensive # comprehensive | caveman | reference | tutorial+provider: anthropic # LLM provider (auto-detected if omitted)+model: claude-sonnet-4-6 # Model identifier (provider default if omitted)+embedder: mock # Embedding provider (mock if no key detected)+embedding_model: text-embedding-3-small # Embedding model (provider default if omitted)+reasoning: auto # auto | off | none | minimal | low | medium | high | xhigh | max+commit_limit: 500 # Max commits per file for git analysis (clamped 1-10000)+follow_renames: false # Track file renames in git history+wiki_style: comprehensive # comprehensive | caveman | reference | tutorial | custom+enable_onboarding: true # Show first-run onboarding promptsexclude_patterns: # Gitignore-style patterns- vendor/- "*.generated.*"- proto/-commit_limit: 500 # Max commits per file for git analysis-follow_renames: false # Track file renames in git history++distill: # see "The distill: block" below+ enabled: true++mcp: # see "The mcp: block" below+ tools: ["+get_execution_flows", "-get_dead_code"]++refactoring: # see "The refactoring: block" below+ enabled: true```You can edit this file directly. Changes take effect on the next `init`,`update`, or `serve` run.+| Key | Default | Meaning |+|-----|---------|---------|+| `provider` | auto-detected | `anthropic`, `openai`, `gemini`, `openrouter`, `deepseek`, `ollama`, `litellm`, `opencode` |+| `model` | provider default | Model identifier passed to the provider |+| `embedder` | `mock` | `openai`, `gemini`, `ollama`, `openrouter`, `mock` |+| `embedding_model` | provider default | Embedding model identifier |+| `reasoning` | `auto` | `auto`, `off`, `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` |+| `commit_limit` | `500` | Max commits per file walked for git analysis, clamped to 1-10000 |+| `follow_renames` | `false` | Track file renames through git history |+| `exclude_patterns` | `[]` | Extra gitignore-style patterns, on top of `.gitignore` |+| `wiki_style` | `comprehensive` | `comprehensive`, `caveman`, `reference`, `tutorial`, `custom` |+| `enable_onboarding` | `true` | Show first-run onboarding prompts (CLI and web) |+| `distill` | see below | Output distillation config |+| `mcp` | see below | MCP tool surface config |+| `refactoring` | see below | Refactoring-intelligence config |+`reasoning` controls documentation-generation calls for reasoning-capable chat-models. `auto` preserves provider defaults. `off` disables Qwen3-style thinking-for OpenAI-compatible vLLM/SGLang endpoints (sends-`extra_body.chat_template_kwargs.enable_thinking=false`) and maps to OpenRouter's-`reasoning.effort=none` for effort-capable OpenRouter model families. `minimal`-requests OpenAI's lowest supported reasoning effort for supported OpenAI-reasoning models and maps to OpenRouter's `reasoning.effort=minimal`. Providers-or models that cannot translate an explicit mode fail before making an API call.+models. `auto` preserves provider defaults. `off`/`none` disable Qwen3-style+thinking for OpenAI-compatible vLLM/SGLang endpoints (sends+`extra_body.chat_template_kwargs.enable_thinking=false`) and map to+OpenRouter's `reasoning.effort=none` for effort-capable OpenRouter model+families. `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` request the+matching effort level from providers and model families that support it (for+example OpenAI reasoning models and OpenRouter's `reasoning.effort`).+Providers or models that cannot translate an explicit mode fail before making+an API call.`wiki_style` controls the voice and density of generated wiki pages. Set it with`init --wiki-style` or switch later with `repowise restyle <style>` (which also@@ -65,7 +101,12 @@ existing pages, use `restyle`.> **Code-health rules** are configured separately in> `.repowise/health-rules.json` (per-file marker overrides); see-> [CODE_HEALTH.md](CODE_HEALTH.md#configuration).+> [The `health-rules.json` file](#the-health-rulesjson-file) below.++**Not stored in `config.yaml`:** `--skip-tests`, `--skip-infra`, and+`--include-submodules` are CLI-flag-only for a given run; they don't persist+to `config.yaml`. `--include-submodules` is recorded in `state.json` instead+(workspace state), not in `config.yaml`.### The `distill:` block@@ -77,14 +118,14 @@ distill:enabled: true # master switch for this repocommands:enabled: true # the command path (CLI + hook rewrites)- permission: ask # ask | allow | off (rewrite-hook posture)- families: # per-filter overrides- test_output: allow # auto-allow rewrites for test runs- git_diff: deny # never rewrite git diff here- disabled_filters: [] # filters to skip entirely, e.g. [logs]+ permission: ask # ask | allow | off (rewrite-hook posture)+ families: # per-filter overrides+ test_output: allow # auto-allow rewrites for test runs+ git_diff: deny # never rewrite git diff here+ disabled_filters: [] # filters to skip entirely, e.g. [logs]omission_store:- ttl_days: 7 # prune stored omissions after this many days- max_mb: 50 # size cap; oldest entries pruned first+ ttl_days: 7 # prune stored omissions after this many days+ max_mb: 50 # size cap; oldest entries pruned first```- `permission: ask` (the default) means the agent's rewritten command is shown@@ -130,11 +171,11 @@ refactoring:enabled: true # the deterministic plans (zero LLM, in the health pass)detectors:disabled: [] # e.g. [move_method] to silence one detector- min_confidence: low # low | medium | high (confidence floor)+ min_confidence: null # low | medium | high (confidence floor; null = no floor)llm:enabled: true # code generation, on by default; set false to disableprovider: null # falls back to the repo's configured LLM provider- model: null+ model: null # falls back to the repo's configured model```- The deterministic layer is **zero-LLM** and runs in the `init` / `update`@@ -153,6 +194,49 @@ refactoring:---+## The `health-rules.json` file++A separate JSON file (not part of `config.yaml`) that tunes code-health+biomarkers: which ones run, their severity, and per-path overrides. Malformed+JSON never raises, repowise warns and falls back to an empty config.++```json+{+ "profile": null,+ "disabled_biomarkers": [],+ "severity_overrides": {+ "high_churn": "low"+ },+ "rules": [+ {+ "path": "legacy/**",+ "disabled_biomarkers": ["long_function"],+ "severity_overrides": {+ "duplication": "critical"+ }+ }+ ]+}+```++| Key | Default | Meaning |+|-----|---------|---------|+| `profile` | `null` | Named calibration profile; only `"small-team"` is defined today |+| `disabled_biomarkers` | `[]` | Biomarker names to skip repo-wide |+| `severity_overrides` | `{}` | Maps a biomarker name to a severity label |+| `rules[]` | `[]` | Per-path overrides, evaluated in order |+| `rules[].path` | required | Glob matched against the file path (aliases `path_glob` and `glob` are also accepted and treated the same) |+| `rules[].disabled_biomarkers` | `[]` | Biomarkers to skip for files matching `path` |+| `rules[].severity_overrides` | `{}` | Severity overrides for files matching `path` |++Valid severity labels are `low`, `medium`, `high`, `critical`. Only the+severity **label** is overridable this way, never the underlying numeric+weights or caps that produce the health score.++Full reference: [CODE_HEALTH.md](CODE_HEALTH.md#configuration).++---+## LLM providers### Anthropic (Claude)@@ -185,9 +269,10 @@ export OPENAI_BASE_URL="http://localhost:8000/v1"repowise init --provider openai --model qwen3 --reasoning off```-For OpenRouter:+### OpenRouter```bash+export OPENROUTER_API_KEY="sk-or-..."repowise init --provider openrouter --model openai/gpt-5 --reasoning minimalrepowise init --provider openrouter --model x-ai/grok-4 --reasoning off```@@ -201,6 +286,13 @@ repowise init --provider geminiGemini is also the default embedding provider when `GEMINI_API_KEY` is set.+### DeepSeek++```bash+export DEEPSEEK_API_KEY="..."+repowise init --provider deepseek --model deepseek-chat+```+### Ollama (local, no API key)```bash@@ -235,14 +327,20 @@ The embedder is separate from the LLM provider.|----------|---------|-------|| `gemini` | `GEMINI_API_KEY` | Default when key is present || `openai` | `OPENAI_API_KEY` | OpenAI `text-embedding-3-small` |+| `openrouter` | `OPENROUTER_API_KEY` | Routed through OpenRouter || `ollama` | `OLLAMA_EMBEDDING_MODEL` | Local Ollama embeddings, no API key |-| `mock` | n/a | Dummy embeddings, no semantic search |+| `mock` | n/a | Dummy embeddings, no semantic search (default when no key is detected) |```bashrepowise init --embedder openairepowise reindex --embedder gemini # switch embedder and rebuild index```+`REPOWISE_EMBEDDING_MODEL` overrides the model for whichever embedder is+active. `REPOWISE_EMBEDDING_DIMS` and `REPOWISE_EMBEDDING_TIMEOUT` apply the+same way; the `OLLAMA_EMBEDDING_*` variants below are Ollama-specific+equivalents.+---## BYOK (Bring Your Own Key)@@ -259,23 +357,82 @@ The `.repowise/.env` file is gitignored automatically.## Environment variables+### Provider API keys+| Variable | Description ||----------|-------------|| `ANTHROPIC_API_KEY` | Anthropic API key || `OPENAI_API_KEY` | OpenAI API key || `GEMINI_API_KEY` / `GOOGLE_API_KEY` | Google Gemini API key |+| `OPENROUTER_API_KEY` | OpenRouter API key |+| `DEEPSEEK_API_KEY` | DeepSeek API key |+| `LITELLM_API_KEY` | LiteLLM proxy key |+| `LITELLM_API_BASE` | LiteLLM proxy base URL |++### Provider base URLs++| Variable | Description |+|----------|-------------|+| `ANTHROPIC_BASE_URL` | Override the Anthropic API base URL |+| `OPENAI_BASE_URL` | Override the OpenAI API base URL (used for vLLM/SGLang-compatible endpoints) |+| `GEMINI_BASE_URL` | Override the Gemini API base URL || `OLLAMA_BASE_URL` | Ollama server URL (default: `http://localhost:11434`) |+| `DEEPSEEK_BASE_URL` | Override the DeepSeek API base URL |+| `LITELLM_BASE_URL` | Override the LiteLLM proxy base URL |++### Provider and model overrides++| Variable | Description |+|----------|-------------|+| `REPOWISE_PROVIDER` | Override provider (skips auto-detection) |+| `REPOWISE_MODEL` | Override model |+| `REPOWISE_DOC_MODEL` | Override the model used for `get_answer` synthesis specifically |+| `REPOWISE_REASONING` | Override `reasoning` (see valid values above) |++### Embeddings++| Variable | Description |+|----------|-------------|+| `REPOWISE_EMBEDDER` | Embedder: `gemini`, `openai`, `ollama`, `openrouter`, or `mock` |+| `REPOWISE_EMBEDDING_MODEL` | Embedding model, applies to any embedder |+| `REPOWISE_EMBEDDING_DIMS` | Embedding output dimensions (optional; inferred from the model otherwise) |+| `REPOWISE_EMBEDDING_TIMEOUT` | Embed request timeout in seconds || `OLLAMA_EMBEDDING_MODEL` | Ollama embedding model (also selects the `ollama` embedder) || `OLLAMA_EMBEDDING_DIMS` | Ollama embedding output dimensions (optional; inferred from the model otherwise) || `OLLAMA_EMBEDDING_TIMEOUT` | Ollama embed request timeout in seconds (default: `30`); raise it for long pages on slow local models |-| `LITELLM_API_KEY` | LiteLLM proxy key |-| `REPOWISE_PROVIDER` | Override provider (skips auto-detection) |-| `REPOWISE_EMBEDDER` | Embedder: `gemini`, `openai`, or `mock` |++### Server and database++| Variable | Description |+|----------|-------------|| `REPOWISE_DB_URL` | Use PostgreSQL instead of SQLite (e.g. `postgresql+asyncpg://...`) |+| `REPOWISE_DATABASE_URL` | Legacy alias for `REPOWISE_DB_URL`, still honored || `REPOWISE_HOST` | API server host (default: `127.0.0.1`) || `REPOWISE_PORT` | API server port (default: `7337`) || `REPOWISE_MCP_PORT` | MCP SSE server port (default: `7338`) || `REPOWISE_API_URL` | Frontend only; backend URL for the web UI (default: `http://localhost:7337`) |+| `REPOWISE_API_KEY` | Bearer token required by clients calling the server API |+| `REPOWISE_CONFIG_DIR` | Override where repowise looks for its config directory |+| `REPOWISE_GITHUB_WEBHOOK_SECRET` | Secret for verifying GitHub webhook signatures |+| `REPOWISE_GITLAB_WEBHOOK_TOKEN` | Token for verifying GitLab webhook requests |++### Telemetry++Anonymous usage telemetry is **enabled by default** (opt-out).++| Variable | Description |+|----------|-------------|+| `DO_NOT_TRACK` | Any truthy value disables telemetry (respects the cross-tool convention) |+| `REPOWISE_TELEMETRY_DISABLED` | Disables telemetry, repowise-specific |+| `REPOWISE_TELEMETRY_DEBUG` | Prints the telemetry payload to stderr instead of sending it |++### Misc++| Variable | Description |+|----------|-------------|+| `REPOWISE_GIT_WINDOW_ANCHOR` | Set to `head` to anchor git "now" to the latest commit instead of wall-clock time |+| `REPOWISE_SKIP_EDITOR_SETUP` | Skip the interactive editor/MCP setup step |+| `REPOWISE_CHANGELOG` | Override the changelog source used by the "what's new" check |---@@ -295,15 +452,18 @@ On top of that, add extra patterns via `--exclude` / `-x`:repowise init -x vendor/ -x "*.generated.ts" -x proto/ -x "**/*.pb.go"```-Patterns are saved to `config.yaml` and applied on subsequent `update` runs. You-can also create a `.repowiseIgnore` file (same gitignore syntax) at the repo root-or in any subdirectory for more granular control without touching `.gitignore`.+Patterns are saved to `config.yaml` (`exclude_patterns`) and applied on+subsequent `update` runs. You can also create a `.repowiseIgnore` file (same+gitignore syntax) at the repo root or in any subdirectory for more granular+control without touching `.gitignore`.Built-in exclusions (always applied): `.git/`, `.repowise/`, `node_modules/`,`__pycache__/`, `*.pyc`, `.venv/`, binary files, lockfiles, and minified assets.-Use `--skip-tests` to exclude test files and `--skip-infra` to exclude-Dockerfiles, Makefiles, and shell scripts.+`--skip-tests` excludes test files and `--skip-infra` excludes Dockerfiles,+Makefiles, and shell scripts. Both are CLI-flag-only for the run they're+passed on; they aren't written to `config.yaml`, so pass them again on+subsequent `init`/`update` calls if you want the same exclusions.---@@ -315,7 +475,9 @@ Git submodule directories are excluded by default. To include them:repowise init --include-submodules```-repowise reads `.gitmodules` to detect submodule paths.+repowise reads `.gitmodules` to detect submodule paths. This flag isn't+written to `config.yaml`; for a workspace, the choice is recorded in+`state.json` instead.---@@ -328,7 +490,8 @@ export REPOWISE_DB_URL="postgresql+asyncpg://user:pass@localhost:5432/repowise"repowise init```-The schema is managed with Alembic migrations.+`REPOWISE_DATABASE_URL` is a legacy alias for `REPOWISE_DB_URL` and is still+honored. The schema is managed with Alembic migrations.---@@ -359,11 +522,11 @@ conformance:rules:- source: frontend # matcher: a glob over node id / repo / nametarget: db # matcher- allow: false # optional, default false (deny). true = exception- description: "..." # optional, shown in reports+ allow: false # optional, default false (deny). true = exception+ description: "..." # optional, shown in reports- source: "tag:ui" # matcher: tag:<name> (repos carrying that tag)target: "tag:data"- - source: "*" # matcher: * (any service)+ - source: "*" # matcher: * (any service)target: legacy-payments```@@ -375,3 +538,12 @@ conformance:| `description` | string | `""` | Human-readable rationale, surfaced in reports |Rules are evaluated only against structural edges (HTTP, gRPC, event, package, db); behavioral co-change is never treated as a dependency.++---++## Deprecated / legacy aliases++| Old name | Current name | Notes |+|----------|--------------|-------|+| `max_pages_pct` | `coverage_pct` | Internal alias, still read for backward compatibility |+| `REPOWISE_DATABASE_URL` | `REPOWISE_DB_URL` | Still honored |diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.mdindex e4f29e690..dd70c968f 100644--- a/docs/LANGUAGE_SUPPORT.md+++ b/docs/LANGUAGE_SUPPORT.md@@ -1,709 +1,212 @@# Language Support-repowise analyses codebases written in many languages. Each language goes-through a multi-stage pipeline: file traversal, AST parsing, import-resolution, call graph construction, and heritage (inheritance) extraction.-Not every language has reached full coverage yet --- this page documents-exactly what works today, what is coming next, and how to add a new language.+repowise parses **15 languages to a full AST**, resolves imports and call+graphs across them, and scores **9 at the Full tier** with code-health markers.+Everything else in your repo is still tracked through git history and appears in+the wiki. This page is the "what works for my language today" reference.++> **How to add a language, and how the pipeline works internally:** see+> [architecture/language-support.md](architecture/language-support.md). Adding+> a language needs one `.scm` query file and one config entry, with no changes+> to the parser core.----## Support Tiers--Every language falls into one of five tiers. The tier determines which-pipeline stages produce meaningful output.--| Stage | Full | Partial | Scaffolded | Traversal | Config / Data |-|-------|:----:|:-------:|:----------:|:---------:|:-------------:|-| File discovery & git history | Y | Y | Y | Y | Y |-| AST symbol extraction | Y | Y | -- | -- | -- |-| Import resolution | Y | Y | -- | -- | -- |-| Call graph edges | Y | partial | -- | -- | -- |-| Heritage (extends/implements) | Y | partial | -- | -- | -- |-| Named bindings | Y | -- | -- | -- | -- |-| Code-health markers | Y¹ | -- | -- | -- | -- |-| Dead code detection | Y | Y | Y | Y | -- |-| Semantic search & wiki pages | Y | Y | Y | Y | Y |--¹ **Code-health markers** require a per-language complexity-walker map-(`analysis/health/complexity/languages.py`), independent of `.scm` parsing.-A language is only listed **Full** once it clears the-[code-health checklist](#code-health-marker-coverage) below, except-**Go**, whose class-level metrics (LCOM4 / god-class) are not computable-because Go methods attach to a type via an external receiver rather than-nesting in a class body; Go gets the function- and assertion-level-markers but is footnoted on the class-level ones.+## Tiers at a glance++Every language falls into one tier. The tier determines which pipeline stages+produce meaningful output.++| Tier | Languages | What works |+|------|-----------|------------|+| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage, docstrings, framework-aware edges, dynamic-hint extractors, and **code-health markers** |+| **Good** | C · Ruby · Swift · Scala · PHP · Dart | Everything above except code-health markers (C, Ruby, Swift, Scala, PHP; Dart *does* get health markers). Dedicated workspace resolvers and framework edges per language |+| **SQL / dbt** | `.sql` via sqlglot | Tables / views / functions / procedures as symbols with wiki pages; dbt projects get real `ref()` / `source()` lineage |+| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown · Shell | In the file tree and wiki; special handlers extract endpoints / targets where applicable |+| **Lightweight** | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# | Regex-tier file-level import graph (no symbols/calls). Honest file-to-file dependencies, no symbol-level claims |+| **Partial** | Luau / Roblox | AST symbols + `require()` resolution (Rojo / `.luaurc` aware); no health markers yet |+| **Structural** | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history only (blame, hotspots, co-change). No AST parsing |++**Pipeline stage coverage:**++| Stage | Full | Good | Lightweight | Structural | Config / Data |+|-------|:----:|:----:|:-----------:|:----------:|:-------------:|+| File discovery & git history | ✅ | ✅ | ✅ | ✅ | ✅ |+| AST symbol extraction | ✅ | ✅ | - | - | - |+| Import resolution | ✅ | ✅¹ | regex | - | - |+| Call graph edges | ✅ | ✅ | - | - | - |+| Heritage (extends/implements) | ✅ | ✅ | - | - | - |+| Named bindings | ✅ | ✅ | - | - | - |+| Code-health markers | ✅² | Dart only | - | - | - |+| Dead code detection | ✅ | ✅ | ✅ | ✅ | - |+| Semantic search & wiki pages | ✅ | ✅ | ✅ | ✅ | ✅ |++¹ Scala's import resolution is partial (build-file fallback via SBT/Mill); the+other Good languages resolve imports fully.+² See [code-health coverage](#code-health-coverage), a language is only "Full"+once it clears the health checklist.----## Language Reference--### Full--Languages with complete pipeline coverage: AST parsing, import resolution,-call resolution, named bindings, heritage extraction, and docstrings.--| Language | Extensions | Entry Points | Import Style |-|----------|-----------|-------------|-------------|-| **Python** | `.py` `.pyi` | `main.py` `app.py` `__main__.py` `manage.py` `wsgi.py` `asgi.py` | `import x` / `from x import y` |-| **TypeScript** | `.ts` `.tsx` | `index.ts` `main.ts` `app.ts` `server.ts` | `import { x } from 'y'` / `export { x } from 'y'` & `export * from 'y'` re-export barrels / `require()` with tsconfig path aliases, npm/yarn/pnpm `workspaces`, and optional `.vue`/`.svelte`/`.astro` SFC probing |-| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `index.js` `main.js` `app.js` `server.js` | `import` / `require()` incl. CommonJS re-export shapes (`module.exports = require('./x')`, `exports.foo = require('./y')`, `Object.assign(module.exports, require('./z'), …)`, flagged as re-export hubs like ESM barrels) and member picks (`var x = require('./m').member`) |-| **Java** | `.java` | `Main.java` `Application.java` | `import pkg.Class` / `import pkg.*` / `import static pkg.Class.*` with Maven `pom.xml` reactor + Gradle `settings.gradle(.kts)` source-sets + `gradle/libs.versions.toml` discovery, JPMS `module-info.java` / `package-info.java` recognition, fan-out to every file in the imported package (siblings share importers), same-package implicit identifier resolution; JDK namespaces (`java.` / `javax.` / `jdk.`) are filtered with no node, `jakarta.` classifies as an external dependency |-| **Kotlin** | `.kt` `.kts` | `Main.kt` `Application.kt` | `import com.example.Foo` / `import com.example.*` sharing the JVM workspace index with Java (cross-language resolution, `.kt` under `src/main/java` recognised); `kotlin.` stdlib filtered with no node, `kotlinx.` classifies as an external dependency; same-package implicit identifier resolution |-| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with multi-module `go.mod` discovery (longest-prefix match); a package import fans out to **all** `.go` files in the package directory |-| **Rust** | `.rs` | `main.rs` `lib.rs` | `use crate::` / `use super::` / `use self::` with `Cargo.toml` |-| **C++** | `.cpp` `.cc` `.cxx` `.h` `.hpp` `.hxx` | `main.cpp` `main.cc` `WinMain` `wWinMain` `LLVMFuzzerTestOneInput` `DllMain` | `#include` with `compile_commands.json` resolution + CMake / Bazel workspace public-header maps + per-target include-dir search + sibling-TU fan-out (header-only targets fan out across their headers) + same-stem same-dir header ↔ implementation pairing edges |-| **C#** | `.cs` | `Program.cs` `Startup.cs` | `using Acme.Domain` / `global using` / `using static` / `using Alias = X.Y.Z` with `.csproj` / `.sln` / `Directory.Build.props` resolution; `partial` class co-fragments linked bidirectionally; nested types resolve one level (`Outer.Inner`) |--All nine languages support:-- Tree-sitter AST parsing with dedicated `.scm` query files-- Three-tier call resolution (same-file, cross-file, global stem match)-- Named binding extraction (mapping imported names to source symbols)-- Heritage extraction (class/interface/trait/record inheritance chains)-- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)-- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; TYPO3 convention files (`ext_localconf.php`, `Configuration/TCA/*`, `JavaScriptModules.php` registrations) for PHP; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router + stdlib `net/http` (`http.HandleFunc` / `mux.Handle`) + gRPC `RegisterXxxServer` -> handler/impl files for Go; Axum/Actix `.route` -> handler files for Rust)-- Per-language dynamic-hint extractors (Django/Pytest/Node/`importlib` string-import registries for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`reflect.New`/`reflect.ValueOf`/`plugin.Open`/`plugin.Lookup`; Alpine.js `Alpine.data`/`store`/`magic`/`directive` registrations -> handler files for JS)-- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace -> file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection, host-builder extension method resolution (`app.MapCatalogApi()` / `services.AddCatalogServices()` on any C# repo, not just ASP.NET), `nameof(Type)` references resolved as dynamic uses, local `var x = new T()` property reads bound to the defining file, and CommunityToolkit MVVM source-generator synthesis (`[ObservableProperty]` fields -> PascalCase property, `[RelayCommand]` methods -> `<Name>Command`)-- For Go only: a package-granular workspace index (`GoPackageIndex`) built as a warmup phase: a package import resolves to every file in the package directory, and package-qualified calls (`pkg.Func`) / same-package bare calls resolve across all of a package's files; type-reference resolution emits `type_use` edges for field / parameter / return / composite-literal types (unwrapping `*T` / `[]T` / `map[K]V` / `pkg.T` / generics); package-aware dead-code reachability (a file is reachable when its package is imported or is a `package main` entry); structural interface satisfaction: concrete types are matched to the interfaces their method set satisfies (embedded interfaces expanded) and emit `method_implements` edges so interfaces reached only through implementors are not flagged dead; and Go never-flag conventions (`*_test.go`, `cmd/**/main.go`, `doc.go`, `magefile.go`, generated `*.pb.go` / `*_string.go` / `zz_generated*` / `bindata.go`) plus `init` / `TestMain` / `Test*` / `Benchmark*` / `Example*` / `Fuzz*` entry handling-- For C/C++ only: a unified `CppWorkspaceIndex` warmup parses CMake reactors (`add_subdirectory`, `add_executable` / `add_library`, `target_sources`, `target_include_directories`, `target_compile_definitions`, `target_link_libraries`, `option`/`if(...)` conditional sources, CMake File API `build/.cmake/api/v1/reply/` JSON), Bazel `BUILD` files (`cc_binary` / `cc_library` / `cc_test` / `cc_proto_library` / `cc_grpc_library` / `cc_fuzz_test`), and `compile_commands.json`; the index drives a six-step include resolver (compile_commands -> workspace public-header map -> per-target include-dirs -> importer-relative -> stdlib filter -> stem fallback) and fans `#include` edges out to every sibling TU in the same target so internal headers are reachable without a direct importer; project-specific export macros (`LEVELDB_EXPORT` / `SEASTAR_API` / `*_EXPORT` / `*_API` / `*_PUBLIC`) are discovered from `target_compile_definitions` and `#define X __declspec(dllexport)` patterns and re-applied as visibility markers during the warmup, alongside the literal `__declspec(dllexport)` / `__attribute__((visibility("default")))` / `EMSCRIPTEN_KEEPALIVE` / `WASM_EXPORT` / `export_name` / `((used))` markers (so JS↔WASM exports and project-macro-exported public APIs are not flagged dead); type-reference resolution emits `type_use` edges for parameter / field / return / template-argument types (unwrapping `std::vector` / `std::optional` / `std::shared_ptr` / friends and stripping pointer / reference / array tails) and consults the workspace's same-target sibling set for unqualified resolution; static-initialiser registration macros (`PYBIND11_MODULE`, `BOOST_PYTHON_MODULE`, `REGISTER_OP`, `REGISTER_KERNEL_BUILDER`, `BOOST_CLASS_EXPORT`, `PLUGINLIB_EXPORT_CLASS`, `RCLCPP_COMPONENTS_REGISTER_NODE`, `Q_OBJECT` / `Q_GADGET` / `QML_ELEMENT`, gflags `DEFINE_*`, `ABSL_FLAG`, `__attribute__((constructor/used))`, `[[gnu::retain/used]]`, `JNI_OnLoad`, `NAPI_MODULE`) synthesize the symbols they emit at compile time and stamp their TU as an entry point so the file is not flagged unreachable; framework edges cover the C++ test, benchmark, and fuzzing ecosystem: **GoogleTest** (`TEST` / `TEST_F` / `TEST_P` / `TYPED_TEST` with `TEST_F(FixtureClass, …)` emitting a `type_use` edge to the fixture's defining header), **Catch2** (`TEST_CASE` / `TEST_CASE_METHOD` / `SCENARIO`), **Boost.Test** (`BOOST_AUTO_TEST_CASE` / `BOOST_FIXTURE_TEST_CASE(case, Fixture)` with fixture rescue), **doctest** (`DOCTEST_TEST_CASE`), **Google Benchmark** (`BENCHMARK` / `BENCHMARK_F` / `BENCHMARK_MAIN`), **libFuzzer** (`LLVMFuzzerTestOneInput` / `LLVMFuzzerInitialize`); C++ dynamic-hint extractor (function-pointer assignments, designated-initializer field tables, `dlopen` / `dlsym` / `LoadLibrary` / `GetProcAddress`, Qt old-style `connect(SIGNAL(sig()), SLOT(slot()))` and new-style `connect(&Sender::sig, &Recv::slot)`); C++ contract methods (constructor / destructor / operator overloads, conversion operators (`operator bool`, `operator T`), STL customisation points (`begin` / `end` / `cbegin` / `cend` / `rbegin` / `rend` / `size` / `empty` / `data` / `swap` / `hash_value` / `to_string`), coroutine machinery (`await_ready` / `await_suspend` / `await_resume` / `promise_type` / `initial_suspend` / `final_suspend` / `return_void` / `return_value` / `yield_value` / `unhandled_exception`), `std::format` / `std::error_code` customisation); directory-granular reachability with **header-reached-by-symbol-reference rescue**, `int main` / `WinMain` / `wWinMain` / `wmain` / `LLVMFuzzerTestOneInput` / `LLVMFuzzerInitialize` / `DllMain` binary-entry recognition, sibling-rescue (internal header reached via its `.cc` neighbour), same-directory main-carrier rescue (helper files alongside `main.cc` are not dead), and conditional-compile alternative pairing (`env_posix.cc` ↔ `env_windows.cc`, `crypto_openssl.cc` ↔ `crypto_gnutls.cc`); never-flag conventions for `apps/**`, `demos/**`, `examples/**`, `samples/**`, `benchmarks/**`, `bench/**`, `tools/**`, `tests/{perf,fuzz,unit,manual,integration}/**`, `*_test.{cc,cpp}` / `*_unittest.*` / `*_perf.*` / `*_benchmark.*` / `*_fuzz.*` suffix globs, skeleton convention headers (`port_example.h`, `*_example.{h,hpp,cc}`), build directory roots (`build/**`, `cmake-build-*/**`, `_deps/**`, `out/{build,Debug,Release}/**`), generated source patterns (`moc_*.{cpp,cc}`, `ui_*.h`, `qrc_*.{cpp,cc}`, `*.moc`, `*.pb.{cc,h}`, `*.pb-c.{c,h}`, `*.grpc.pb.{cc,h}`, `*.capnp.{c++,h}`, `*.flatbuffers.h`, `*_generated.h`, `*.tab.{c,h}`, `*.yy.c`, `*_lex.cc`, `*_wrap.{cxx,cpp}`, `*.cython.cpp`), vendor roots (`external/**`, `extern/**`, `contrib/**`, `submodules/**`, `vendor/**`, `third_party/**`, `deps/**`), precompiled-header conventions (`pch.{h,cc,cpp}`, `stdafx.*`, `PrecompiledHeader.{cc,cpp}`), and Windows COM / ATL DLL entry points (`DllMain`, `DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer`, `DllUnregisterServer`, `DllGetActivationFactory`); a per-symbol-use dead-code check rescues headers whose declared types are referenced as parameter / field / return / template-argument / `extends` / `implements` even with no `#include` chain-- For JavaScript only: esbuild/rollup bundle outputs (`*.bundle.js`), minified artifacts (`*.min.js`), LiveReload generated browser-global scripts (`livereload/gen/*`, `livereload.js`) and WASM JS glue (`*wasm_exec.js`) are never flagged as dead (build products / browser-loaded, never module-imported)-- For TypeScript / JavaScript only: a workspace-granular index (`TsWorkspaceIndex`) built as a warmup phase that surfaces every file reachable through a `package.json` `exports` map (including `"./locales/*"`-style wildcards) as an entry point so downstream npm consumers don't read as unreachable; type-reference resolution emits `type_use` edges for parameter / field / return / generic-constraint / type-alias-RHS / heritage clauses (unwrapping `Promise<T>`, `T[]`, `Pick<T,K>`, union/intersection, conditional/mapped types) so interfaces consumed only as types are not flagged dead; same-file rescue exempts symbols whose only consumer is another declaration in the same module; convention never-flag globs for `*.test.*` / `*.spec.*` / `*.stories.*` / `*.bench.*` / `__tests__/**` / `__mocks__/**` / Next.js app-router files (`page.tsx`, `layout.tsx`, `route.ts`, `middleware.ts`, `instrumentation.ts`, route segment configs) / SvelteKit `+page` / `+layout` / `+server` / Remix `entry.client` / `entry.server` / `next-env.d.ts` / `*.gen.ts` / `generated/**`; experimental sub-package rescue marks every source file in directories named `bench` / `benchmarks` / `treeshake` / `examples` / `demos` / `samples` / `playground` / `scratch` / `scripts` as a live entry (these dirs invoke their files via runtime CLI arguments no static scan can follow); npm-script entry detection parses every `package.json` `scripts.*` command for paths (`tsx X.ts` / `bun run X.mts` / `rollup -c X.js`), quoted glob arguments (prettier / eslint scopes), and bare directory tokens; MDX `import` scan + `vitest.config` `include` glob scan as belt-and-suspenders for entry surfaces the static parser can't see; framework edges for Next.js App Router (`app/**/{page,layout,route,middleware,…}`), Hono / Fastify / Koa / Elysia router DSLs (`.get('/x', handler)`), Remix / SvelteKit / Astro filesystem-convention routes, and tRPC procedure registries (`.query(handler)` / `.mutation(handler)`); JSX-namespace types declared inside a `namespace JSX` file are exempt from `unused_export` (consumed by tsc via `jsxImportSource`, never imported as values)-- For XAML only: `<ResourceDictionary Source="..."/>` and `MergedDictionaries` entries resolve across `pack://application:,,,/`, `ms-appx:///`, repo-rooted and relative URIs, emitting xaml-to-xaml `dynamic_uses` edges-- For JVM (Java + Kotlin together) only: a unified `JvmWorkspaceIndex` warmup parsing Maven `pom.xml` reactors and Gradle `settings.gradle(.kts)` + source-sets + `gradle/libs.versions.toml` version catalogs; one walk groups every `.java` and `.kt` file by package directory so `import com.foo.Bar` fans out to every defining file in the package (siblings share importers), `import com.foo.*` / `import static com.foo.Bar.*` expand to all matching files, same-package implicit identifier access is honoured, and Kotlin↔Java cross-language resolution links callers across both source-roots (including `.kt` files hosted under `src/main/java`); type-reference resolution emits `type_use` edges for parameter / field / return / generic / `new T()` types (unwrapping arrays, generics, nullables), plus Kotlin `companion object` / `object` singleton / method-reference (`Foo::bar`) / `sealed … permits` resolution; source-generator-equivalent synthesis emits the symbols Lombok (`@Data` / `@Value` / `@Builder` / `@RequiredArgsConstructor` / `@Slf4j` / `@UtilityClass` / friends), Java `record`, Kotlin `data class` / `enum class` / `object`, and MapStruct / AutoValue / Immutables would produce at compile time, so a Lombok-only Spring service no longer reads its injected fields as unused; framework edges cover Spring (stereotypes with meta-annotation resolution; `@RequestMapping` family routing; Spring Data `JpaRepository` / `Crud` / `Mongo` / `R2dbc` / `Elasticsearch` / `Neo4j` / `Couchbase` / `Cassandra` interfaces and their derived-query methods as entry points; `@Bean` factories; single-constructor + `@Autowired` / `@Inject` / `@Resource` DI; Lombok-RAC/AAC constructor inference), Jakarta (JAX-RS `@Path`, CDI scopes, Servlet 3+ `@WebServlet`/`@WebFilter`/`@WebListener`, JPA `@Entity` + `@OneToMany`/`@ManyToOne`/`@ManyToMany`/`@OneToOne` association edges; both `javax.*` and `jakarta.*`), Quarkus (entry stereotypes + SmallRye `@Incoming("topic")` ↔ `@Outgoing("topic")` cross-linking), Micronaut (DI / routing, gated on Micronaut imports to disambiguate Spring's collisions), and Android (`AndroidManifest.xml` `android:name` references emit edges to the named class); JVM dynamic hints capture `Class.forName`, Mockito / mockk, MapStruct `Mappers.getMapper`, `SpringApplication.run` and Kotlin `runApplication<>`, Jackson / Gson `readValue` / `fromJson` / `treeToValue`; package-aware dead-code reachability rescues sibling-rescued packages, stereotype-annotated classes, `main(String[])` carriers, and FQNs listed in `META-INF/services/*` / `META-INF/spring.factories` (Boot 2) / `META-INF/spring/...AutoConfiguration.imports` (Boot 3) / JPMS `provides … with …`, all resolved during the workspace warmup; JVM never-flag patterns cover `module-info.java`, `package-info.java`, every conventional test source-set (`src/test/**`, `src/integrationTest/**`, `src/intTest/**`, `src/it/**`, `src/jmh/**`, generic `src/*Test/**`), generated source roots (`build/generated/**`, KAPT/KSP, `target/generated-sources/**`, GraalVM `aotSources`), generated suffix conventions (`Dagger*`, `AutoValue_*`, JPA `*_.java` metamodel, `*Grpc.java`, protoc `*OuterClass.java`), JUnit / TestNG / Spock / ArchUnit test-naming + annotation-marked entry points (`@Test` / `@PostConstruct` / `@EventListener` / `@Scheduled` / `@JmsListener` / `@KafkaListener` / `@RabbitListener` / `@SqsListener` / `@Incoming` / `@Outgoing` / `@Mojo` / `@Bean` / ...), and JVM contract methods (`equals` / `hashCode` / `toString` / `compareTo` / `clone` / serialization `readObject` / `writeObject` / `serialVersionUID` / Lombok `canEqual` / Kotlin `componentN` / `copy` / enum `values` / `valueOf`)--#### Code-health marker coverage--The code-health layer scores every source file from deterministic-markers (complexity, cohesion, test-quality, ...). These run off a-per-language complexity-walker map-(`analysis/health/complexity/languages.py`) that is **independent** of the-`.scm` ingestion queries: a language can parse perfectly for the graph yet-still need this map before health markers fire. To keep "Full" meaning-"health works", a language must clear this checklist (each item has a green-fixture under `tests/fixtures/lang_samples/<lang>/` + a walker test):--1. **Control flow**: `if` / loop / `switch`/`match`/`when` / `try`-`catch`- nodes mapped -> McCabe CCN, nesting depth, cognitive complexity.-2. **Boolean operators**: `&&` / `||` (or their text form) counted toward- CCN and `complex_conditional`.-3. **Class metrics**: `class_kinds` set so `method_count` / `total_nloc` /- `max_method_ccn` aggregate (feeds `god_class`). *(N/A for Go: no- class-grouping node.)*-4. **LCOM4 cohesion**: `self_identifiers` + `member_access_kinds` set so- explicit-receiver member access is detected (feeds `low_cohesion`).- Receiver-less idioms degrade to "no signal", never a false positive.- *(N/A for Go.)*-5. **Assertion blocks**: `assert_kinds` / `assert_call_kinds` set so runs- of consecutive assertions are detected on test files (feeds- `large_assertion_block` / `duplicated_assertion_block`).--| Language | Control flow | Class metrics | LCOM4 | Assertions |-|----------|:---:|:---:|:---:|:---:|-| Python | Y | Y | Y | Y |-| TypeScript / JavaScript | Y | Y | Y | Y |-| Java | Y | Y | Y | Y |-| Kotlin | Y | Y | Y | Y |-| Go | Y | n/a | n/a | Y |-| Rust | Y | Y | Y | Y |-| C++ | Y | Y | Y | Y |-| C# | Y | Y | Y | Y |-| Dart | Y | Y | n/a | Y (`assert` statements only; `expect()` calls have no call-node type to key on) |--### Good+## Full tier++Complete pipeline coverage: AST parsing, import resolution, call resolution,+named bindings, heritage, docstrings, framework-aware edges, dynamic-hint+extractors, and code-health markers.++| Language | Extensions | Import style |+|----------|-----------|--------------|+| **Python** | `.py` `.pyi` | `import x` / `from x import y`; source-root-aware module index (src/, monorepo `packages/*/src`, PEP 420), `__init__.py` re-export barrels |+| **TypeScript** | `.ts` `.tsx` | ESM / `require()` with tsconfig path aliases, npm/yarn/pnpm workspaces, `export * from` barrels, optional `.vue`/`.svelte`/`.astro` probing |+| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `import` / `require()` including CommonJS re-export shapes and member picks |+| **Java** | `.java` | `import pkg.Class` / `.*` / `import static` with Maven + Gradle reactor discovery, JPMS recognition, package fan-out |+| **Kotlin** | `.kt` `.kts` | Shares the JVM workspace index with Java (cross-language resolution); `.kt` under `src/main/java` recognised |+| **Go** | `.go` | `import "path"` with multi-module `go.mod` discovery; a package import fans out to every file in the package |+| **Rust** | `.rs` | `use crate::` / `super::` / `self::` with `Cargo.toml` |+| **C++** | `.cpp` `.cc` `.cxx` `.h` `.hpp` `.hxx` | `#include` via `compile_commands.json` + CMake / Bazel workspace header maps, header↔implementation pairing |+| **C#** | `.cs` | `using` / `global using` / `using static` / aliases with `.csproj` / `.sln` resolution; MSBuild project graph; `partial` class linking |++All nine also support three-tier call resolution (same-file, cross-file, global+stem match) and docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc,+Doxygen, XML doc).++**Framework-aware edges** connect routes to handlers, DI registrations to+implementations, and ORM entities to relationships:++| Language | Frameworks |+|----------|-----------|+| Python | Django, FastAPI, Flask, pytest fixtures |+| Java / Kotlin | Spring (stereotypes, `@RequestMapping`, Spring Data, `@Bean`), Jakarta / JPA, Quarkus, Micronaut, Android manifest |+| C# | ASP.NET (attribute + minimal API), EF Core, gRPC-dotnet, host-builder extension methods, CommunityToolkit MVVM |+| Go | net/http, gin, echo, chi, gRPC server registration |+| Rust | Axum, Actix route → handler |+| JS / TS | Next.js App Router, Hono / Fastify / Koa / Elysia, Remix / SvelteKit / Astro, tRPC, Express / NestJS |+| C++ | GoogleTest, Catch2, Boost.Test, doctest, Google Benchmark, libFuzzer |++The dead-code analyzer understands each ecosystem's entry points, generated-file+conventions, and never-flag globs so build products and framework-invoked code+aren't reported as unreachable. (Full per-language detail:+[architecture/language-support.md](architecture/language-support.md).)++---++## Good tierAST parsing, symbol extraction, import resolution, call resolution, named-bindings, heritage extraction (including Ruby mixins, Rust derive, Swift-extension conformance, PHP trait use), and docstrings. Dedicated import-resolvers for each language.--| Language | Extensions | Entry Points | Import Style |-|----------|-----------|-------------|-------------|-| **C** | `.c` | `main.c` | `#include` with `compile_commands.json` (shares C++ grammar) |-| **Ruby** | `.rb` | `main.rb` `app.rb` `config.ru` | `require 'mod'` / `require_relative './mod'` with `$LOAD_PATH` convention probing (`require 'sinatra/base'` -> `lib/sinatra/base.rb`, including every sub-gem's `lib/` in monorepos), Ruby-stdlib requires filtered with no node, Gemfile/gemspec dependencies labelled as gem externals, rspec directory-mirror edges (`spec/lib/x_spec.rb` -> `lib/x.rb`), plus Rails / Zeitwerk autoloading (gated on `config/application.rb`) |-| **Swift** | `.swift` | `main.swift` `App.swift` | `import Foundation` with SPM `Package.swift` `targets:` -> directory mapping; intra-module type references link same-target files (Swift has no intra-module imports by design); `@main` / `@UIApplicationMain` / `@NSApplicationMain` flag entry points; `@_exported import` marks re-exports |-| **Scala** | `.scala` | `Main.scala` `App.scala` | `import pkg.Foo`, brace imports `{A, B => C}` (expanded per selected name, hidden imports skipped), wildcards (`pkg._` / Scala 3 `pkg.*`), and package imports, resolved through the shared JVM workspace index (chained package clauses, Scala ↔ Java cross-language, same-package implicit identifiers) with SBT `build.sbt` / Mill `build.sc` multi-project parsing as fallback; `scala.` and JDK namespaces filtered |-| **PHP** | `.php` | `index.php` `public/index.php` | `use Foo\Bar\Baz` with composer.json `autoload.psr-4` longest-prefix resolution |-| **Dart** | `.dart` | `main.dart` | `import` / `export` (re-export) / `part` / `part of` URIs; `package:` URIs via every `pubspec.yaml` `name:` (monorepos included); `dart:` SDK URIs filtered; `as` prefixes and `show` combinators become named bindings; heritage covers `extends` / `with` (mixin) / `implements` / mixin `on` constraints; Flutter route tables (`MaterialApp(routes:)`, `GoRoute` / `MaterialPageRoute` builders) and `runApp()` emit framework edges; the regex tier below stays as the no-grammar fallback |--### Config / Data--Non-code files included in the file tree and wiki. Special handlers extract-endpoints or targets where applicable.--| Language | Extensions / Filenames | Special Handler |-|----------|----------------------|----------------|-| **OpenAPI** | YAML/JSON with `openapi` or `swagger` key | Extracts API paths and schemas |-| **Dockerfile** | `Dockerfile` | Extracts stages and exposed ports |-| **Makefile** | `Makefile` `GNUmakefile` | Extracts targets |-| **Protobuf** | `.proto` | -- |-| **GraphQL** | `.graphql` `.gql` | -- |-| **Terraform** | `.tf` `.hcl` | -- |-| **YAML** | `.yaml` `.yml` | -- |-| **JSON** | `.json` | -- |-| **TOML** | `.toml` | -- |-| **Markdown** | `.md` `.mdx` `.markdown` `.mdown` | -- |-| **AsciiDoc** | `.adoc` `.asciidoc` | -- |-| **SQL** | `.sql` | Graduated: DDL symbols + dbt lineage, see [SQL + dbt](#sql--dbt) |-| **Shell** | `.sh` `.bash` `.zsh` | -- |--### Partial (Luau, Roblox)--| Language | Extensions | Entry Points | Import Style |-|----------|-----------|-------------|-------------|-| **Luau** | `.luau` `.lua` | `init.luau` `init.lua` | `require(script.Parent.X)` / `require(script.X)` / `require(game.Service.Path)` / `require("rel/path")` |--AST parsing, symbol extraction (functions, Luau type aliases), and-`require(...)` call capture are wired. Import resolution handles string-literals, `script`/`script.Parent` relative instance paths (including the-`:WaitForChild("X")` / `:FindFirstChild("X")` idioms), absolute Roblox-instance paths (`game.<Service>...`, plus the `game:GetService("X")` idiom)-through Rojo's `default.project.json` tree mapping, and `@alias` requires-through `.luaurc` `aliases` maps (nearest declaration wins, child overrides-parent). Repos without a Rojo project file / `.luaurc` keep the conservative-external-node fallback (issue #52 is closed by both halves).--### Lightweight (regex-tier import graphs)--These languages have no AST parsing (no symbols, calls, or heritage) but-get a real file-level import graph from a regex tier: import statements-are extracted with per-language regexes and resolved against a declared-module-name index (declaration scan + path-convention inverse). The-knowledge graph runs in flow/sparse mode on the resulting density:-honest file-to-file dependencies, no symbol-level claims.--| Language | Extensions | Import Forms Resolved |-|----------|-----------|----------------------|-| **Elixir** | `.ex` `.exs` | `alias` / `import` / `use` / `require` (incl. `Foo.{Bar, Baz}` brace groups) → `defmodule` index + Mix `lib/` path convention (umbrella `apps/*/lib` included); Elixir/OTP stdlib filtered after local-miss |-| **Dart** | `.dart` | `import` / `export` (re-export) / `part` / `part of` URIs; `package:` URIs via every `pubspec.yaml` `name:` (monorepos included); `dart:` SDK URIs filtered; foreign packages → `external:pub:<name>` |-| **Clojure** | `.clj` `.cljc` `.cljs` | `(:require …)` / `(:use …)` vectors and bare specs (string/comment-safe) → `(ns …)` index + classpath convention (dashes ↔ underscores); `clojure.*`/`cljs.*` filtered |-| **Haskell** | `.hs` `.lhs` | `import [safe] [qualified] ["pkg"] Foo.Bar` → `module` declaration index + trailing-PascalCase path inverse (handles any hs-source-dirs without parsing `.cabal`); base-ish namespaces filtered after local-miss |-| **Lean 4** | `.lean` | `import Foo.Bar`, `import all Foo.Bar`, visibility imports (`public import Foo.Bar` / `private import Foo.Bar` / `meta import Foo.Bar`), and `open [scoped] Foo` → path-derived module index (`Mathlib/Data/Nat/Basic.lean` → `Mathlib.Data.Nat.Basic`); core/library roots filtered after local-miss |-| **Erlang** | `.erl` `.hrl` | `-include` / `-include_lib` / `-behaviour` + module-qualified calls (`mod:fun(`) → `-module()` index; qualified calls are strict local-hit-or-drop (never mint externals) |-| **F#** | `.fs` `.fsi` `.fsx` | `open` → file-level `namespace`/`module` index (unambiguous single-file declarations only), plus the fsproj `<Compile Include>` compile-order dependency spine (a real F# constraint: files may only reference earlier files) |--### SQL + dbt--SQL is parsed by a dedicated special handler (sqlglot, multi-dialect and-error-tolerant) rather than tree-sitter, plus the lightweight import tier-for dbt lineage. Four independent capabilities:--**DDL symbols (any `.sql` file).** `CREATE TABLE` / `VIEW` /-`MATERIALIZED VIEW` -> class-kind symbols with columns in the signature;-`CREATE FUNCTION` / `PROCEDURE` -> function-kind symbols. Tables get wiki-pages, search hits, and `get_symbol` lookups (`schema.sql::public.users`).-Indexes and triggers are deliberately not symbols. Dialect is sqlglot's-permissive default; set `sql_dialect` in `.repowise/config.yaml`-(`postgres`, `mysql`, `tsql`, `clickhouse`, ...) for dialect-specific-syntax like PL/pgSQL `$$` bodies. Any parse problem degrades the file to-plain passthrough: no symbols, never a crash, never a guess.--**dbt lineage (gated on `dbt_project.yml`).** `{{ ref('model') }}`,-`{{ ref('package', 'model') }}`, and `{{ source('schema', 'table') }}`-become real import edges: refs resolve against a per-project model-name-index built from `dbt_project.yml`'s `model-paths` / `seed-paths` /-`snapshot-paths` (defaults `models/` `seeds/` `snapshots/`; `.csv` seeds-are ref-able), sources become typed `external:source:<schema>.<table>`-nodes marking the warehouse boundary, and refs to uninstalled packages-become `external:dbt:<package>.<model>`. When two projects in a monorepo-declare the same model name, the importer's own project wins; two-arg-refs prefer the project whose declared `name` matches. Everything that-rides the import graph falls out free: model-level lineage, hotspots,-co-change, ownership, and Leiden communities of the DAG.--**App-to-database contracts (workspace mode).** The workspace contract-extractor pairs table *providers* (DDL `CREATE`/`ALTER` in `.sql` files,-Alembic `op.create_table`, and ORM entities: SQLAlchemy `__tablename__`,-SQLModel `table=True`, Django `db_table`, JPA `@Entity`/`@Table`, EF Core-`DbSet<T>`/`[Table]`, ActiveRecord, Eloquent `$table`) with table-*consumers* (SQL string literals in app code, parsed with sqlglot when the-literal parses, recovered by a verb-anchored regex when interpolation-breaks it). Matched pairs become `data` contracts rendered as `db` edges-on the Live System Map: "which services touch table X" across repos.-Table names are normalized in one place (quoting, `public`/`dbo`-prefixes, case), and an interpolated table target emits nothing rather-than a guess.--**Health markers (maintainability/performance pillars only).** Stored-routines get cyclomatic complexity counted from the decision keywords in-the body (`sql_high_complexity`; procedural bodies do not parse into an-AST, so nesting is deliberately not reported). Three statement smells-ride the sqlglot AST: `sql_select_star` (a bare `*` in a view or-routine), `sql_update_delete_without_where`, and `sql_cartesian_join`-(comma-join with no predicate). All four are uncalibrated by construction-and never move the defect headline; dbt/Jinja templates and garbled-parses emit nothing. See `docs/CODE_HEALTH.md`.---### Structural (git + file tree only)--These languages are tracked in git history (blame, hotspot analysis,-co-change detection) but have no AST parsing or import resolution. Files-appear in the wiki as traversal-level entries, and the knowledge graph-runs in **structural mode** for repos dominated by them: the tour-orients by directory structure, naming conventions, and git evidence:-it never claims an execution flow it cannot see.--Objective-C, R, Zig, Julia, Elm, OCaml, Crystal, Nim, D+bindings, and heritage (Ruby mixins, Rust derive, Swift extension conformance,+PHP trait use, Dart mixins). Dedicated workspace resolvers per language.++| Language | Extensions | Import style |+|----------|-----------|--------------|+| **C** | `.c` | `#include` via `compile_commands.json` (shares C++ grammar) |+| **Ruby** | `.rb` | `require` / `require_relative` with `$LOAD_PATH` probing, Gemfile externals, RSpec mirror edges, Rails / Zeitwerk autoloading |+| **Swift** | `.swift` | `import` with SPM `Package.swift` target → directory mapping; intra-module type references; `@main` entry points |+| **Scala** | `.scala` | `import pkg.Foo`, brace/wildcard/package imports via the shared JVM index; SBT / Mill build parsing as fallback (partial import resolution) |+| **PHP** | `.php` | `use Foo\Bar\Baz` with composer.json PSR-4 longest-prefix resolution; Laravel, TYPO3 edges |+| **Dart** | `.dart` | `import` / `export` / `part` URIs; `package:` via every `pubspec.yaml`; Flutter route tables and `runApp()` edges; **code-health markers** |----## How the Pipeline Processes a File--```-File discovered by FileTraverser- |- v-Extension/filename -> LanguageTag (via LanguageRegistry)- |- +-- Config/data language? -> empty ParsedFile (passthrough)- +-- Special format? -> special_handlers.py (OpenAPI/Dockerfile/Makefile/SQL)- +-- Has grammar? -> tree-sitter AST parsing- |- v- .scm query extracts:- @symbol.def / @symbol.name -> Symbol nodes- @import.statement / @import.module -> Import edges- @call.target / @call.receiver -> Call edges- |- v- Per-language extractors:- - Named bindings (import name -> source symbol)- - Heritage (extends/implements/traits)- - Docstrings (Python, JSDoc, GoDoc, Rustdoc, Javadoc)- - Visibility (public/private/protected)- |- v- GraphBuilder resolves imports:- Python: dotted module paths via a source-root-aware module index- (src/ + monorepo packages/*/src + PEP 420 namespace- packages), __init__.py re-export barrels, stem fallback- TS/JS: relative paths, tsconfig aliases, workspace exports,- `export ... from` re-export barrels, node_modules- Go: go.mod module path stripping- Rust: crate::/self::/super::, mod.rs probing- C/C++: compile_commands.json include directories- Lightweight tier (Elixir/Dart/Clojure/Haskell/Lean 4/Erlang/F#):- Dart: package:/dart:/relative URIs via the pubspec name map +- library-name index (dotted part-of)- regex-extracted imports vs a declared-module-name index- (dbt: ref()/source() vs a per-project model-name index)- Other: stem-map fallback (filename matching)- |- v- Graph analysis:- PageRank, community detection, dead code, execution flows-```+## SQL + dbt++SQL is parsed by a dedicated sqlglot handler (multi-dialect, error-tolerant)+rather than tree-sitter, plus the lightweight import tier for dbt lineage.++- **DDL symbols** (any `.sql` file), `CREATE TABLE` / `VIEW` /+ `MATERIALIZED VIEW` become class-kind symbols with columns in the signature;+ `CREATE FUNCTION` / `PROCEDURE` become function-kind symbols, with wiki pages+ and `get_symbol` lookups. Set `sql_dialect` in config for dialect-specific+ syntax (`postgres`, `mysql`, `tsql`, `clickhouse`, …). Any parse problem+ degrades the file to passthrough, never a crash, never a guess.+- **dbt lineage** (gated on `dbt_project.yml`), `{{ ref('model') }}` and+ `{{ source('schema', 'table') }}` become real import edges resolved against a+ per-project model-name index, so model-level lineage, hotspots, co-change,+ ownership, and communities all fall out free.+- **App-to-database contracts** (workspace mode), pairs table *providers* (DDL,+ Alembic, ORM entities) with table *consumers* (SQL string literals in app+ code) into `data` contracts on the Live System Map. See+ [WORKSPACES.md](WORKSPACES.md).+- **Health markers**, stored routines get cyclomatic complexity;+ `sql_select_star`, `sql_update_delete_without_where`, and `sql_cartesian_join`+ ride the sqlglot AST. All uncalibrated by construction and never move the+ defect headline. See [CODE_HEALTH.md](CODE_HEALTH.md).----## Adding a New Language--The pipeline is fully modular. Language identity data lives in the-centralised `LanguageRegistry`, per-language extraction logic lives in-`extractors/`, and per-language import resolution lives in `resolvers/`.-Adding a new language touches these places:--### Step 1: Add a `LanguageSpec` module--Language identity data lives in the `languages/specs/` package: **one module-per language**. Create-`packages/core/src/repowise/core/ingestion/languages/specs/mylang.py` exporting-a single `SPEC`:--```python-"""LanguageSpec for mylang."""--from ..spec import LanguageSpec--SPEC = LanguageSpec(- tag="mylang",- display_name="MyLang",- extensions=frozenset({".ml"}),- grammar_package="tree_sitter_mylang", # PyPI package name- scm_file="mylang.scm", # query file name- heritage_node_types=frozenset({"class_declaration"}),- entry_point_patterns=("main.ml",),- manifest_files=("mylang.toml",),- shebang_tokens=("mylang",),- builtin_calls=frozenset({"print", "len"}), # filter from call graph- builtin_parents=frozenset({"Object"}), # filter from heritage- color_hex="#AB47BC",-)-```--Then register it in `languages/specs/__init__.py` by importing the module and-slotting it into the `ALL_SPECS` tuple. **Order matters**: `LanguageRegistry`-builds its extension map first-spec-wins, so place more specific languages-ahead of ones that share an extension (e.g. TypeScript before JavaScript).-The `LanguageRegistry` in `registry.py` consumes `ALL_SPECS`; you never edit-the registry itself to add a language.--### Step 2: Add the `LanguageTag`--Add `"mylang"` to the `LanguageTag` Literal type in-`packages/core/src/repowise/core/ingestion/models.py`.--### Step 3: Write a tree-sitter query file--Create `packages/core/src/repowise/core/ingestion/queries/mylang.scm` using-tree-sitter S-expression syntax. Follow the capture-name conventions:--| Capture | Purpose | Required? |-|---------|---------|-----------|-| `@symbol.def` | Full definition node (line numbers, kind lookup) | Yes |-| `@symbol.name` | Name identifier | Yes |-| `@symbol.params` | Parameter list | No |-| `@symbol.modifiers` | Decorators / visibility modifiers | No |-| `@symbol.receiver` | Go-style method receiver | No |-| `@import.statement` | Full import node | Yes |-| `@import.module` | Module path being imported | Yes |-| `@call.target` | Function/method being called | No (enables call graph) |-| `@call.receiver` | Object the call is made on | No |-| `@call.arguments` | Call arguments | No |--Look at existing `.scm` files for examples --- `python.scm` and-`typescript.scm` are good starting points.--### Step 4: Add a `LanguageConfig` entry--Add a parser configuration to `LANGUAGE_CONFIGS` in-`packages/core/src/repowise/core/ingestion/language_configs.py` (re-exported-from `parser.py` for back-compat):--```python-"mylang": LanguageConfig(- symbol_node_types={- "function_definition": "function",- "class_definition": "class",- },- import_node_types=["import_statement"],- export_node_types=[],- visibility_fn=public_by_default, # from extractors.visibility- parent_extraction="nesting",- parent_class_types=frozenset({"class_definition"}),- entry_point_patterns=["main.ml"],-),-```--### Step 5: Add the tree-sitter grammar dependency--Add the grammar package to `pyproject.toml`:--```toml-[project]-dependencies = [- # ...- "tree-sitter-mylang>=0.23,<1",-]-```--### Step 6 (optional): Binding extractor--For full-tier support, add a `extract_mylang_bindings()` function in-`packages/core/src/repowise/core/ingestion/extractors/bindings.py` and-register it in the `extract_import_bindings()` dispatcher. Without this,-imports are still resolved but named-binding-level call resolution won't-work.--### Step 7 (optional): Heritage extractor--Add a `_extract_mylang_heritage()` function in-`packages/core/src/repowise/core/ingestion/extractors/heritage.py` and-register it in the `HERITAGE_EXTRACTORS` dict. Without this, inheritance-chains won't appear in the graph.--### Step 8 (optional): Import resolver--If the language has a non-trivial import system, create a resolver in-`packages/core/src/repowise/core/ingestion/resolvers/mylang.py` and-register it in the `_RESOLVERS` dict in `resolvers/__init__.py`. For simple-languages, the generic stem-map fallback (matching by filename) works out-of the box.--### Verify--```bash-# Run the parser tests-pytest tests/ -k "mylang or sample_repo" -x--# Index a real project-repowise init /path/to/mylang-project-```--No changes are needed to `traverser.py`, `dead_code.py`,-`page_generator.py`, `cost_estimator.py`, or any other consumer file ----they all derive their language sets from the registry automatically.--### Optional language-specific passes--Several pluggable hooks let a language opt into deeper resolution-without touching the shared pipeline files:--- `graph_warmups.py` --- register a one-time pre-import warmup (e.g.- building a project index) so its cost shows up as its own phase- instead of inflating `graph.imports`.-- `type_ref_resolution._STRATEGIES` --- register a strategy that- resolves parameter-type captures (`@param.type` in the language's- `.scm`) to file-level type-use edges. Drives DI-aware analysis.-- `languages/<lang>_member_reads.py` --- emit `reads` edges for- property / member access. Used today for C# `var x = new T()`- locals; the same shape applies to any statically-typed language.-- `extractors/synthetic_symbols.py` --- recognise source-generator- attributes and emit the symbols the generator would produce- at compile time. Used today for CommunityToolkit MVVM- (`[ObservableProperty]`, `[RelayCommand]`); the same shape fits- Java Lombok, Kotlin `@Parcelize`, etc.-- `extractors/visibility.py::refine_<lang>_visibility` --- node-aware- visibility refinement for languages where access is dictated by AST- context (C/C++ access specifiers, storage class, export attributes)- rather than modifier text alone.-- `graph_warmups.py` `is_never_flag` stamping --- read the language's- build manifest during warmup and set `is_never_flag=True` on file- nodes the manifest declares as a non-primary / secondary target.- The dead-code analyzer consults this attribute in `_should_never_flag`,- so each repo's own build files teach the analyzer what to ignore- without extending the hardcoded glob list. Used today by `_warmup_jvm`- to exempt every file under a Gradle non-`main` source set- (`testFixtures`, `integrationTest`, `javaPoet`, `jcstress`, `jmh`,- custom names); Caffeine's `javaPoet/` and `jcstress/` are picked up- automatically without us knowing the names exist. The same shape fits- Rust (`[[example]]` / `[[bench]]` / `[[bin]]` targets in `Cargo.toml`),- C# (projects with `<Sdk>Microsoft.NET.Sdk.Test</Sdk>` or- `Microsoft.NET.Test.Sdk` references), TS/JS (workspace `packages/*`- declared `"private": true`), and Go (`//go:build integration`-gated- files): any language that already builds a workspace index can opt- in by stamping the attribute during its warmup.-- `analysis/health/complexity/languages.py` --- the code-health- complexity walker keeps its own per-language node-type map- (`LanguageNodeMap`), independent of the ingestion `.scm` queries. Add a- map for a language to get McCabe complexity, nesting, cognitive- complexity, and the per-function markers; optionally set- `class_kinds` / `self_identifiers` / `member_access_kinds` to also get- class-level metrics (LCOM4 cohesion, god-class), and- `assert_kinds` / `assert_call_kinds` to get test-quality assertion-block- smells. All tiers are purely additive and degrade safely: an unmapped- language simply produces no health findings rather than wrong ones.- Control-flow and assertion maps ship for all nine full-tier languages- (Python, TypeScript, JavaScript, Go, Java, Kotlin, Rust, C++, C#);- class-level maps for all of those except Go (no class-grouping node).- See `complexity/README.md` for the extension recipe and the LCOM4- heuristic's limits.-- `analysis/health/perf/dialects/` --- the **performance** health signal- (`io_in_loop` / `string_concat_in_loop` / language-specific markers) is- driven by a per-language `PerfDialect` plugin, registered in- `PERF_DIALECTS` exactly like `resolvers/` and the workspace `http/`- dialects. A dialect owns callee extraction (the per-grammar seam: Python- `attribute`, Go `selector_expression`, Java `method_invocation`'s- `object`/`name`, C# `member_access_expression`), the execution-sink- lexicon (`sink_kind`), the constant-loop / string-concat / async- predicates, and its own **marker list** --- so Go contributes- `defer_in_loop`, Java/Go contribute `regex_compile_in_loop`, C#- contributes sync-over-async `blocking_sync_in_async`, and the Phase-7a loop- markers (`resource_construction_in_loop`, `lock_in_loop`,- `serial_await_in_loop`, `membership_test_against_list_in_loop`) are each- opt-in per dialect via the `loop_call_marker` / `loop_stmt_marker` hooks,- none hardcoded in the walker. Every method has a safe "no signal" default, so a language- without a dialect (or one that overrides only some facets) produces no- false perf findings. Adding a language's perf support is one module plus a- `call_kinds` line on its `LanguageNodeMap` and its- `external_systems/io_kind.py` ecosystem rows --- no walker edits.-- `analysis/health/dataflow/dialects/` --- the **dataflow** layer- (intra-procedural CFG + def/use + reaching definitions, powering the- **Extract Method** refactoring) is driven by a per-language `DefUseDialect`- plugin, registered in `DEFUSE_DIALECTS` exactly like `perf/dialects/`. A- dialect owns the read-vs-write classification of each statement (the- per-grammar seam: which node is an assignment / declaration / destructuring- target, which is a member or index target that binds no local, how a loop's- binder reads and writes) and the parameter binders (including a Go method- receiver). The CFG builder, the reaching-definitions fixpoint, and the- Extract Method slicer stay language-agnostic: the control-flow grammar they- branch on (`if_kinds` / `block_kinds` / `return_kinds` / `raise_kinds` /- `break_kinds` / `continue_kinds`, alongside the existing- `branch_kinds` / `loop_kinds` / `try_kinds`) lives on the `LanguageNodeMap`,- so the same builder serves Python's clause-style `elif` / `else` and the- C-family's `alternative`-field `else if` without a per-language branch. Every- facet has a safe "no signal" default, so a language without a dialect (or one- whose map omits the control-flow kinds) produces no def/use and therefore no- Extract Method suggestion --- never a wrong one. Adding a language is one- module plus the `assignment_kinds` / `local_decl_kinds` and control-flow- lines on its `LanguageNodeMap` --- no core edits. The full dataflow pass runs- only for functions a structural marker already flagged- (`large_method` / `brain_method` / `complex_method`), so it stays within the- health-pass budget.--#### Dataflow / Extract Method coverage--The dataflow layer needs a `DefUseDialect` (plus the `assignment_kinds` /-`local_decl_kinds` and control-flow kinds on the language's `LanguageNodeMap`);-it is independent of the perf / class / assertion tiers. A language without a-dialect emits no Extract Method suggestions. Coverage rolls out in value order-(the high-yield set first), degrading to silence elsewhere.--| Language | CFG + def/use | Extract Method | Notes |-|----------|:---:|:---:|---|-| Python | Y | Y | assignment, augmented, walrus, tuple-unpack, `for` / `with`-as / comprehension targets |-| Go | Y | Y | `:=` / `var`, `=` vs `+=` (operator-sniffed), `x++`, `range` binders, selector / index targets; method `receiver` seeded as a param |-| TypeScript / JavaScript | Y | Y | `let` / `const` / `var`, `=` / `+=`, `++`, array / object destructuring, `for...of` / `for...in` binders, member / subscript targets |-| Java | Y | Y | declarations (multi-declarator), `=` vs `+=` (operator-sniffed), `x++`, enhanced-`for` binders, try-with-resources bindings, field / array targets; `switch`-arm writes are conservative may-defs |-| Rust | Y | Y | `let` with destructuring patterns (tuple / slice / struct / ref), `=` vs `+=` (distinct node kinds), `for` / `if let` / `while let` binders, field / index / deref targets, `self` receiver seeded as a param; `?` counts as an early exit (no span containing one is offered); `match`-arm writes are conservative may-defs; a block's tail expression is never extracted over |-| Kotlin / C++ / C# | --- | --- | later |--Validated on real code (flagged-only, the production path): Go fires on-`gorilla/mux` (e.g. `setMatch` sheds ccn 15); TS/JS fires across the hosted-Next.js frontend; Java fires on `google/gson` (e.g. `JsonTreeReader.getPath`-sheds ccn 7); Rust fires on `sharkdp/fd` (e.g. `FormatTemplate::parse` sheds-ccn 6). The flagged-only gate held in every run (Go 8 / 108 functions,-TS 212 / 1172, Java 53 / 1082, Rust 8 / 217), keeping the per-file cost in the-low single-digit milliseconds.--#### Performance-signal coverage--The performance signal needs the `PerfDialect` above (plus `call_kinds` on-the language's `LanguageNodeMap`); it is independent of the control-flow /-class / assertion tiers. A language without a dialect simply emits no perf-findings.--| Language | io_in_loop | string_concat | Phase-7a loop markers | Other language-specific markers | sync-over-async |-|----------|:---:|:---:|---|---|:---:|-| Python | Y | Y | resource_construction, lock, serial_await, membership | --- | `blocking_sync_in_async` |-| TypeScript / JavaScript | Y | Y | resource_construction, serial_await, membership | --- | --- |-| Java | Y | Y | resource_construction, lock | `regex_compile_in_loop` | --- (no async syntax) |-| Go | Y | Y | resource_construction, lock | `defer_in_loop`, `regex_compile_in_loop` | --- (goroutines) |-| C# | Y | Y | resource_construction, lock, serial_await | --- (.NET caches regexes) | `blocking_sync_in_async` (`.Result` / `.Wait()` / `.GetResult()`) |-| Rust | Y | --- (`String` is amortized) | resource_construction, serial_await | `regex_compile_in_loop` (`Regex::new`) | `blocking_sync_in_async` (`block_on` / `std::thread::sleep` / sync `std::fs` in `async fn`) |-| Dart | Y | Y | resource_construction, serial_await | --- | --- |-| Kotlin / C++ | --- | --- | --- | --- | --- |--The Rust dialect classifies `sqlx` executor verbs (db), `reqwest::get` /-`reqwest::post` and `std::fs` (network / filesystem) as sinks; `io_in_loop` is-multi-repo validated (85% on bevy / rtk / deepwiki-rs). `string_concat_in_loop`-is intentionally absent: Rust `String::push_str` / `+=` are amortized O(1), so-it would be a guaranteed false positive. Kotlin will be nearly free once it-rides the JVM lexicon; C++ is later. What each dialect classifies as a db /-network / filesystem / subprocess sink, and the per-language precision hazards,-lives in `docs/CODE_HEALTH.md`.+## Lightweight, Partial, and Structural tiers----+**Lightweight** (Elixir, Clojure, Haskell, Lean 4, Erlang, F#), no AST parsing,+but a real file-level import graph from a regex tier: import statements are+extracted per-language and resolved against a declared module-name index. The+knowledge graph runs in flow/sparse mode on the result: honest file-to-file+dependencies, no symbol-level claims. F# additionally honours the fsproj+`<Compile Include>` compile-order spine.-## Architecture--The language pipeline is fully modular. Per-language code lives in-dedicated subpackages: adding a new language means dropping a file-into each subpackage rather than editing monoliths.--```-ingestion/- languages/ # LanguageRegistry + LanguageSpec (identity data)- spec.py # LanguageSpec dataclass (the schema)- registry.py # LanguageRegistry lookup interface + REGISTRY singleton- specs/ # one module per language, each exporting `SPEC`- __init__.py # aggregates every SPEC into ordered `ALL_SPECS`- python.py typescript.py go.py rust.py csharp.py … (44 languages)- python_modules.py # dotted-module ↔ file index (src / monorepo / PEP 420)- extractors/ # Per-language AST extraction- visibility.py # symbol visibility (public/private/protected)- signatures.py # human-readable signature building- docstrings.py # module + symbol docstring extraction- bindings/ # import name + alias binding extraction (per-lang)- __init__.py # extract_import_bindings dispatcher- python.py ts_js.py go.py rust.py java.py kotlin.py- ruby.py csharp.py swift.py scala.py php.py cpp.py- heritage/ # inheritance/interface/trait extraction (per-lang)- __init__.py # extract_heritage + HERITAGE_EXTRACTORS dispatcher- python.py ts_js.py java.py go.py rust.py cpp.py- kotlin.py ruby.py swift.py csharp.py scala.py php.py- resolvers/ # Per-language import resolution- python.py # dotted imports via module index: __init__.py- # barrels, src/ + monorepo packages/*/src, namespace pkgs- typescript.py # multi-ext probe, tsconfig aliases- go.py # go.mod module path stripping- rust.py # crate::/self::/super::, mod.rs probing- cpp.py # compile_commands.json include paths- kotlin.py # package-to-directory mapping- ruby.py # require/require_relative resolution- csharp.py / dotnet/ # namespace-based + MSBuild project graph- swift.py # module import resolution- scala.py # package-to-directory mapping- php.py # namespace/PSR-4 resolution- generic.py # stem-matching fallback- framework_edges/ # Framework convention edges (one module per framework + base.py)- # __init__.py re-exports add_framework_edges; iterates FrameworkHandler list- # django/fastapi/flask/aspnet/rails/laravel/spring/express/go/rust/typo3- # + pytest_edges (conftest); base.py = read_text, _add_edge_if_new, name→file maps- dynamic_hints/ # Per-language dynamic-edge extractors- base.py # DynamicHintExtractor + DynamicEdge- registry.py # HintRegistry- django.py pytest_hints.py python_imports.py node.py dotnet.py- spring.py ruby.py php.py scala.py swift.py c.py luau.py go.py- parser.py # ASTParser (language-agnostic orchestration)- graph.py # GraphBuilder (import/call/heritage resolution)--analysis/- dead_code/ # Dead code detection (Phase 1 split)- __init__.py # re-exports DeadCodeAnalyzer + dataclasses- analyzer.py # DeadCodeAnalyzer class + four detection passes- models.py # DeadCodeKind, DeadCodeFindingData, DeadCodeReport- constants.py # never-flag globs, framework decorators, fixtures- dynamic_markers.py # per-language source-text dynamic markers-```--Adding a new language requires zero changes to `parser.py`, `graph.py`,-`traverser.py`, or any analysis core file. New language work consists of-adding one file to each per-language subpackage and registering it in the-relevant `__init__.py` dispatcher / dict.+**Partial** (Luau / Roblox), AST symbols, Luau type aliases, and `require(...)`+capture are wired. Import resolution handles string literals, `script` relative+instance paths (including `:WaitForChild` idioms), absolute Roblox paths via+Rojo's `default.project.json`, and `@alias` requires via `.luaurc`. No health+markers yet.++**Structural** (Objective-C, R, Zig, Julia, Elm, OCaml, Crystal, Nim, D) -+tracked in git history (blame, hotspots, co-change) but no AST parsing. Files+appear in the wiki as traversal-level entries, and the knowledge graph runs in+structural mode: it orients by directory structure, naming, and git evidence,+and never claims an execution flow it cannot see.----## Workspace contract extraction--In **workspace mode** (multiple repos indexed together), repowise links-service-to-service API contracts (HTTP routes and gRPC services) so a-provider endpoint in one repo connects to its consumers in another. The-extractors live in `core/workspace/extractors/` and follow the same-dialect-plugin shape as the rest of the language pipeline: the orchestrator-owns only the file walk, and each framework / client library is an-independent module registered in a tuple.--```-workspace/extractors/- base.py # iter_source_files walk + ScanContext (shared by all)- langs.py # registry-derived extension sets (JS_TS, PYTHON, RUST, …)- http/- dialect.py # HttpDialect protocol + build_provider/consumer_contract- paths.py # normalize_http_path + URL helpers- express.py fastapi.py spring.py laravel.py go.py aspnet.py # providers- js_clients.py python_clients.py csharp_http.py # consumers- __init__.py # HttpExtractor + PROVIDER_DIALECTS / CONSUMER_DIALECTS- grpc/- dialect.py # GrpcDialect protocol + make_grpc_contract- proto.py go.py java.py python.py typescript.py csharp.py- __init__.py # GrpcExtractor + DIALECTS-```--A dialect declares the file extensions it understands (via `langs.py`) and-turns regex matches into `Contract`s through the shared builders, so every-dialect emits identically-shaped providers/consumers and the path-normalization-rules live in one place. Framework-specific quirks stay local to the dialect:-Spring/ASP.NET class-prefix stitching, Go `HandleFunc` -> `*` method, fetch-GET/method de-duplication.--**Adding a framework or client** means dropping one module into `http/` or-`grpc/` and appending its dialect to the relevant registry tuple-(`PROVIDER_DIALECTS`, `CONSUMER_DIALECTS`, or `DIALECTS`): no orchestrator-edits. The current coverage:--| Contract | Providers | Consumers |-|----------|-----------|-----------|-| **HTTP** | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal), Rust (Axum routes, Actix/Rocket attribute macros) | `fetch` / `axios` / URL-literal wrapper calls (JS/TS), `requests` / `httpx` (Python), `HttpClient` / wrapper methods / `UnityWebRequest` / Best.HTTP (C#), `reqwest` (Rust) |-| **gRPC** | `.proto` IDL, Go, Java, Python, NestJS (`@GrpcMethod`), C# (gRPC-dotnet) | Go, Java, Python, C# |+## Code-health coverage++Code-health markers run off a per-language complexity-walker map that is+**independent** of `.scm` parsing, a language can parse perfectly for the graph+yet still need this map before health markers fire. This table is why a language+is "Full" vs "Good".++| Language | Complexity / nesting | Class metrics (LCOM4, god-class) | Assertion smells | Extract Method (dataflow) | Performance risk |+|----------|:---:|:---:|:---:|:---:|:---:|+| Python | ✅ | ✅ | ✅ | ✅ | ✅ |+| TypeScript / JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ |+| Java | ✅ | ✅ | ✅ | ✅ | ✅ |+| Go | ✅ | n/a¹ | ✅ | ✅ | ✅ |+| Rust | ✅ | ✅ | ✅ | ✅ | ✅² |+| C# | ✅ | ✅ | ✅ | later | ✅ |+| Kotlin | ✅ | ✅ | ✅ | later | later |+| C++ | ✅ | ✅ | ✅ | later | later |+| Dart | ✅ | n/a³ | ✅ | later | ✅ |++¹ Go methods attach to a type via an external receiver rather than nesting in a+class body, so class-level metrics aren't computable; Go gets the function- and+assertion-level markers.+² Rust omits `string_concat_in_loop` by design (`String::push_str` is amortized+O(1), so it would be a guaranteed false positive).+³ Dart assertion smells cover `assert` statements only; `expect()` calls have no+call-node type to key on.++The **performance** signal (`io_in_loop`, `string_concat_in_loop`,+`resource_construction_in_loop`, language-specific markers like Go+`defer_in_loop` and C# sync-over-async) and the **dataflow** layer (powering+Extract Method) each roll out per language in value order, degrading to silence+where a dialect isn't wired yet. Per-marker mechanics and precision hazards:+[CODE_HEALTH.md](CODE_HEALTH.md).---## Roadmap-| Language | Target Tier | Status |+| Language | Target tier | Status ||----------|------------|--------|-| Dart | Good | Shipped: tree-sitter AST (symbols, calls, bindings, heritage), health control-flow + class facts, perf dialect (io/await/concat/resource in loop), Flutter route + `runApp` framework edges; next: riverpod/get_it dynamic hints, dataflow dialect |+| Dart | Good | Shipped: AST, health control-flow + class facts, perf dialect, Flutter edges. Next: riverpod/get_it dynamic hints, dataflow dialect |+| Kotlin / C++ | Full (health) | Perf + dataflow dialects pending; everything else shipped |+| C# | Full (health) | Dataflow dialect pending; perf shipped || Elixir | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-elixir` available) || F# | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-f-sharp` available) |-| SQL / dbt | -- | DDL symbols, dbt lineage, app-to-database contracts (workspace `data` extractor), and precision-gated health markers all shipped; next: column-level blast radius |+| SQL / dbt | - | DDL symbols, dbt lineage, app-to-database contracts, health markers shipped. Next: column-level blast radius |++---++## See also++- [architecture/language-support.md](architecture/language-support.md), pipeline internals + how to add a language+- [CODE_HEALTH.md](CODE_HEALTH.md), code-health markers and per-language precision+- [WORKSPACES.md](WORKSPACES.md), cross-repo contracts and co-changediff --git a/docs/MCP_TOOLS.md b/docs/MCP_TOOLS.mdindex 9595d8eb3..9814be0dc 100644--- a/docs/MCP_TOOLS.md+++ b/docs/MCP_TOOLS.md@@ -1,6 +1,8 @@# MCP Tools Reference-repowise exposes a curated set of tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence: dependency graph, git history, documentation, and architectural decisions. A single-repo server advertises 10 tools by default; workspace mode adds 3 more automatically. The surface is configurable; see [Configuring the tool surface](#configuring-the-tool-surface).+repowise exposes a curated set of tools via the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). These tools give AI coding assistants (Claude Code, Codex, Cursor, Cline, Windsurf) structured access to your codebase intelligence: dependency graph, git history, documentation, and architectural decisions.++16 tools are registered in total. A single-repo server advertises 11 by default: the nine flagship tools below plus `list_repos` and `generate_refactoring_code`. Workspace mode adds 3 more automatically, for 14. Two further tools are off by default everywhere and must be opted in. The surface is configurable; see [Configuring the tool surface](#configuring-the-tool-surface).**Start the MCP server:**@@ -14,7 +16,7 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport----## Tool Overview+## The nine flagship tools| Tool | Purpose | Typical use ||------|---------|-------------|@@ -27,24 +29,20 @@ repowise mcp --transport sse --port 7338 # legacy SSE transport| `get_why` | Architectural decisions | Before structural changes || `get_dead_code` | Unreachable code | Cleanup tasks || `get_health` | Code-health marker scores | Before refactoring, find the worst files |-| `list_repos` | List the repos a server is serving | Discovering workspace repo aliases |-| `get_blast_radius` | Cross-repo downstream impact (workspace only) | Before changing a service other repos consume |-| `get_conformance` | Architecture rule violations + cycles (workspace only) | Auditing or before changing service boundaries |-| `get_architecture` | System coupling, cyclic core, 1-10 architecture score (workspace only) | Gauging overall structure before a cross-service refactor |-Two further tools are **off by default** and opt-in (see below): `get_dependency_path` (shortest dependency path between two symbols/files) and `get_execution_flows` (top entry points and their call traces).+Also always on by default: `list_repos` (repo aliases) and `generate_refactoring_code` (opt-in code generation from a health plan). See [Supplementary tools](#supplementary-tools).---## Configuring the tool surface-The default surface is deliberately small: fewer, richer tools mean fewer round-trips and less schema overhead per task. What a server advertises is resolved from three things: each tool's defaults, whether the server is in workspace mode, and an optional override.+The default surface is deliberately small: fewer, richer tools mean fewer round-trips and less schema overhead per task. What a server advertises is resolved from three things: each tool's `default`/`requires_workspace` metadata, whether the server is in workspace mode, and an optional override.-- **Default (single-repo):** the 10 tools above (every tool except the workspace-only three).-- **Default (workspace):** those 10 plus `get_blast_radius`, `get_conformance`, and `get_architecture`, which are added automatically when the server is started inside a workspace. They are never advertised outside one.-- **Opt-in tools:** `get_dependency_path` and `get_execution_flows` are registered but off by default. Turn them on per repo.+- **Default (single-repo):** 11 tools, the nine flagship tools plus `list_repos` and `generate_refactoring_code` (though `generate_refactoring_code` returns an error until its config flag is set; see below).+- **Default (workspace):** those 11 plus `get_architecture`, `get_blast_radius`, and `get_conformance`, added automatically when the server starts inside a workspace. They are never advertised outside one.+- **Opt-in tools:** `get_dependency_path` and `get_execution_flows` are registered but off by default everywhere. Turn them on per repo.-**Configure it in `.repowise/config.yaml`** under an `mcp.tools` key. Two shapes are supported:+**Configure it in `.repowise/config.yaml`** under an `mcp.tools` key. Three shapes are supported:```yaml# Adjust the default set with + / - deltas (the common case):@@ -94,8 +92,23 @@ envelope lists how to get it back:Truncated skeleton blocks are replaced in place by a `[repowise#<ref>: ...]`marker; everything else is captured into one combined document per response.Resolve refs with `repowise expand <ref>` from a shell, or-`get_symbol("repowise#<ref>")` from any MCP client; the tool count stays at-nine. See [DISTILL.md](DISTILL.md) for the full reversibility model.+`get_symbol("repowise#<ref>")` from any MCP client. See+[DISTILL.md](DISTILL.md) for the full reversibility model.++**The `_meta` envelope** (all fields optional, present only when meaningful):++| Field | When present |+|-------|--------------|+| `timing_ms` | Tool wall-time |+| `hint` | A short, conservative follow-up suggestion |+| `cached` | Only when `true` |+| `index_age_days` | Days since the last `repowise update` |+| `indexed_commit` | Short (12-char) SHA the index was built against |+| `live_head` | Only when it differs from `indexed_commit` |+| `stale_warning` | Only on a real signal: HEAD mismatch, or age over ~90 days when git is unreachable |+| `embedder`, `embedder_degraded`, `embedder_warning` | Only when the embedder fell back to a mock/degraded mode |++Silence on these fields means the index is current; don't infer staleness from their absence. `list_repos`, `get_architecture`, `get_blast_radius`, and `get_conformance` don't carry a freshness envelope at all.---@@ -103,27 +116,29 @@ nine. See [DISTILL.md](DISTILL.md) for the full reversibility model.Architecture summary, module map, entry points, git health, and community summary.-**Parameters:** None required.+**Parameters:**-| Parameter | Type | Description |-|-----------|------|-------------|-| `repo` | string | *(workspace only)* Target repo alias, or `"all"` |+| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |+| `include` | list[string] | No | `"content"` returns the full overview essay in `content_md` instead of the compact summary section |-**Returns:** Architecture description, key modules with purpose and owner, entry points, tech stack, hotspot files, knowledge silos, community summary (top communities by size with labels and cohesion scores).+**Returns:** Architecture description, key modules with purpose and owner, entry points, tech stack, hotspot files, knowledge silos, community summary (top communities by size with labels and cohesion scores). `content_md` is compact by default (summary + tech stack + layers); pass `include=["content"]` for the full essay.-**When to use:** First call on any unfamiliar codebase. Gives the agent a mental map before diving into specifics.+**When to use:** First call on any unfamiliar codebase. Gives the agent a mental map before diving into specifics. Skip on later calls in the same session; it doesn't change mid-session.-**Example call:**+**Example calls:**```get_overview()+get_overview(include=["content"])```---## `get_answer`-One-call RAG: retrieves over the wiki, gates synthesis on confidence, and returns a cited 2–5 sentence answer.+One-call RAG: retrieves over the wiki, gates synthesis on confidence, and returns a cited 2-5 sentence answer.**Parameters:**@@ -190,26 +205,29 @@ Also resolves **omission refs** (`repowise#<12-hex>`) from truncated responses.| Parameter | Type | Required | Description ||-----------|------|----------|-------------|-| `symbol_id` | string | Yes | Canonical `"path/to/file.py::SymbolName"` from `get_context`'s symbol list (normalises `::` / `.` / `/` separators across languages), **or** an omission ref `"repowise#<12-hex>"` / a pasted whole `[repowise#…]` marker. |-| `query` | string | No | Omission refs only: return just the stored lines matching this regex (or substring). Ignored for symbol ids. |-| `context_lines` | int | No | Extra source lines before/after the symbol (0–50, default 0) |+| `symbol_id` | string | Yes | One of three forms: `"path/to/file.py::SymbolName"` (canonical, from `get_context`'s symbol list; normalises `::` / `.` / `/` separators across languages), `"path/to/file.py:140-180"` (a live range read, 200 lines max), or an omission ref `"repowise#<12-hex>"` / a pasted whole `[repowise#...]` marker. |+| `query` | string | No | Omission refs only: return just the stored lines matching this regex (or substring). Ignored for symbol ids and range reads. |+| `context_lines` | int | No | Extra source lines before/after the symbol (0-50, default 0) || `repo` | string | No | *(workspace only)* Usually omitted; `"all"` is not supported |-**Returns:** For a symbol id: the symbol's source bytes (bounded at ~400 lines),+**Returns:** For a symbol id or range: the source bytes (bounded at ~400 lines),its exact start/end line numbers, kind, and a `truncated` flag; on a miss, an-`error` with the closest matches. For an omission ref: the stored content plus-provenance (`source`, `created_at`, `original_tokens`).+`error` with the closest matches (`fallback_lines` from a live grep). For an+omission ref: the stored content plus provenance (`source`, `created_at`,+`original_tokens`).**When to use:** When you need the body of one function or class: pipe the-`symbol_id` straight from `get_context`'s symbol list. Or when a response's-`_meta.omitted` lists refs you want back and you have no shell for-`repowise expand` (e.g. Claude Desktop).+`symbol_id` straight from `get_context`'s symbol list. Use the line-range form+for anything that falls between symbols. Or when a response's `_meta.omitted`+lists refs you want back and you have no shell for `repowise expand` (e.g.+Claude Desktop).**Example calls:**```get_symbol(symbol_id="src/auth/service.py::AuthService")get_symbol(symbol_id="src/auth/service.py::login", context_lines=10)+get_symbol(symbol_id="src/auth/service.py:140-180")get_symbol(symbol_id="repowise#a1b2c3d4e5f6")get_symbol(symbol_id="repowise#a1b2c3d4e5f6", query="FAILED")```@@ -218,7 +236,7 @@ get_symbol(symbol_id="repowise#a1b2c3d4e5f6", query="FAILED")## `search_codebase`-Hybrid code search over RepoWise's indexes. A single tool that, depending on+Hybrid code search over repowise's indexes. A single tool that, depending onthe shape of the query, searches the indexed **symbols**, **file paths**, orthe **wiki**, instead of forcing a fallback to Grep for identifiers.@@ -251,7 +269,8 @@ the **wiki**, instead of forcing a fallback to Grep for identifiers.- *Concept hits*: ranked wiki pages with `relevance_score`, `snippet`, `target_path`, and a `search_method` (`embedding` vs `bm25` fallback).Tombstoned and `exclude_patterns`-excluded results are filtered. In workspace-mode, structural and concept searches both federate across repos and merge.+mode, structural and concept searches both federate across repos and merge+(this is the one tool where `repo="all"` is fully supported).**When to use:** Locating a function/class/method by name, resolving apath-shaped query, or discovering pages by topic: the symbol/file shapes pipe@@ -260,9 +279,9 @@ directly into `get_symbol` / `get_context`.**Example calls:**```-search_codebase(query="GitIndexer index_repo") # → symbol hits-search_codebase(query="core/ingestion/indexer.py") # → file hits-search_codebase(query="rate limit OR throttle OR retry") # → wiki pages+search_codebase(query="GitIndexer index_repo") # -> symbol hits+search_codebase(query="core/ingestion/indexer.py") # -> file hits+search_codebase(query="rate limit OR throttle OR retry") # -> wiki pagessearch_codebase(query="login", mode="symbol", symbol_kind="method")```@@ -277,10 +296,10 @@ Modification risk assessment for files or a set of changed files.| Parameter | Type | Required | Description ||-----------|------|----------|-------------|| `targets` | list[string] | No | File paths to assess |-| `changed_files` | list[string] | No | Files in a PR/changeset for blast radius analysis |+| `changed_files` | list[string] | No | Files in a PR/changeset for blast radius analysis; passing this switches the response into PR-directive mode || `repo` | string | No | *(workspace only)* Target repo alias |-**Returns:** Per-file risk score (0–10), hotspot status, dependent count, co-change partners, blast radius, recommended reviewers, test gap analysis, security signals. In workspace mode, enriched with cross-repo co-change partners and contract dependencies.+**Returns:** Per-file risk score (0-10), hotspot status, dependent count, co-change partners, blast radius, recommended reviewers, test gap analysis, security signals. In workspace mode, enriched with cross-repo co-change partners and contract dependencies.When `changed_files` is passed, the response leads with a `directive` block. In workspace mode that directive also carries the cross-repo fallout of the changed repo:@@ -301,88 +320,23 @@ get_risk(changed_files=["src/api/routes.ts", "src/middleware/cors.ts"])----## `get_blast_radius`--*(Workspace mode only.)* Cross-repo downstream impact: if you change this service, what breaks across the other repos?--**Parameters:**--| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| `targets` | list[string] | Yes | Node ids (`repo` or `repo::service/path`) or repo aliases |-| `max_depth` | int | No | Reachability depth (1–8, default 3) |-| `include_behavioral` | bool | No | Include co-change (behavioral) edges (default true) |--**Returns:** The impacted services ranked by impact `score`, each with `distance` (hops), `structural` (a real dependency vs co-change only), and the edge kinds that carried the impact; plus `impacted_repos`, `structural_count` / `behavioral_count`, `total_impacted`, and any `unresolved_targets`.--**When to use:** Before changing a high-fan-out provider, see who consumes it across repo boundaries. Structural impact (`will break`) outweighs behavioral co-change (`may drift`). Reads the same system graph the [Live System Map](WORKSPACES.md#live-system-map) renders.--**Example calls:**--```-get_blast_radius(targets=["backend"])-get_blast_radius(targets=["mono::services/auth"], max_depth=2, include_behavioral=false)-```-------## `get_conformance`--*(Workspace mode only.)* Architecture governance: does the live system graph obey the declared dependency rules, and are there circular service dependencies?--**Parameters:**--| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| `repo` | string | No | Limit findings to those involving this repo alias |--**Returns:** `violations` (each with the offending `source`/`target` services, the `rule_source`/`rule_target` matchers that fired, and the `edge_kind`), `cycles` (each with the participating `nodes` and `length`), and the `violation_count` / `cycle_count` / `rules_evaluated` rollups.--**When to use:** Before a refactor that changes service boundaries, or to audit whether the live architecture still matches the intended one. Rules are declared under `conformance:` in `.repowise-workspace.yaml`. See [Architecture Conformance](WORKSPACES.md#architecture-conformance).--**Example calls:**--```-get_conformance()-get_conformance(repo="frontend")-```-------## `get_architecture`--*(Workspace mode only.)* The one evaluative read of the whole system: how coupled is it, where is the architectural core, and a single 1-10 architecture score. Deterministic, structural edges only (co-change excluded).--**Parameters:** none.--**Returns:** `score` (1-10), `architecture_type` (`core-periphery` or `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size` / `core_ratio` / `core_members` (the largest cyclic group), `cycle_count`, `conformance_violations`, a `role_breakdown` (count of Core / Shared / Control / Peripheral services), and a one-line `summary`.--**When to use:** Before a cross-service refactor, or to gauge and compare overall system structure over time. See [Architecture Metrics](WORKSPACES.md#architecture-metrics).--**Example call:**--```-get_architecture()-```------## `get_why`-Architectural decision intelligence. Three modes depending on parameters.+Architectural decision intelligence. Falls back to git archaeology when no decision records exist for a path, and further to a rationale comment mined live from the source when neither decisions nor git history explain the "why".**Parameters:**| Parameter | Type | Required | Description ||-----------|------|----------|-------------|-| `query` | string | No | Natural language query about decisions, OR a file path |-| `repo` | string | No | *(workspace only)* Target repo alias |+| `query` | string | No | Natural language question about decisions, OR a file/module path |+| `targets` | list[string] | No | File paths to anchor an NL `query` search to |+| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` (only when `query` is given) |**Modes:**-1. **NL search**: pass a question: `get_why(query="why JWT over sessions?")` -> searches decision records-2. **Path-based**: pass a file path: `get_why(query="src/auth/service.ts")` -> returns decisions governing that file-3. **Health dashboard**: no args: `get_why()` -> stale decisions, conflicts, ungoverned hotspots+1. **NL search**: pass a question, optionally anchored to `targets`: `get_why(query="why JWT over sessions?")` -> searches decision records.+2. **Path-based**: pass a file path as `query`: `get_why(query="src/auth/service.ts")` -> returns decisions governing that file plus its origin story.+3. **Health dashboard**: no `query`: `get_why()` -> stale decisions, conflicts, ungoverned hotspots.**Returns:** Matching decision records with title, rationale, alternatives considered, affected files, staleness score. Health mode returns stale decisions, conflicts, and ungoverned hotspots.@@ -393,6 +347,7 @@ Architectural decision intelligence. Three modes depending on parameters.```get_why(query="rate limiting")get_why(query="src/payments/processor.ts")+get_why(query="why is caching split from the eviction path?", targets=["src/cache"])get_why()```@@ -400,25 +355,36 @@ get_why()## `get_dead_code`-Unreachable code sorted by confidence tier with cleanup impact estimates.+Unreachable code, unused exports, unused internals, and zombie packages, sorted by confidence tier with cleanup impact estimates. Flag-based, not include-list-based.**Parameters:**| Parameter | Type | Required | Description ||-----------|------|----------|-------------|-| `min_confidence` | float | No | Minimum confidence threshold (default: 0.4) |-| `include_internals` | boolean | No | Include private/underscore symbols (default: false) || `repo` | string | No | *(workspace only)* Target repo alias |--**Returns:** Dead code findings grouped by confidence tier (`safe_to_delete` ≥ 0.70, `review_first` < 0.70). Each finding includes: file path, kind (unreachable_file, unused_export, unused_internal, zombie_package), confidence score, line count, and cleanup impact estimate.--**When to use:** Cleanup tasks. Conservative by design: `safe_to_delete` excludes dynamically-loaded patterns and framework-decorated functions.+| `kind` | string | No | Restrict to one finding kind: `unreachable_file` \| `unused_export` \| `unused_internal` \| `zombie_package` |+| `min_confidence` | float | No | Minimum confidence floor (default `0.5`; `0.7`+ is cleanup-ready only) |+| `safe_only` | boolean | No | Deletion-ready findings only, excluding anything with runtime-load risk (default `false`) |+| `limit` | int | No | Max findings per tier, clamped to 25 (default 20) |+| `tier` | string | No | Restrict to one tier: `high` (>= 0.8) \| `medium` \| `low` |+| `directory` | string | No | Path-prefix filter |+| `owner` | string | No | Primary-owner filter |+| `group_by` | string | No | Roll findings up by `directory` or `owner` instead of listing them flat |+| `include_internals` | boolean | No | Include private/underscore symbols (default `false`) |+| `include_zombie_packages` | boolean | No | Include zombie-package findings (default `true`) |+| `no_unreachable` | boolean | No | Exclude `unreachable_file` findings (default `false`) |+| `no_unused_exports` | boolean | No | Exclude `unused_export` findings (default `false`) |++**Returns:** Dead code findings grouped by confidence tier (high >= 0.8, medium, low). Each finding includes: file path, kind, confidence score, line count, and cleanup impact estimate. In workspace mode, confidence is lowered on findings other repos still import.++**When to use:** Cleanup tasks, not a targeted fix. Conservative by design: `safe_only` excludes dynamically-loaded patterns and framework-decorated functions.**Example calls:**```get_dead_code()-get_dead_code(min_confidence=0.8, include_internals=true)+get_dead_code(min_confidence=0.8, tier="high", safe_only=true)+get_dead_code(kind="unused_export", group_by="owner")```---@@ -436,7 +402,7 @@ code-health merge-gate judges it on.| Parameter | Type | Required | Description ||-----------|------|----------|-------------|| `targets` | list[string] | No | File paths, or `module:foo` to expand a module's file set. Empty means dashboard mode. |-| `include` | list[string] | No | Opt-in blocks (default response stays lean): `"biomarkers"` (findings in dashboard mode), `"refactoring"` (structured, graph-aware refactoring plans; see below), `"trend"` (snapshot diff + declining / predicted-decline alerts), `"coverage"`, `"accuracy"` (the "does the score find the bugs?" stat, dashboard mode), `"signals"` (per-file process / people / topology signals, targeted mode), `"churn_complexity"` (churn × complexity quadrant points, dashboard mode), and a dimension name (`"performance"` / `"defect"` / `"maintainability"`) to filter findings to that pillar. |+| `include` | list[string] | No | Opt-in blocks (default response stays lean): `"biomarkers"` (findings in dashboard mode), `"refactoring"` (structured, graph-aware refactoring plans; see below), `"trend"` (snapshot diff + declining / predicted-decline alerts), `"coverage"`, `"accuracy"` (the "does the score find the bugs?" stat, dashboard mode), `"signals"` (per-file process / people / topology signals, targeted mode), `"churn_complexity"` (churn x complexity quadrant points, dashboard mode), and a dimension name (`"performance"` / `"defect"` / `"maintainability"`) to filter findings to that pillar. || `repo` | string | No | *(workspace only)* Target repo alias || `limit` | int | No | Max rows in the lowest-scoring file list (default 20, capped at 50) |@@ -458,9 +424,9 @@ make that actionable rather than a mystery:recover to reach the Healthy floor (8.0), how many files sit below it, and howfew of them carry the whole gap (`files_to_reach_target`) or half of it(`files_for_half_gap`). This reframes a repo-wide number as a short worklist.-- Every metric row carries `weighted_deficit = (8 - score) × nloc`: how much the+- Every metric row carries `weighted_deficit = (8 - score) x nloc`: how much therepo headline recovers if that file reaches 8.0. `high_leverage_files`- (dashboard mode) is the top-N ranked by it — distinct from `worst_files`, which+ (dashboard mode) is the top-N ranked by it, distinct from `worst_files`, whichsorts by raw score and ranks a 30-line file at 1.0 equal to a 1,200-line file at1.0 that moves the average ~40x more.@@ -481,12 +447,12 @@ The opt-in enrichments:strings): `extract_class` (the cohesion `groups` to split into), `extract_helper`(clone `occurrences` + `suggested_site`), `move_method` (`{method, from_class,to_class}`), and `break_cycle` (the import `cut_edges`). Each plan carries its- `evidence`, `impact_delta`, `effort_bucket`, and `blast_radius`. The list is- capped to `limit` and ranked file-leverage-first (by the file's- `weighted_deficit`, then per-plan impact), so plans on the files that move the- headline surface first; `refactoring_plans_total` reports the full count behind- the cap. Each plan echoes its `file_weighted_deficit`. Full shapes in- [`docs/REFACTORING.md`](REFACTORING.md).+ `evidence`, `impact_delta`, `effort_bucket`, `blast_radius`, and an `id` you can+ hand to `generate_refactoring_code`. The list is capped to `limit` and ranked+ file-leverage-first (by the file's `weighted_deficit`, then per-plan impact), so+ plans on the files that move the headline surface first; `refactoring_plans_total`+ reports the full count behind the cap. Each plan echoes its+ `file_weighted_deficit`. Full shapes in [`docs/REFACTORING.md`](REFACTORING.md).- **dimension filter** narrows the returned findings to one pillar. Pair with`"biomarkers"` for the full (uncapped) finding set, e.g.`include=["biomarkers", "performance"]`.@@ -509,13 +475,145 @@ get_health(targets=["module:src.api"], include=["trend", "refactoring"])---+## Supplementary tools++These are registered and on by default (in the modes noted) but are not part+of the nine-tool headline set.++### `list_repos`++Lists the repos this server is serving. No parameters.++**Returns:** In workspace mode, `workspace: true`, the workspace root, the default repo alias, and every configured repo alias (`repos`). In single-repo mode, `workspace: false` and a single `"default"` alias.++**When to use:** Discovering the `repo` aliases to pass to other tools, especially in workspace mode.++```+list_repos()+```++### `generate_refactoring_code`++Turns one structured refactoring plan from `get_health(include=["refactoring"])` into actual generated code and a unified diff, grounded on the plan plus the real source spans it references. For Extract Class, the result includes an LCOM4 before/after self-check.++**Disabled by default.** Returns `{"error": "disabled", ...}` unless `refactoring.llm.enabled: true` is set in the repo's `.repowise/config.yaml`. When enabled, it uses the repo's configured LLM provider/model (bring your own key) and caches results by a content hash, so an unchanged plan never regenerates.++**Parameters:**++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `suggestion_id` | string | Yes | The `id` of a plan returned by `get_health(include=["refactoring"])` |+| `repo` | string | No | *(workspace only)* Target repo alias |++**When to use:** After `get_health(include=["refactoring"])` surfaces a plan you want turned into an applyable diff, and your repo has opted into LLM-backed generation.++```+generate_refactoring_code(suggestion_id="a1b2c3d4")+```++### Workspace-only tools++*(Available only when the server is started inside a workspace; see [Workspace Mode](#workspace-mode).)*++#### `get_blast_radius`++Cross-repo downstream impact: if you change this service, what breaks across the other repos?++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `targets` | list[string] | Yes | Node ids (`repo` or `repo::service/path`) or repo aliases |+| `max_depth` | int | No | Reachability depth (1-8, default 3) |+| `include_behavioral` | bool | No | Include co-change (behavioral) edges (default `true`) |++**Returns:** The impacted services ranked by impact `score`, each with `distance` (hops), `structural` (a real dependency vs co-change only), and the edge kinds that carried the impact; plus `impacted_repos`, `structural_count` / `behavioral_count`, `total_impacted`, and any `unresolved_targets`.++**When to use:** Before changing a high-fan-out provider, see who consumes it across repo boundaries. Structural impact ("will break") outweighs behavioral co-change ("may drift"). Reads the same system graph the [Live System Map](WORKSPACES.md#live-system-map) renders.++```+get_blast_radius(targets=["backend"])+get_blast_radius(targets=["mono::services/auth"], max_depth=2, include_behavioral=false)+```++#### `get_conformance`++Architecture governance: does the live system graph obey the declared dependency rules, and are there circular service dependencies?++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `repo` | string | No | Limit findings to those involving this repo alias |++**Returns:** `violations` (each with the offending `source`/`target` services, the `rule_source`/`rule_target` matchers that fired, and the `edge_kind`), `cycles` (each with the participating `nodes` and `length`), and the `violation_count` / `cycle_count` / `rules_evaluated` rollups.++**When to use:** Before a refactor that changes service boundaries, or to audit whether the live architecture still matches the intended one. Rules are declared under `conformance:` in `.repowise-workspace.yaml`. See [Architecture Conformance](WORKSPACES.md#architecture-conformance).++```+get_conformance()+get_conformance(repo="frontend")+```++#### `get_architecture`++The one evaluative read of the whole system: how coupled is it, where is the architectural core, and a single 1-10 architecture score. Deterministic, structural edges only (co-change excluded). No parameters.++**Returns:** `score` (1-10), `architecture_type` (`core-periphery` or `hierarchical`), `propagation_cost_pct` (share of other services the average service reaches), `core_size` / `core_ratio` / `core_members` (the largest cyclic group), `cycle_count`, `conformance_violations`, a `role_breakdown` (count of Core / Shared / Control / Peripheral services), and a one-line `summary`.++**When to use:** Before a cross-service refactor, or to gauge and compare overall system structure over time. See [Architecture Metrics](WORKSPACES.md#architecture-metrics).++```+get_architecture()+```++### Opt-in tools++*(Registered but off by default in every mode; enable with `mcp.tools: ["+name"]` or `repowise mcp --tools "+name"`. See [Configuring the tool surface](#configuring-the-tool-surface).)*++#### `get_dependency_path`++Shortest dependency path between two files or modules.++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `source` | string | Yes | Source file or module path |+| `target` | string | Yes | Target file or module path |+| `repo` | string | No | *(workspace only)* Target repo alias; `"all"` is not supported |++**Returns:** The dependency path when one exists. When no direct path exists, visual context instead: nearest common ancestors, shared neighbors, community analysis, and bridge suggestions, to help debug architectural silos.++**When to use:** Understanding how two parts of the codebase are (or aren't) connected, or why an expected dependency doesn't show up.++```+get_dependency_path(source="src/api/routes.py", target="src/db/models.py")+```++#### `get_execution_flows`++Top entry points and their call traces: how the codebase actually executes.++| Parameter | Type | Required | Description |+|-----------|------|----------|-------------|+| `top_n` | int | No | Number of top entry points to trace (default 10) |+| `max_depth` | int | No | Max trace depth per flow (default 8) |+| `entry_point` | string | No | Trace from a specific symbol, overriding `top_n` scoring |+| `repo` | string | No | *(workspace only)* Target repo alias; `"all"` is not supported |++**Returns:** Scored entry points with BFS call-path traces showing which functions are called in sequence, and whether the flow crosses community boundaries.++**When to use:** Understanding runtime call flow through an unfamiliar system, or tracing what a specific entry point actually does end to end.++```+get_execution_flows()+get_execution_flows(entry_point="src/cli/main.py::main", max_depth=4)+```++---+## Workspace ModeIn workspace mode (initialized with `repowise init .`), all tools accept an optional `repo` parameter:- **Omit `repo`**: queries the default (primary) repo- **`repo="backend"`**: targets a specific repo by alias-- **`repo="all"`**: queries across all workspace repos (supported by `search_codebase`, `get_context`, `get_overview`; not supported by `get_symbol`)+- **`repo="all"`**: queries across all workspace repos (fully supported by `search_codebase`; `get_context` and `get_overview` also accept it; not supported by `get_symbol`, `get_dependency_path`, or `get_execution_flows`)The MCP server automatically enriches responses with cross-repo intelligence:- **Co-change partners** from other repos surfaced in `get_context` and `get_risk`@@ -533,7 +631,7 @@ The MCP server automatically enriches responses with cross-repo intelligence:In addition to the MCP tools above, `repowise init` installs AI-agent hooks (Claude Code and Codex) that provide **passive, automatic** context enrichment:- **Claude Code PostToolUse**: broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, and git operations can trigger stale-wiki notices.-- **Codex SessionStart/UserPromptSubmit**: Codex receives concise Repowise MCP workflow guidance when a session or prompt starts.+- **Codex SessionStart/UserPromptSubmit**: Codex receives concise repowise MCP workflow guidance when a session or prompt starts.- **Codex PostToolUse**: after edits or git operations, Codex receives a freshness reminder when indexed context may be stale.Hooks are lightweight reminders. MCP tools are for deeper, on-demand investigation. See [Auto-Sync](AUTO_SYNC.md) and [Codex Integration](CODEX.md) for details.diff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 000000000..2f898dc88--- /dev/null+++ b/docs/README.md@@ -0,0 +1,63 @@+# repowise documentation++The codebase intelligence layer for your AI coding agent. Index once, and give+your agent a dependency graph, git history, auto-generated docs, architectural+decisions, and a defect-validated code-health score, all through task-shaped MCP+tools.++New here? Start with the [Quickstart](QUICKSTART.md) (under 5 minutes, no API+key), then wire up [your agent](MCP_TOOLS.md).++## Get started++| Doc | What it covers |+|-----|----------------|+| [QUICKSTART.md](QUICKSTART.md) | Install, index your repo, and connect your agent in under 5 minutes |+| [USER_GUIDE.md](USER_GUIDE.md) | The everyday guide: the CLI, the local dashboard, and every view in it |+| [VSCODE.md](VSCODE.md) | The Repowise VS Code extension: health in the gutter, risk before you push, dashboards in the editor |++## Connect your AI agent++| Doc | What it covers |+|-----|----------------|+| [MCP_TOOLS.md](MCP_TOOLS.md) | The MCP tools, what each answers, and worked multi-tool examples |+| [CODEX.md](CODEX.md) | Wiring repowise into the Codex CLI |+| [OPENCODE.md](OPENCODE.md) | Wiring repowise into opencode |+| [DISTILL.md](DISTILL.md) | `repowise distill`: compress noisy command output before your agent reads it |++## The intelligence layers++| Doc | What it covers |+|-----|----------------|+| [INTELLIGENCE_LAYERS.md](INTELLIGENCE_LAYERS.md) | Overview of the five layers: graph, git, docs, decisions, code health |+| [CODE_HEALTH.md](CODE_HEALTH.md) | Defect risk, maintainability, and performance from 25 deterministic markers, plus refactoring targets |+| [REFACTORING.md](REFACTORING.md) | Concrete, graph-aware refactoring plans (Extract Class, Move Method, Break Cycle, …) |+| [CHANGE_RISK.md](CHANGE_RISK.md) | Score any commit or `base..HEAD` range 0–10 for defect risk |+| [LANGUAGE_SUPPORT.md](LANGUAGE_SUPPORT.md) | What works per language, across 15 parsed languages and 9 at the Full tier |+| [WORKSPACES.md](WORKSPACES.md) | Multi-repo intelligence: cross-repo contracts, co-changes, and federated MCP |+| [AUTO_SYNC.md](AUTO_SYNC.md) | Keep the index fresh automatically on every commit |+| [WIKI_STYLES.md](WIKI_STYLES.md) | Selectable documentation styles (comprehensive / reference / tutorial / caveman) |++## Reference++| Doc | What it covers |+|-----|----------------|+| [CLI_REFERENCE.md](CLI_REFERENCE.md) | Every command and flag |+| [CONFIG.md](CONFIG.md) | `.repowise/config.yaml`, `health-rules.json`, and environment variables |+| [COMPUTED_GLOSSARY.md](COMPUTED_GLOSSARY.md) | Definitions for every computed metric and term repowise reports |+| [TELEMETRY.md](TELEMETRY.md) | What anonymous telemetry collects, and how to turn it off |+| [UPGRADING.md](UPGRADING.md) | Notes for upgrading between versions |+| [CHANGELOG.md](CHANGELOG.md) | Release history |++## Teams & business++| Doc | What it covers |+|-----|----------------|+| [COMMERCIAL.md](COMMERCIAL.md) | Hosted tier, enterprise (on-prem, SSO/SCIM), and commercial licensing |++## Architecture & internals++How repowise is built, for contributors and the curious. See+[architecture/](architecture/README.md) for the full set: the system+architecture, code-health internals, the language pipeline, graph algorithms,+and more.diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 838fb0b84..caacbeb03 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -24,7 +24,7 @@ Everything you need to know to install, use, and get the most out of repowise.- [doctor](#repowise-doctor)- [workspace](#repowise-workspace)- [hook](#repowise-hook)-4. [Web UI](#web-ui)+4. [Web Dashboard](#web-dashboard)5. [MCP Integration with AI Editors](#mcp-integration-with-ai-editors)6. [Proactive Context Enrichment (Hooks)](#proactive-context-enrichment-hooks)7. [Output Distillation (Distill)](#output-distillation-distill)@@ -43,7 +43,7 @@ Everything you need to know to install, use, and get the most out of repowise.pip install repowise```-This installs the core engine, CLI, server, and MCP tools. No LLM provider SDK is included by default — install only the one you need:+This installs the core engine, CLI, server, and MCP tools. No LLM provider SDK is included by default, install only the one you need:```bashpip install "repowise[anthropic]" # Claude (Anthropic)@@ -71,7 +71,7 @@ pip install "repowise[postgres]"- Python 3.11 or later- Git (repowise analyzes your repository's git history)-- An LLM API key or authenticated Codex CLI (for documentation generation — not needed for analysis-only mode)+- An LLM API key or authenticated Codex CLI (for documentation generation, not needed for analysis-only mode)### Verify Installation@@ -125,9 +125,9 @@ repowise initIn interactive mode, repowise asks you to choose:-- **Index-only** — free, no LLM. Parses code, builds dependency graph, indexes git history. Useful for analysis without documentation generation.-- **Full** — uses your chosen LLM to generate human-readable wiki pages for every file and module.-- **Advanced** — fine-tune every option (concurrency, exclusions, commit limits, etc.)+- **Index-only**, free, no LLM. Parses code, builds dependency graph, indexes git history. Useful for analysis without documentation generation.+- **Full**, uses your chosen LLM to generate human-readable wiki pages for every file and module.+- **Advanced**, fine-tune every option (concurrency, exclusions, commit limits, etc.)A typical first run on a medium codebase (~500 files) takes 5-15 minutes and costs $1-5 depending on the provider.@@ -170,10 +170,10 @@ repowise init [PATH]**What it does (4 phases):**-1. **Ingestion** — walks every file, parses AST with tree-sitter, builds a dependency graph, indexes git history (churn, hotspots, ownership, bus factor)-2. **Analysis** — detects dead code, extracts architectural decisions from inline markers, READMEs, and git history-3. **Generation** — sends structured prompts to the LLM, generates file-level, module-level, and repo-level wiki pages, plus architecture diagrams-4. **Persistence** — stores everything in `.repowise/wiki.db`, builds search indexes, generates managed editor instruction files+1. **Ingestion**, walks every file, parses AST with tree-sitter, builds a dependency graph, indexes git history (churn, hotspots, ownership, bus factor)+2. **Analysis**, detects dead code, extracts architectural decisions from inline markers, READMEs, and git history+3. **Generation**, sends structured prompts to the LLM, generates file-level, module-level, and repo-level wiki pages, plus architecture diagrams+4. **Persistence**, stores everything in `.repowise/wiki.db`, builds search indexes, generates managed editor instruction files**Options:**@@ -185,7 +185,7 @@ repowise init [PATH]| `--index-only` | Skip LLM generation entirely. Only parse, build graph, and index git. Free. || `--wiki-style` | Documentation voice: `comprehensive` (default), `caveman` (token-condensed), `reference` (API-manual), `tutorial`. Saved to config; switch later with `repowise restyle`. See [WIKI_STYLES.md](WIKI_STYLES.md). || `--dry-run` | Show generation plan and cost estimate without running anything. |-| `--test-run` | Generate docs for only the top 10 files (by PageRank) — quick validation. |+| `--test-run` | Generate docs for only the top 10 files (by PageRank), quick validation. || `--skip-tests` | Exclude test files from documentation generation. || `--skip-infra` | Exclude infrastructure files (Dockerfiles, Makefiles, Terraform, shell scripts). || `--exclude / -x` | Gitignore-style exclusion patterns. Repeatable: `-x vendor/ -x "*.generated.*"` |@@ -238,7 +238,7 @@ Incrementally update wiki pages for files that changed since the last sync.repowise update [PATH]```-Much faster and cheaper than a full `init` — only regenerates pages for changed files and their dependents.+Much faster and cheaper than a full `init`, only regenerates pages for changed files and their dependents.**How it works:**@@ -265,7 +265,7 @@ Much faster and cheaper than a full `init` — only regenerates pages for changeIf you first indexed a large repo with `repowise init --mode fast` (graph + essential git only, no LLM docs), `repowise update --full` upgrades it to a full index **without redoing the structural work**:-1. Backfills the git tier from *essential* to *full* — per-file blame and repo-wide co-change — via a resumable, checkpointed worker (re-run `--full` to resume if interrupted).+1. Backfills the git tier from *essential* to *full*, per-file blame and repo-wide co-change, via a resumable, checkpointed worker (re-run `--full` to resume if interrupted).2. Rehydrates the dependency graph straight from the database instead of re-parsing and re-resolving it, so imports/calls/heritage resolution and centrality are **not** recomputed.3. Generates the LLM documentation that fast mode skipped.@@ -317,7 +317,7 @@ Runs continuously. Uses filesystem events (via watchdog) to detect saves, deboun**Example:**```bash-# Start watching — wiki syncs as you code+# Start watching, wiki syncs as you coderepowise watch --debounce 3000```@@ -340,9 +340,9 @@ repowise search QUERY [PATH]**Search modes:**-- **fulltext** — SQLite FTS. Fast, exact keyword matching.-- **semantic** — Vector similarity search via LanceDB. Understands meaning ("how does auth work?" finds authentication code even without the word "auth"). Falls back to fulltext if vector store is unavailable.-- **symbol** — Searches the symbol index (function names, class names, etc.) with fuzzy matching.+- **fulltext**, SQLite FTS. Fast, exact keyword matching.+- **semantic**, Vector similarity search via LanceDB. Understands meaning ("how does auth work?" finds authentication code even without the word "auth"). Falls back to fulltext if vector store is unavailable.+- **symbol**, Searches the symbol index (function names, class names, etc.) with fuzzy matching.**Examples:**@@ -350,7 +350,7 @@ repowise search QUERY [PATH]# Keyword searchrepowise search "rate limiting"-# Semantic search — understands intent+# Semantic search, understands intentrepowise search "how are errors handled" --mode semantic# Find a symbol@@ -382,15 +382,15 @@ This is how you connect repowise to Claude Code, Cursor, Cline, Windsurf, and ot|------|-------------|| `get_overview` | Repository architecture summary, key modules, entry points, git health, community summary || `get_answer` | One-call RAG: confidence-gated synthesis over the wiki, with cited 2–5 sentence answers and a per-repository question cache |-| `get_context` | Complete context for files/modules/symbols — docs, ownership, decisions, freshness, community membership. Defaults to `compact=True`; pass `compact=False` for the full structure block and importer list. In workspace mode, accepts `repo` parameter. |+| `get_context` | Complete context for files/modules/symbols, docs, ownership, decisions, freshness, community membership. Defaults to `compact=True`; pass `compact=False` for the full structure block and importer list. In workspace mode, accepts `repo` parameter. || `get_symbol` | Raw source bytes for one indexed symbol with exact line bounds (cheaper/safer than `Read` + offset math) || `search_codebase` | Semantic search over wiki with git freshness boosting. In workspace mode, searches across all repos. |-| `get_risk` | Modification risk assessment — hotspot score, dependents, co-change partners, bus factor, blast radius, test gaps, 0–10 risk score |-| `get_why` | Why code is structured the way it is — architectural decisions, git archaeology. Three modes: NL search, path-based, health dashboard. |+| `get_risk` | Modification risk assessment, hotspot score, dependents, co-change partners, bus factor, blast radius, test gaps, 0–10 risk score |+| `get_why` | Why code is structured the way it is, architectural decisions, git archaeology. Three modes: NL search, path-based, health dashboard. || `get_dead_code` | Tiered dead code report grouped by confidence with cleanup impact estimates |-| `get_health` | 25-marker code-health scores — dashboard KPIs + lowest-scoring files, or per-file findings; `include` for refactoring suggestions and trend alerts |+| `get_health` | 25-marker code-health scores, dashboard KPIs + lowest-scoring files, or per-file findings; `include` for refactoring suggestions and trend alerts |-In workspace mode, tools are workspace-aware — pass `repo="backend"` to target a specific repo or `repo="all"` to query across the entire workspace. The default repo is used when `repo` is omitted.+In workspace mode, tools are workspace-aware, pass `repo="backend"` to target a specific repo or `repo="all"` to query across the entire workspace. The default repo is used when `repo` is omitted.See [MCP Integration](#mcp-integration-with-ai-editors) for setup instructions. Full tool reference: [MCP_TOOLS.md](MCP_TOOLS.md)@@ -520,7 +520,7 @@ Generate or update `CLAUDE.md` with codebase intelligence.repowise generate-claude-md [PATH]```-`CLAUDE.md` gives AI editors (Claude Code, Cursor, etc.) instant context about your codebase — architecture, key modules, hotspots, entry points, and conventions.+`CLAUDE.md` gives AI editors (Claude Code, Cursor, etc.) instant context about your codebase, architecture, key modules, hotspots, entry points, and conventions.If you have custom instructions at the top of your `CLAUDE.md`, they are preserved. Only the auto-generated section (between markers) is updated.@@ -608,7 +608,7 @@ Checks:- `state.json` valid- Providers installed and importable- Stale page count-- **CLI version** — best-effort check of your installed CLI against the latest+- **CLI version**, best-effort check of your installed CLI against the latestPyPI releaseThe CLI version row is advisory: when a newer release exists it prints the@@ -665,11 +665,11 @@ repowise hook uninstall # Remove the hookrepowise hook uninstall --workspace```-The hook is marker-delimited, so it coexists safely with other tools' hooks (linters, formatters, etc.) in the same `post-commit` file. The hook runs `repowise update` in the background — your terminal is never blocked.+The hook is marker-delimited, so it coexists safely with other tools' hooks (linters, formatters, etc.) in the same `post-commit` file. The hook runs `repowise update` in the background, your terminal is never blocked.----## Web UI+## Web DashboardRepowise includes a full web dashboard built with Next.js, React, and D3.js.@@ -719,10 +719,10 @@ Open **http://localhost:3000** for the Web UI, **http://localhost:7337** for theFor working on the frontend code with hot reload:```bash-# Terminal 1 — API only+# Terminal 1, API onlyrepowise serve --no-ui-# Terminal 2 — Frontend with hot reload+# Terminal 2, Frontend with hot reloadcd /path/to/repowisenpm installREPOWISE_API_URL=http://localhost:7337 npm run dev --workspace packages/web@@ -737,83 +737,42 @@ npm run dev --workspace packages/webOpen **http://localhost:3000** in your browser.-### Pages & Features+### Navigation-**Dashboard** (`/`)-Home page with aggregate stats (total pages, fresh/stale counts, dead code findings), a list of indexed repositories, and recent job status.+Two global pages sit outside any repo: **Dashboard** (`/`, lists indexed repos and recent job status) and **Settings** (`/settings`, API connection, default provider/model, embedder, webhook/MCP setup).-**Repository Overview** (`/repos/[id]/overview`)-A single-page dashboard for each repository that aggregates key health signals. Includes:-- **Health score ring** — composite score (0–100) computed from documentation coverage, freshness, dead code ratio, hotspot density, and ownership silo risk-- **Attention panel** — prioritized list of items needing action (stale docs, high-churn hotspots, dead code findings)-- **Language donut** — breakdown of codebase by programming language-- **Ownership treemap** — visualizes code ownership distribution across modules-- **Hotspots mini** — top high-churn files at a glance-- **Decisions timeline** — recent architectural decisions-- **Module minimap** — compact interactive graph of module relationships-- **Quick actions** — one-click buttons for sync, full re-index, CLAUDE.md generation, and export-- **Active job banner** — shows progress of running pipeline jobs with live polling+Everything else lives under a repo: `/repos/{id}/...`. The sidebar groups repo pages like this:-The overview page degrades gracefully — each data section loads independently, so partial data (e.g., missing git metadata) still renders a useful dashboard. A "Graph Intelligence" section at the bottom of the overview shows an expandable list of architectural communities (with labels, cohesion scores, and member counts) and an execution flows panel listing the top entry points with their call-path traces.+| Page | Route | What it's for |+|------|-------|----------------|+| Overview | `/overview` | Repo health dashboard: aggregate score, attention panel (what needs action), hotspots, decisions timeline, community graph |+| Docs | `/docs` | Wiki browser: AI-generated documentation for every file and module, with an Explorer tab and a Coverage/freshness tab |+| Architecture | `/architecture` | One page, five tabs: Communities (default), Explore (full dependency graph with dead-code/hotspot overlays), Coupling (change-coupling graph), Dependencies (declared third-party deps), Symbols (functions, classes, exports) |+| Knowledge Graph | `/knowledge-graph` | The curated, layered architecture view (guided tour, personas, drill-down from system to module to file) |+| Code Health | `/code-health` | One page, seven tabs: Triage (default), Findings, Hotspots & churn, Coverage, Dead code, Impact (blast radius), Security |+| Refactoring | `/refactoring` | Ranked refactoring plan cards, with copy-to-agent export |+| Files | `/files` | Browsable file tree |+| Commits / Contributors / Decisions | `/commits`, `/owners`, `/decisions` | Grouped under "People & History": git activity, ownership/bus-factor risk, and architectural decisions |+| Chat | `/chat` | Natural-language Q&A over the codebase, using the same MCP tools as editor integrations |+| Stats / Usage & savings / Settings | `/stats`, `/costs`, `/settings` | Grouped under repo Settings: "by the numbers" stats, distill/LLM cost tracking, per-repo config |-**Wiki Browser** (`/repos/[id]/wiki/...`)-The heart of repowise. Browse AI-generated documentation for every file and module. Each page includes:-- Rendered markdown with syntax-highlighted code blocks and Mermaid diagrams-- Sticky table of contents-- Freshness badge (fresh / stale / outdated)-- Git history sidebar — commits, churn percentile, top authors, co-change partners, hotspot indicator-- Regenerate button for stale pages-- "Graph Intelligence" section in the right sidebar showing PageRank and betweenness percentile bars, community label, and in/out degree counts+A global command palette (`Ctrl+K` / `Cmd+K`, available on every page) is the fastest way to jump between pages or repos; it replaced the old standalone Search page.-**Dependency Graph** (`/repos/[id]/graph`)-Interactive force-directed graph rendered on HTML Canvas with D3.js. Handles 2000+ nodes. Six view modes:-- **Module view** — hierarchical organization-- **Ego graph** — neighborhood of a selected node-- **Architecture view** — entry point reachability-- **Dead code view** — highlights unreachable files-- **Hot files view** — commit activity heatmap-- **Full graph** — everything+Older top-level routes (`/risk`, `/hotspots`, `/security`, `/health`, `/coverage`, `/graph`, `/c4`, `/coupling`, `/ownership`, `/blast-radius`) still resolve and redirect into the tabs above, but don't link to them directly; use the tabbed pages instead.-Supports pan, zoom, click-to-inspect, path finding between nodes, filtering by language, and PNG export. Community color mode uses real community labels (derived from Leiden detection) in the legend rather than generic placeholders. Clicking a node in community color mode opens a community detail panel showing members, cohesion score, and neighboring communities. The active color mode is preserved as a URL parameter so links can be shared.+**Index-only repos:** the dashboard itself isn't gated by mode. Views that depend on the generated wiki (Docs, Chat, and parts of Overview) just show empty or thin content if you ran `repowise init --index-only`; everything else (Architecture, Code Health, Files, Commits, Contributors) works off the parsed graph and git history alone.-**Search** (`/repos/[id]/search`)-Full-text and semantic search with result cards showing snippets, confidence scores, and links. A global command palette (`Ctrl+K` / `Cmd+K`) is accessible from any page for quick navigation.+### Workspace mode-**Symbol Index** (`/repos/[id]/symbols`)-Searchable, sortable table of every extracted symbol (functions, classes, methods, interfaces). Click any row to open the symbol drawer, which now includes a right panel showing graph metrics (PageRank and betweenness percentile bars), callers and callees with confidence scores, and heritage relationships (extends/implements) for classes.+In a multi-repo workspace, a collapsible **Workspace** nav section appears above the per-repo pages:-**Documentation Coverage** (`/repos/[id]/coverage`)-Donut chart and table showing freshness breakdown. Regenerate stale pages directly from the UI.--**Code Ownership** (`/repos/[id]/ownership`)-Contributor attribution by module or file. Highlights knowledge silos (bus factor risk) where one person owns >80% of a module.--**Hotspots** (`/repos/[id]/hotspots`)-Ranked table of high-churn files with commit counts, churn percentile bars, and owner attribution.--**Dead Code** (`/repos/[id]/dead-code`)-Findings grouped by category (unreachable files, unused exports, zombie packages) with confidence scores, line counts, and safe-to-delete badges. Bulk operations for resolving or acknowledging findings.--**Architectural Decisions** (`/repos/[id]/decisions`)-Browse and manage extracted decisions. View full rationale, affected files, health score, and status.--**Codebase Chat** (`/repos/[id]/chat`)-Ask questions about your codebase in natural language. Streaming responses powered by your configured LLM with real-time tool call visualization. The chat uses the same MCP tools as editor integrations.--**Settings** (`/settings`)-Configure API connection, default provider/model, embedder, and view webhook/MCP setup instructions.--**Workspace Dashboard** (`/workspace`) *(workspace mode only)*-Aggregate stats across all repos, repo cards with file/symbol/coverage counts, and cross-repo intelligence summary.--**Workspace System Map** (`/workspace/system-map`) *(workspace mode only)*-A code-derived diagram of your services and their typed relationships (HTTP, gRPC, events, package deps, co-change), health-colored, with edge-kind filters, a service-to-repo collapse toggle, and click-through drill-down to the underlying contracts.--**Workspace Contracts** (`/workspace/contracts`) *(workspace mode only)*-All detected API contracts (HTTP, gRPC, message topics) with provider/consumer matching, filterable by type and repo.--**Workspace Co-Changes** (`/workspace/co-changes`) *(workspace mode only)*-Cross-repo file pairs ranked by co-change strength.+| Page | Route | What it's for |+|------|-------|----------------|+| Overview | `/workspace` | Aggregate stats across all repos |+| System Map | `/workspace/system-map` | Code-derived service diagram (HTTP, gRPC, events, package deps, co-change), health-colored, with drill-down into contracts |+| Conformance | `/workspace/conformance` | Dependency-cycle detection and a dependency structure matrix (DSM) |+| Contracts | `/workspace/contracts` | Detected API contracts (HTTP, gRPC, message topics) with provider/consumer matching |+| Co-Changes | `/workspace/co-changes` | Cross-repo file pairs ranked by co-change strength |---@@ -880,7 +839,7 @@ Unlike MCP tools, hooks are passive reminders that fire from editor lifecycle ev### How it works-#### Claude Code PostToolUse Hook — Grep/Glob enrichment+#### Claude Code PostToolUse Hook, Grep/Glob enrichmentWhen Claude Code runs a broad or zero-result `Grep` or `Glob`, repowise can query the local `wiki.db` and append focused context:@@ -891,14 +850,14 @@ When Claude Code runs a broad or zero-result `Grep` or `Glob`, repowise can quer| **Depends on** | What this file imports (forward dependency) || **Git signals** | Hotspot status, bus factor, and owner |-No LLM calls, no network requests — pure local SQLite queries against `wiki.db`.+No LLM calls, no network requests, pure local SQLite queries against `wiki.db`.-#### PostToolUse Hook — Git/edit freshness detection+#### PostToolUse Hook, Git/edit freshness detectionAfter a successful `git commit`, `git merge`, `git rebase`, `git cherry-pick`, or `git pull`, repowise checks whether the wiki is stale by comparing `HEAD` against the last indexed commit in `.repowise/state.json`. Codex edit hooks also remind the agent that indexed context may be stale after edits.```-Wiki is stale — run `repowise update` to refresh+Wiki is stale, run `repowise update` to refresh```This ensures agents are never silently working from outdated documentation.@@ -913,12 +872,12 @@ Claude Code hooks are written to `~/.claude/settings.json` automatically during| Codex `SessionStart` / `UserPromptSubmit` | lifecycle | Remind Codex to use Repowise MCP tools || Codex `PostToolUse` | `Bash`, `apply_patch\|Edit\|Write` | Check git/edit freshness |-Both hooks call the `repowise-augment` console script — a standalone, import-isolated entry point that does not load the full `repowise` CLI. This keeps cold start under the 500ms target and ensures a broken environment (missing optional dep, corrupt DB, etc.) never crashes the agent: any failure exits 0 silently. The equivalent `repowise augment` Click subcommand still exists for manual debugging.+Both hooks call the `repowise-augment` console script, a standalone, import-isolated entry point that does not load the full `repowise` CLI. This keeps cold start under the 500ms target and ensures a broken environment (missing optional dep, corrupt DB, etc.) never crashes the agent: any failure exits 0 silently. The equivalent `repowise augment` Click subcommand still exists for manual debugging.### CLI command```bash-repowise-augment # Not meant to be called manually — invoked by AI-agent hooks+repowise-augment # Not meant to be called manually, invoked by AI-agent hooksrepowise augment # Equivalent Click subcommand, useful for manual debugging```@@ -941,14 +900,14 @@ When an agent runs `Grep` or `Glob`, it sees its normal results followed by contDepends on: update_cmd.py, cost_estimator.py```-This means an agent that searches for `"PageGenerator"` immediately knows which files depend on it, what it depends on, and that it is a hotspot — without making a separate MCP tool call.+This means an agent that searches for `"PageGenerator"` immediately knows which files depend on it, what it depends on, and that it is a hotspot, without making a separate MCP tool call.### Relationship to MCP toolsHooks and MCP tools are complementary:-- **Hooks** — passive, automatic, zero agent effort. Fire on every search regardless of whether the agent is thinking about graph context.-- **MCP tools** — active, on-demand, richer output. Used when the agent needs full documentation, risk assessment, architectural decisions, or dependency tracing.+- **Hooks**, passive, automatic, zero agent effort. Fire on every search regardless of whether the agent is thinking about graph context.+- **MCP tools**, active, on-demand, richer output. Used when the agent needs full documentation, risk assessment, architectural decisions, or dependency tracing.For most day-to-day coding tasks, hooks provide sufficient context automatically. MCP tools remain the right choice for deeper investigation.@@ -956,7 +915,7 @@ For most day-to-day coding tasks, hooks provide sufficient context automatically## Output Distillation (Distill)-Most of an agent's context is spent on command output it never needed — 300+Most of an agent's context is spent on command output it never needed, 300lines of passing tests to find 4 failures, a full `git log` for "what changedrecently". Distill compresses noisy output **before the agent reads it**,errors-first and fully reversible. Full guide: [DISTILL.md](DISTILL.md).@@ -982,7 +941,7 @@ repowise expand a1b2c3d4e5f6 -q "FAILED" # just the matching lines**Make your agent use it.** Two complementary ways:1. `repowise init` adds an "Output Distillation" section to the managed- `CLAUDE.md`, so the agent prefers `repowise distill <cmd>` voluntarily —+ `CLAUDE.md`, so the agent prefers `repowise distill <cmd>` voluntarily -works in any agent that runs shell commands.2. Opt into the **command-rewrite hook** (Claude Code): noisy commands arerewritten to `repowise distill <cmd>` automatically, pending your approval.@@ -997,7 +956,7 @@ to `ask` so you see every rewritten command. Per-repo behavior lives under**Skeletons for large files.** For structure-level questions about an indexedfile, `get_context(["path"], include=["skeleton"])` returns every signature-plus the bodies of only the most central symbols — typically ~15% of the full+plus the bodies of only the most central symbols, typically ~15% of the fullfile's tokens. After a large `Read`, the PostToolUse hook nudges the agentwith the skeleton's cost once per file per session.@@ -1009,7 +968,7 @@ repowise saved --by day```The Costs page in the web UI shows the same numbers on its *Cache & savings*-tab. The ledger covers the distill command/hook path only — MCP response+tab. The ledger covers the distill command/hook path only, MCP responsetruncation is not counted.---@@ -1093,7 +1052,7 @@ repowise updaterepowise watch# Option C: Set-and-forget (if hook installed)-# Just code and commit — the hook handles it+# Just code and commit, the hook handles it```### Before a code review@@ -1154,7 +1113,7 @@ Install the optional dependency: `pip install "repowise[anthropic]"` (or openai,Check that an embedder is configured. Run `repowise reindex --embedder gemini` to rebuild the vector store.**"embedder.mock_active" warning**-Set `REPOWISE_EMBEDDER=gemini` (or `openai`) for real vector search. Mock embedder produces random vectors — semantic search won't work meaningfully.+Set `REPOWISE_EMBEDDER=gemini` (or `openai`) for real vector search. Mock embedder produces random vectors, semantic search won't work meaningfully.**Stale pages after code changes**Run `repowise update` to sync. Or use `repowise watch` for automatic syncing.diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.mdindex c43b10e11..da4d8ecb9 100644--- a/docs/WORKSPACES.md+++ b/docs/WORKSPACES.md@@ -1,4 +1,4 @@-# Workspaces — Multi-Repo Support+# Workspaces, Multi-Repo SupportRepowise workspaces let you index and analyze multiple repositories together. You get per-repo documentation, graphs, and search, plus cross-repo intelligence: co-change detection, API contract extraction, and package dependency mapping.@@ -28,7 +28,7 @@ Use a workspace when your project spans multiple git repositories that are relat- **Microservices** that communicate over HTTP, gRPC, or message topics- Any set of repos where you want to understand **cross-repo dependencies and co-change patterns**-If you only have a single repo, `repowise init` works as before — no workspace needed.+If you only have a single repo, `repowise init` works as before, no workspace needed.---@@ -67,9 +67,9 @@ Repowise will:2. **Prompt you to select** which repos to index3. **Ask you to pick a primary repo** (the default for MCP queries)4. **Walk you through provider setup** (LLM provider, model, cost estimate)-5. **Index each repo** — parse files, build graphs, index git history+5. **Index each repo**, parse files, build graphs, index git history6. **Generate documentation** for each repo (unless `--index-only`)-7. **Run cross-repo analysis** — co-changes, API contracts, package deps+7. **Run cross-repo analysis**, co-changes, API contracts, package deps8. **Register MCP servers** with Claude Desktop and Claude Code### 3. Explore@@ -94,7 +94,7 @@ repowise search "authentication flow"A workspace is a directory containing multiple git repositories, tied together by a config file (`.repowise-workspace.yaml`) and a shared data directory (`.repowise-workspace/`).-Each repo is indexed independently into its own `.repowise/wiki.db` — the same format as single-repo mode. The workspace layer adds cross-repo analysis on top.+Each repo is indexed independently into its own `.repowise/wiki.db`, the same format as single-repo mode. The workspace layer adds cross-repo analysis on top.### Single-Repo vs Workspace@@ -172,7 +172,7 @@ repowise workspace set-default backend### `repowise workspace diagnostics`-Explain the cross-repo contract link count — per-repo provider/consumer counts, unmatched consumers grouped by reason, and orphan providers. See [Extraction Diagnostics](#extraction-diagnostics).+Explain the cross-repo contract link count, per-repo provider/consumer counts, unmatched consumers grouped by reason, and orphan providers. See [Extraction Diagnostics](#extraction-diagnostics).```bashrepowise workspace diagnostics # human-readable report@@ -221,9 +221,12 @@ Scans source files for HTTP route handlers, gRPC service definitions, and messag| Type | Providers | Consumers ||------|-----------|-----------|-| HTTP | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi) | fetch, axios, requests, httpx |-| gRPC | `.proto` service definitions | gRPC client stubs |-| Topics | Kafka, RabbitMQ, Redis Pub/Sub, NATS producers | Corresponding consumers |+| HTTP | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal API), Rust (Axum routes, Actix/Rocket attribute macros) | fetch/axios/URL-literal wrappers (JS/TS), requests/httpx (Python), HttpClient/UnityWebRequest/Best.HTTP (C#), reqwest (Rust) |+| gRPC | `.proto` service definitions, plus per-language dialects (Go, Java, Python, C#, TypeScript, NestJS `@GrpcMethod`) | gRPC client stubs |+| Data / DB | DDL (`CREATE TABLE`/`VIEW`/`MATERIALIZED VIEW`), ORM dialects (SQLAlchemy, Django, JPA, EF Core, ActiveRecord, Eloquent) | Raw SQL string literals in app code (verb-anchored: `SELECT`/`INSERT`/`UPDATE`/`DELETE`/`MERGE`) |+| Topics | Kafka, RabbitMQ, NATS producers | Corresponding consumers |++Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](#system-graph). The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.HTTP routes are matched on their **full** path: a router mount prefix(`APIRouter(prefix=...)`, `include_router(prefix=...)`, Express `app.use('/x', router)`,@@ -236,6 +239,10 @@ provides that path and a lower-confidence **candidate** when the target is ambig```yamlcontracts:+ detect_http: true+ detect_grpc: true+ detect_topics: true+ detect_data: true# Map a consumer base token or absolute host to the repo it targets, so a# call whose base is unresolved at parse time links as an exact match.service_bases:@@ -246,10 +253,13 @@ contracts:- "generated/**"```-Files under test trees (`tests/`, `test/`, `__tests__/`, `spec/`, `e2e/`) and test-files (`test_*.py`, `*.test.ts`, `*.spec.ts`, ...) are excluded by default: a route-or topic that exists only in a test is a fixture, not a service contract. Calls to a-literal third-party host (Stripe, Formspree, ...) that is not a workspace service are+Directories named `tests/`, `__tests__/`, and `__mocks__/` are excluded by name;+`test/`, `spec/`, and `e2e/` are deliberately *not* excluded by directory, since those+names double as legitimate product directories in some codebases. Regardless of+directory, filenames matching `test_*.py`, `*_test.py`, `*_test.go`, `*.test.*`,+`*.spec.*`, `*.e2e.*`, or `conftest.py` are always excluded: a route or topic that+exists only in a test is a fixture, not a service contract. Calls to a literal+third-party host (Stripe, Formspree, ...) that is not a workspace service areexcluded from matching and reported under the `external_host` diagnostics reason.### Package Dependency Scanning@@ -260,24 +270,24 @@ Reads package manifests (`package.json`, `pyproject.toml`, `go.mod`, `pom.xml`,## System Graph-The contracts, package dependencies, and co-changes above are each a flat list. repowise folds them into a single normalized **system graph** — the one structure every cross-repo view reads. It is rebuilt automatically on every `repowise update --workspace` and persisted to `.repowise-workspace/system_graph.json`.+The contracts, package dependencies, and co-changes above are each a flat list. repowise folds them into a single normalized **system graph**, the one structure every cross-repo view reads. It is rebuilt automatically on every `repowise update --workspace` and persisted to `.repowise-workspace/system_graph.json`.**Nodes are services, not repos.** A monorepo with three detected service boundaries (a `package.json` / `go.mod` / `Cargo.toml` sub-directory) shows three nodes; the repo is a grouping attribute on each node. A repo with no sub-boundary collapses to a single repo-root node. Each node carries its provider/consumer counts, the contract types it participates in, and flags for orphan/isolated services.**Edges are typed and honest.** Every edge carries:-- a `kind` — `http`, `grpc`, `event`, `package`, or `co_change`;-- a `match_type` — `exact`, `candidate`, `manual`, or `inferred`;+- a `kind`, `http`, `grpc`, `event`, `package`, `co_change`, or `db`;+- a `match_type`, `exact`, `candidate`, `manual`, or `inferred`;- a `confidence` and a `weight` (how many underlying contracts / deps / co-changes it aggregates);- `contract_refs` back-pointers so any view can drill from an edge to its evidence.-Edge direction is uniform: **`source` depends on / calls `target`.** A consumer points to the provider it calls; a dependent repo points to the repo it imports. Structural edges (contracts, package deps) are flagged distinctly from behavioral co-change edges — repowise never conflates "these change together" with "these call each other".+Edge direction is uniform: **`source` depends on / calls `target`.** A consumer points to the provider it calls; a dependent repo points to the repo it imports. Structural edges (contracts, package deps) are flagged distinctly from behavioral co-change edges, repowise never conflates "these change together" with "these call each other".Fetch it over REST with `GET /api/workspace/system-graph`, or explore it visually in the [Live System Map](#live-system-map).## Extraction Diagnostics-When the cross-repo link count looks low, diagnostics explain why. Computed alongside contract matching, they report — per repo and contract type — how many providers and consumers were found, which consumers went unmatched (and why), and which providers have no consumer at all.+When the cross-repo link count looks low, diagnostics explain why. Computed alongside contract matching, they report, per repo and contract type, how many providers and consumers were found, which consumers went unmatched (and why), and which providers have no consumer at all.```bashrepowise workspace diagnostics # human-readable report@@ -289,12 +299,12 @@ The report covers:- **Provider / consumer counts** per repo, broken down by contract type.- **Unmatched consumers**, grouped by reason:- - `no_provider` — no provider anywhere declares a matching route/service/topic.- - `internal_only` — the only matching provider is in the same repo + service, so the call is intra-service and intentionally not surfaced as a cross-repo link.- - `unlinked` — a cross-service provider with a matching id exists, but no link formed (a candidate worth inspecting).- - `external_host` — the call targets a literal third-party host (Stripe, Formspree, ...) that is not a workspace service, so it is intentionally excluded from matching.-- **Orphan providers** — endpoints declared but never consumed by any repo.-- **Weak links** — matched links below the confidence threshold.+ - `no_provider`, no provider anywhere declares a matching route/service/topic.+ - `internal_only`, the only matching provider is in the same repo + service, so the call is intra-service and intentionally not surfaced as a cross-repo link.+ - `unlinked`, a cross-service provider with a matching id exists, but no link formed (a candidate worth inspecting).+ - `external_host`, the call targets a literal third-party host (Stripe, Formspree, ...) that is not a workspace service, so it is intentionally excluded from matching.+- **Orphan providers**, endpoints declared but never consumed by any repo.+- **Weak links**, matched links below the confidence threshold.The same data is available over REST at `GET /api/workspace/diagnostics` and is embedded in the system graph artifact's `diagnostics` block.@@ -310,16 +320,16 @@ repowise serveIn workspace mode, the web UI adds:-- **Workspace Dashboard** (`/workspace`) — aggregate stats across all repos, repo cards with file/symbol/coverage counts, and cross-repo intelligence summary-- **System Map** (`/workspace/system-map`) — the [Live System Map](#live-system-map): a code-derived diagram of services and their typed relationships-- **Contracts View** (`/workspace/contracts`) — all detected API contracts with provider/consumer matching, filterable by type and repo-- **Co-Changes View** (`/workspace/co-changes`) — cross-repo file pairs ranked by co-change strength+- **Workspace Dashboard** (`/workspace`), aggregate stats across all repos, repo cards with file/symbol/coverage counts, and cross-repo intelligence summary+- **System Map** (`/workspace/system-map`), the [Live System Map](#live-system-map): a code-derived diagram of services and their typed relationships+- **Contracts View** (`/workspace/contracts`), all detected API contracts with provider/consumer matching, filterable by type and repo+- **Co-Changes View** (`/workspace/co-changes`), cross-repo file pairs ranked by co-change strengthThe sidebar shows all workspace repos under **Repositories**. Click any repo to access its full per-repo pages (overview, docs, graph, search, hotspots, etc.).### Live System Map-The System Map renders the [system graph](#system-graph) as an always-current diagram. It is the visual counterpart to the REST endpoint — the same nodes and edges, laid out and explorable, never a hand-drawn picture.+The System Map renders the [system graph](#system-graph) as an always-current diagram. It is the visual counterpart to the REST endpoint, the same nodes and edges, laid out and explorable, never a hand-drawn picture.- **Service nodes**, coloured by category (service, frontend, worker, library, external), with a health ring rolled up from the owning repo and small flags for orphan or isolated services.- **Typed edges** distinguished by `kind` (colour + glyph) and by `match_type` (solid for exact/manual, dashed for candidate, dotted for inferred co-change). Behavioral co-change edges read differently from structural contract/dependency edges.@@ -333,20 +343,20 @@ The map appears once the workspace has at least two indexed repositories with de## Cross-Repo Blast Radius-Blast radius answers a single question: **if I change this service, what downstream services and repos break?** It walks the [system graph](#system-graph) *against* its edge direction — a `consumer → provider` edge means changing the provider impacts the consumer — and returns every reachable service ranked by an impact score.+Blast radius answers a single question: **if I change this service, what downstream services and repos break?** It walks the [system graph](#system-graph) *against* its edge direction, a `consumer → provider` edge means changing the provider impacts the consumer, and returns every reachable service ranked by an impact score.Two edge classes are weighted and labelled distinctly:-- **Structural** edges (http / grpc / event / package) assert a real dependency — a contract or an import. They propagate impact at full weight and surface as **will break**.+- **Structural** edges (http / grpc / event / package / db) assert a real dependency, a contract or an import. They propagate impact at full weight and surface as **will break**.- **Behavioral** co-change edges only assert that two files historically *changed together*. They are correlation, not a call, so they propagate at half weight (one named constant, `BEHAVIORAL_EDGE_WEIGHT`) and surface as **may drift**.Each impacted service carries its `distance` (hops from the change) and `score` (0-1, with distance decay and the behavioral weighting baked in). Nearer, structural impact ranks highest.Use it three ways:-- **REST** — `GET /api/workspace/blast-radius?target=<node-id-or-repo>&max_depth=3&include_behavioral=true`. `target` is a node id (`repo` or `repo::service/path`) or a repo alias (expands to all its services).-- **MCP** — the `get_blast_radius` tool (workspace mode) gives an agent the impacted set before it touches a high-fan-out provider. The `get_risk` PR-mode directive also gains `will_break_consumers` and `missing_cross_repo_cochanges` so a diff in one repo flags its cross-repo fallout.-- **System Map** — pick a service in the **Blast radius** control above the map; the reachable set ripples (highlighted, the rest dimmed, badges grading intensity), and a side panel lists the impacted services. Click any impacted service to walk the impact outward from there.+- **REST**, `GET /api/workspace/blast-radius?target=<node-id-or-repo>&max_depth=3&include_behavioral=true`. `target` is a node id (`repo` or `repo::service/path`) or a repo alias (expands to all its services).+- **MCP**, the `get_blast_radius` tool (workspace mode) gives an agent the impacted set before it touches a high-fan-out provider. The `get_risk` PR-mode directive also gains `will_break_consumers` and `missing_cross_repo_cochanges` so a diff in one repo flags its cross-repo fallout.+- **System Map**, pick a service in the **Blast radius** control above the map; the reachable set ripples (highlighted, the rest dimmed, badges grading intensity), and a side panel lists the impacted services. Click any impacted service to walk the impact outward from there.---@@ -354,7 +364,7 @@ Use it three ways:Where blast radius answers *what could be affected*, the breaking-change guard answers a sharper question: **did a provider change in a way that actually breaks its consumers?** On every `repowise update --workspace`, the freshly-extracted contracts are diffed against the previously-indexed set and each incompatible provider change is reported with the exact consumer files that call it.-Detected change kinds (a registry — adding a kind is one new rule, never an `if/elif`):+Detected change kinds (a registry, adding a kind is one new rule, never an `if/elif`):| Kind | Severity | Fires when ||------|----------|-----------|@@ -364,15 +374,15 @@ Detected change kinds (a registry — adding a kind is one new rule, never an `i| `field_number_changed` | breaking | A proto field's wire number changed || `field_required` | breaking | A field became required, or a new required field was added |-**Non-breaking changes never flag** — an added *optional* field, a widened set, or a brand-new endpoint produces no record. Field-level diffs need a contract *schema*; today gRPC carries one (proto message fields, recovered by the existing proto parser), and HTTP gains field-level checks when an OpenAPI spec is present. Route-level removal is detected for every transport from the contract id alone.+**Non-breaking changes never flag**, an added *optional* field, a widened set, or a brand-new endpoint produces no record. Field-level diffs need a contract *schema*; today gRPC carries one (proto message fields, recovered by the existing proto parser), and HTTP gains field-level checks when an OpenAPI spec is present. Route-level removal is detected for every transport from the contract id alone.-Impacted consumers are resolved from the matched contract links — the same provider↔consumer evidence the [system graph](#system-graph)'s edges are built from — so impact is endpoint-precise (the consumer file that calls the changed contract) and direct (the first reachability hop, which is exactly what a contract break endangers; transitive ripple stays the job of blast radius).+Impacted consumers are resolved from the matched contract links, the same provider↔consumer evidence the [system graph](#system-graph)'s edges are built from, so impact is endpoint-precise (the consumer file that calls the changed contract) and direct (the first reachability hop, which is exactly what a contract break endangers; transitive ripple stays the job of blast radius).Use it three ways:-- **REST** — `GET /api/workspace/breaking-changes` returns the report from the most recent update (filterable by `repo` or `severity`). Each change carries its provider, detail, and impacted consumers with both code sides.-- **MCP** — the `get_risk` PR-mode directive gains a `breaking_changes` block listing the provider contracts that changed incompatibly in the diff's repo and the consumers they endanger, across repos.-- **System Map** — toggle **Breaking changes** above the map: changed providers are badged with their breaking count, the consumers they endanger are badged *at risk*, and the seams between them are highlighted (additive overlay — the map stays whole). A side panel lists each change with both the provider and consumer files.+- **REST**, `GET /api/workspace/breaking-changes` returns the report from the most recent update (filterable by `repo` or `severity`). Each change carries its provider, detail, and impacted consumers with both code sides.+- **MCP**, the `get_risk` PR-mode directive gains a `breaking_changes` block listing the provider contracts that changed incompatibly in the diff's repo and the consumers they endanger, across repos.+- **System Map**, toggle **Breaking changes** above the map: changed providers are badged with their breaking count, the consumers they endanger are badged *at risk*, and the seams between them are highlighted (additive overlay, the map stays whole). A side panel lists each change with both the provider and consumer files.---@@ -426,7 +436,7 @@ Independently of any rules, conformance detects **circular dependencies** among### Using it-- **CLI** — `repowise workspace check` prints violations and cycles and exits non-zero when any are found, so it gates CI (the architecture lint):+- **CLI**, `repowise workspace check` prints violations and cycles and exits non-zero when any are found, so it gates CI (the architecture lint):```bashrepowise workspace check # human-readable report; exit 1 on findings@@ -434,40 +444,40 @@ Independently of any rules, conformance detects **circular dependencies** among```It recomputes from the persisted system graph, so editing rules and re-running picks them up without a full re-index.-- **REST** — `GET /api/workspace/conformance` returns the report from the most recent update (filterable by `repo`).-- **MCP** — `get_conformance` exposes violations and cycles to an agent; the `get_risk` PR-mode directive gains `conformance_violations` and `dependency_cycles` blocks for the findings the diff's repo participates in.-- **Conformance view** — the web UI's Conformance page renders a **dependency-structure matrix (DSM)**: services on both axes, each filled cell a dependency tinted by transport, with rule violations ringed red and cycle cells amber. Governance panels list the violations and cycles. Violations also badge the offending edges on the [Live System Map](#live-system-map) (toggle **Conformance**), reusing the same additive overlay as the breaking-change guard.+- **REST**, `GET /api/workspace/conformance` returns the report from the most recent update (filterable by `repo`).+- **MCP**, `get_conformance` exposes violations and cycles to an agent; the `get_risk` PR-mode directive gains `conformance_violations` and `dependency_cycles` blocks for the findings the diff's repo participates in.+- **Conformance view**, the web UI's Conformance page renders a **dependency-structure matrix (DSM)**: services on both axes, each filled cell a dependency tinted by transport, with rule violations ringed red and cycle cells amber. Governance panels list the violations and cycles. Violations also badge the offending edges on the [Live System Map](#live-system-map) (toggle **Conformance**), reusing the same additive overlay as the breaking-change guard.---## Architecture Metrics-Conformance and the cycle finder answer *per-relationship* questions (is this edge allowed, is this loop a cycle). Architecture metrics give the one *evaluative* read of the whole system: how coupled it is, where its architectural core is, and a single score you can track over time and compare across workspaces. These are the standard MacCormack / Baldwin / Sturtevant architecture-complexity metrics, computed deterministically over the system graph — no LLM. They use **structural edges only** (http / grpc / event / package / db); co-change is excluded.+Conformance and the cycle finder answer *per-relationship* questions (is this edge allowed, is this loop a cycle). Architecture metrics give the one *evaluative* read of the whole system: how coupled it is, where its architectural core is, and a single score you can track over time and compare across workspaces. These are the standard MacCormack / Baldwin / Sturtevant architecture-complexity metrics, computed deterministically over the system graph, no LLM. They use **structural edges only** (http / grpc / event / package / db); co-change is excluded.### What it computes-- **Propagation cost** — the share of *other* services the average service can reach transitively through dependencies (0% = fully decoupled, 100% = everything reaches everything). The headline coupling number; lower is better.-- **Cyclic core** — the largest cyclic group of services (the largest strongly-connected component of the structural graph). Its size and ratio (core / services) describe how much of the system is tangled together.-- **Architecture type** — `core-periphery` when the core spans a meaningful fraction of the system, else `hierarchical`.-- **Per-service role** — each service is classified from its visibility profile:- - **Core** — in the largest cyclic group (the architectural center).- - **Shared** — high visibility fan-in, low fan-out: many services depend on it, it depends on few (a widely-used utility/library).- - **Control** — high fan-out, low fan-in: it depends on many, few depend on it (an orchestrator / entry point).- - **Peripheral** — lightly coupled in both directions.-- **Architecture score** — a deterministic 1-10 roll-up (matching the Code Health 1-10 convention) from propagation cost, core ratio, dependency-cycle count, and declared-rule violation count. Lower coupling and a smaller core score higher.+- **Propagation cost**, the share of *other* services the average service can reach transitively through dependencies (0% = fully decoupled, 100% = everything reaches everything). The headline coupling number; lower is better.+- **Cyclic core**, the largest cyclic group of services (the largest strongly-connected component of the structural graph). Its size and ratio (core / services) describe how much of the system is tangled together.+- **Architecture type**, `core-periphery` when the core spans a meaningful fraction of the system, else `hierarchical`.+- **Per-service role**, each service is classified from its visibility profile:+ - **Core**, in the largest cyclic group (the architectural center).+ - **Shared**, high visibility fan-in, low fan-out: many services depend on it, it depends on few (a widely-used utility/library).+ - **Control**, high fan-out, low fan-in: it depends on many, few depend on it (an orchestrator / entry point).+ - **Peripheral**, lightly coupled in both directions.+- **Architecture score**, a deterministic 1-10 roll-up (matching the Code Health 1-10 convention) from propagation cost, core ratio, dependency-cycle count, and declared-rule violation count. Lower coupling and a smaller core score higher.### Using it-- **CLI** — `repowise workspace metrics` prints the score, propagation cost, cyclic core, dependency-cycle count, and the per-role service breakdown. CI-friendly plain output; `--json` emits the raw metrics.+- **CLI**, `repowise workspace metrics` prints the score, propagation cost, cyclic core, dependency-cycle count, and the per-role service breakdown. CI-friendly plain output; `--json` emits the raw metrics.```bashrepowise workspace metrics # human-readable summaryrepowise workspace metrics --json # raw metrics JSON```-- **REST** — `GET /api/workspace/architecture` returns the workspace metrics plus the per-service roles. Computed at request time from the system graph (no separate artifact); the conformance violation count, if a report exists, is folded into the score.-- **MCP** — `get_architecture` gives an agent the score, propagation cost, core members, and role breakdown in one call — the system-structure read to consult before a cross-service refactor.-- **Web** — the **architecture score** appears as a stat on both the Conformance and System Map pages. The DSM header shows score / propagation cost / core size and tints each service's diagonal cell by its role, so the on-diagonal core block stands out. On the Live System Map, toggle **Core** to highlight the cyclic core, and the inspector shows any selected service's role and visibility profile.+- **REST**, `GET /api/workspace/architecture` returns the workspace metrics plus the per-service roles. Computed at request time from the system graph (no separate artifact); the conformance violation count, if a report exists, is folded into the score.+- **MCP**, `get_architecture` gives an agent the score, propagation cost, core members, and role breakdown in one call, the system-structure read to consult before a cross-service refactor.+- **Web**, the **architecture score** appears as a stat on both the Conformance and System Map pages. The DSM header shows score / propagation cost / core size and tints each service's diagonal cell by its role, so the on-diagonal core block stands out. On the Live System Map, toggle **Core** to highlight the cyclic core, and the inspector shows any selected service's role and visibility profile.---@@ -475,9 +485,9 @@ Conformance and the cycle finder answer *per-relationship* questions (is this edWorkspace init automatically registers MCP servers with Claude Desktop and Claude Code. The MCP server is workspace-aware:-- **Default repo context** — queries go to the primary repo unless you specify otherwise-- **Cross-repo tools** — MCP tools can query across repos and return enriched context with co-change and contract data; `get_blast_radius` answers cross-repo downstream impact (see [Cross-Repo Blast Radius](#cross-repo-blast-radius)); `get_conformance` answers architecture rule violations and dependency cycles (see [Architecture Conformance](#architecture-conformance)); `get_architecture` answers whole-system coupling, the cyclic core, and the architecture score (see [Architecture Metrics](#architecture-metrics))-- **Repo parameter** — most tools accept an optional `repo` parameter to target a specific repo, or `"all"` to query across the workspace+- **Default repo context**, queries go to the primary repo unless you specify otherwise+- **Cross-repo tools**, MCP tools can query across repos and return enriched context with co-change and contract data; `get_blast_radius` answers cross-repo downstream impact (see [Cross-Repo Blast Radius](#cross-repo-blast-radius)); `get_conformance` answers architecture rule violations and dependency cycles (see [Architecture Conformance](#architecture-conformance)); `get_architecture` answers whole-system coupling, the cyclic core, and the architecture score (see [Architecture Metrics](#architecture-metrics))+- **Repo parameter**, most tools accept an optional `repo` parameter to target a specific repo, or `"all"` to query across the workspace---@@ -519,7 +529,7 @@ Add these to your `.gitignore`:.repowise-workspace.yaml```-The workspace config and data are local — they reference absolute paths and contain generated analysis that should be rebuilt per-machine.+The workspace config and data are local, they reference absolute paths and contain generated analysis that should be rebuilt per-machine.---@@ -552,7 +562,7 @@ repowise watch --workspace### How do I re-run just the cross-repo analysis?-Currently, cross-repo analysis runs automatically during `repowise init .` and `repowise update --workspace`. To force a re-run, use `repowise init .` again — it will detect existing indexes and only re-run what's needed.+Currently, cross-repo analysis runs automatically during `repowise init .` and `repowise update --workspace`. To force a re-run, use `repowise init .` again, it will detect existing indexes and only re-run what's needed.### Does the MCP server handle multiple repos?diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex fa49b0e9e..6f9f5db4e 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -14,10 +14,10 @@ For per-package detail (installation, full API reference, all CLI flags, file ma| Package | README | What it covers ||---------|--------|----------------|-| `packages/core` | [`packages/core/README.md`](../packages/core/README.md) | Ingestion, generation, persistence, providers — all key classes with code examples |-| `packages/cli` | [`packages/cli/README.md`](../packages/cli/README.md) | All 10 CLI commands with every flag documented |-| `packages/server` | [`packages/server/README.md`](../packages/server/README.md) | All REST API endpoints, 11 MCP tools, webhook setup, scheduler jobs |-| `packages/web` | [`packages/web/README.md`](../packages/web/README.md) | Every frontend file with purpose — API client, hooks, components, pages |+| `packages/core` | [`packages/core/README.md`](../../packages/core/README.md) | Ingestion, generation, persistence, providers — all key classes with code examples |+| `packages/cli` | [`packages/cli/README.md`](../../packages/cli/README.md) | All 10 CLI commands with every flag documented |+| `packages/server` | [`packages/server/README.md`](../../packages/server/README.md) | All REST API endpoints, 11 MCP tools, webhook setup, scheduler jobs |+| `packages/web` | [`packages/web/README.md`](../../packages/web/README.md) | Every frontend file with purpose — API client, hooks, components, pages |---@@ -1485,7 +1485,7 @@ and the vector store embed (LanceDB or pgvector) can overlap with the next file'## 15. Editor File Generation-See [`docs/EDITOR_FILES.md`](EDITOR_FILES.md) for the complete reference covering+See [`architecture/editor-files.md`](editor-files.md) for the complete reference coveringarchitecture, all data sources, how the marker-merge system works, and how to addsupport for a new editor file (cursor.md, copilot-instructions.md, etc.).diff --git a/docs/architecture/README.md b/docs/architecture/README.mdnew file mode 100644index 000000000..ccbb34707--- /dev/null+++ b/docs/architecture/README.md@@ -0,0 +1,18 @@+# Architecture & Internals++Deep references for how repowise is built. These are for contributors and the+curious; you don't need them to *use* repowise (start with+[the docs index](../README.md) for that).++| Doc | Covers |+|-----|--------|+| [ARCHITECTURE.md](ARCHITECTURE.md) | The single end-to-end system reference: stores, provider abstraction, the init and maintenance pipelines, git intelligence, dead code, decisions, MCP/REST/UI layers, and key design decisions |+| [deep-dives.md](deep-dives.md) | Algorithm-level treatment of the hard parts: dead-code detection, the decision/ADR system, search & vector-store internals, incremental updates & webhooks, the change-cascade algorithm |+| [code-health.md](code-health.md) | The code-health layer as a full vertical slice: pipeline, the 25+ markers, scoring, trends, persistence schema, and extension points |+| [language-support.md](language-support.md) | The language pipeline internals and the step-by-step recipe for adding a new language |+| [graph-algorithms.md](graph-algorithms.md) | The graph algorithms (PageRank, betweenness, Tarjan SCC, Louvain, shortest path) with the math and complexity |+| [chat.md](chat.md) | The Codebase Chat feature: schema, `ChatProvider` protocol, SSE streaming, the agentic loop, and per-provider notes |+| [editor-files.md](editor-files.md) | How `CLAUDE.md` / `AGENTS.md` generation works (no LLM: pure DB + filesystem derivation) and how to add a new editor file |+| [pluggable-storage.md](pluggable-storage.md) | Extension guide for authoring storage / graph / job-store plugins and adding CLI subcommands or MCP tools |++For the design-token and theme tooling, see [../design/](../design/).diff --git a/docs/internals/chat.md b/docs/architecture/chat.mdsimilarity index 100%rename from docs/internals/chat.mdrename to docs/architecture/chat.mddiff --git a/docs/internals/editor-files.md b/docs/architecture/editor-files.mdsimilarity index 100%rename from docs/internals/editor-files.mdrename to docs/architecture/editor-files.mddiff --git a/docs/architecture/implementation-deep-dive.md b/docs/architecture/implementation-deep-dive.mddeleted file mode 100644index 55e34b82b..000000000--- a/docs/architecture/implementation-deep-dive.md+++ /dev/null@@ -1,1181 +0,0 @@-# Repowise Architecture — Complete Guide--This document covers the entire Repowise architecture beyond the graph layer: ingestion, generation, persistence, providers, server, and MCP tools. For graph algorithms specifically, see `graph-algorithms-guide.md`.-------## Table of Contents--1. [The Big Picture](#1-the-big-picture)-2. [Ingestion Pipeline](#2-ingestion-pipeline)-3. [Generation Pipeline](#3-generation-pipeline)-4. [Persistence Layer (Three Stores)](#4-persistence-layer-three-stores)-5. [LLM Provider Abstraction](#5-llm-provider-abstraction)-6. [Rate Limiter](#6-rate-limiter)-7. [Server Layer](#7-server-layer)-8. [MCP Tools](#8-mcp-tools)-9. [Frontend (Web UI)](#9-frontend-web-ui)-------## 1. The Big Picture--Repowise takes a codebase and produces a living wiki — AI-generated documentation that stays current as the code changes.--```-Your Codebase- │- ▼-┌─────────────────────────────────────────────┐-│ INGESTION │-│ FileTraverser → ASTParser → GraphBuilder │-│ GitIndexer → ChangeDetector │-│ DeadCodeAnalyzer │-└──────────────────┬──────────────────────────┘- │ ParsedFiles, Graph, GitMetadata- ▼-┌─────────────────────────────────────────────┐-│ GENERATION │-│ ContextAssembler → Jinja2 Templates │-│ PageGenerator → LLM Provider │-│ JobSystem (checkpoints, resumability) │-└──────────────────┬──────────────────────────┘- │ GeneratedPages- ▼-┌─────────────────────────────────────────────┐-│ PERSISTENCE │-│ SQL Store ─── Full-Text Search (FTS5) │-│ Vector Store (LanceDB / pgvector) │-│ Graph Store (NetworkX → SQL tables) │-└──────────────────┬──────────────────────────┘- │- ┌──────────┼──────────┐- ▼ ▼ ▼- CLI Server MCP Server- (repowise) (FastAPI) (for AI editors)- │- ▼- Web UI- (Next.js 15)-```--**Why this architecture?** Each layer has a single responsibility and a clear boundary:--- **Ingestion** knows about code but nothing about LLMs or databases-- **Generation** knows about LLMs but not about HTTP or the web UI-- **Persistence** knows about storage but not about how data was created-- **Server** knows about HTTP but delegates all logic to core--This means you can swap the LLM provider, change the database, or replace the frontend without touching the core logic.-------## 2. Ingestion Pipeline--The ingestion pipeline turns raw source code into structured data. It has five components that run in sequence.--### 2.1 FileTraverser — "What files exist?"--**The problem:** A repository contains thousands of files, but most are irrelevant — `node_modules/`, compiled binaries, lock files, generated code. You need to find the files worth documenting.--**How it works:**--FileTraverser walks the directory tree and applies three filter layers:--```-All files in repo- │- ▼- Layer 1: Blocked directories- (.git, node_modules, __pycache__, .venv, dist, build, ...)- │- ▼- Layer 2: .gitignore + .repowiseIgnore- (using pathspec library for glob matching)- │- ▼- Layer 3: File-level filters- - Blocked extensions (.pyc, .so, .exe, .wasm)- - Blocked patterns (*.min.js, package-lock.json)- - Generated file detection (checks first 512 bytes for markers like "DO NOT EDIT")- - Size limit (default 500 KB)- │- ▼- Surviving files → FileInfo objects-```--**Language detection** uses a multi-step fallback:--1. Check special filenames first (`Dockerfile` → dockerfile, `Makefile` → makefile)-2. Check extension map (`.py` → python, `.tsx` → typescript, etc.)-3. If extension unknown: check for null bytes (binary → skip)-4. If text: read first 200 chars for shebang (`#!/usr/bin/env python` → python)--**File classification** adds boolean flags to each FileInfo:--| Flag | How it's detected | Example |-|------|------------------|---------|-| `is_test` | `test_` prefix, `_test` suffix, or inside `/tests/` directory | `test_auth.py`, `auth.spec.ts` |-| `is_entry_point` | Filename in known set: `main.py`, `index.ts`, `app.py`, `server.go` | `src/main.py` |-| `is_config` | Language is yaml, toml, json, dockerfile, or makefile | `docker-compose.yml` |-| `is_api_contract` | Language is proto/graphql, or name contains "openapi"/"swagger" | `api.proto`, `openapi.yaml` |--**Why this matters:** These flags drive downstream decisions. Entry points are never flagged as dead code. Test files don't get full wiki pages. Config files skip AST parsing.--### 2.2 ASTParser — "What's inside each file?"--**The problem:** You need to extract functions, classes, imports, and exports from source code in 9+ languages without writing a parser per language.--**The solution: tree-sitter queries.**--Tree-sitter is a parser generator that produces concrete syntax trees for any language. Repowise uses it with a **unified query architecture**:--```-Source code (Python) tree-sitter grammar S-expression query (.scm)-────────────────── + ───────────────────── + ──────────────────────────-def calculate(x): python grammar (function_definition- return x * 2 name: (identifier) @symbol.name- parameters: (parameters) @symbol.params- ) @symbol.def-```--Every language uses the same capture names:-- `@symbol.def` — the full definition node (provides line numbers)-- `@symbol.name` — the name identifier-- `@symbol.params` — parameter list-- `@symbol.modifiers` — decorators, visibility keywords-- `@import.statement` — full import node-- `@import.module` — the module path being imported--**Adding a new language** requires only two things:-1. Write one `.scm` query file in `packages/core/queries/`-2. Add one entry to the `LANGUAGE_CONFIGS` dict--No new Python classes, no language-specific if/elif chains.--**What the parser extracts:**--For each file, the parser produces a `ParsedFile` containing:--```python-ParsedFile-├── symbols: [Symbol] # functions, classes, methods, interfaces, enums-│ ├── name: "calculate"-│ ├── kind: "function"-│ ├── signature: "def calculate(x: int) -> int"-│ ├── visibility: "public" # language-specific rules-│ ├── start_line, end_line # for source extraction-│ ├── docstring: "..."-│ ├── decorators: ["@cache"]-│ ├── is_async: True/False-│ └── parent_name: "Calculator" # if it's a method-├── imports: [Import]-│ ├── module_path: "utils.helpers"-│ ├── imported_names: ["calculate", "Config"]-│ └── is_relative: True/False-├── exports: ["calculate", "Config"]-└── content_hash: SHA-256 of raw bytes-```--**Visibility detection** is language-specific because every language has different conventions:--| Language | Rule | Example |-|----------|------|---------|-| Python | Underscore prefix → private, dunder → public | `_helper` is private, `__init__` is public |-| Go | Uppercase first letter → public | `Calculate` is public, `calculate` is private |-| TypeScript | `private`/`protected` keyword in modifiers | `private _cache` is private |-| Rust | `pub` keyword in modifiers | `pub fn new()` is public |-| Java | `private`/`protected`/`public` keyword | `public void run()` is public |-| C/C++ | All public by default | Everything is public |--**Parent detection** (for methods) also varies:--| Strategy | Languages | How it works |-|----------|-----------|-------------|-| Nesting | Python, TypeScript, Java | Walk up the AST to find enclosing class node |-| Receiver | Go | Extract type from `func (r *Router) Handle()` receiver |-| Impl block | Rust | Find enclosing `impl Router { }` ancestor |--**Special handlers** exist for languages without tree-sitter support:--- **OpenAPI** (YAML/JSON) — extracts HTTP operations and schema definitions-- **Dockerfile** — extracts FROM, ENTRYPOINT, CMD, EXPOSE as symbols-- **Makefile** — extracts targets as functions, `include` as imports--### 2.3 GraphBuilder — "How do files depend on each other?"--See `graph-algorithms-guide.md` for full coverage. The key point: GraphBuilder takes ParsedFiles and resolves their imports into actual file paths, creating a directed dependency graph. The graph is **two-tier**: file nodes for module-level relationships and symbol nodes for fine-grained call relationships, all in the same `networkx.DiGraph`.--**Named binding resolution** (`NamedBinding` in `ingestion/models.py`) happens during `GraphBuilder.build()`. For each import in a `ParsedFile`, the parser's `_extract_import_bindings()` produces `NamedBinding` objects tracking `local_name`, `exported_name`, `source_file`, and `is_module_alias`. These are used to populate `Import.resolved_file` and to build the alias lookup tables that `CallResolver` relies on. Barrel files (`__init__.py`, `index.ts`) are followed one hop during resolution to handle re-exports.--**Call resolution** runs after import graph construction. `CallResolver` (`ingestion/call_resolver.py`) extracts call sites from the tree-sitter parse tree using `_extract_calls()` (per-language `.scm` captures for all 7 languages), then resolves each `CallSite` in three tiers:--| Tier | Confidence | How it resolves |-|------|-----------|-----------------|-| Same-file | 0.95 | Target defined in the same `ParsedFile` |-| Import-scoped | 0.85–0.93 | Target matched via `NamedBinding` from the file's imports; higher confidence for direct named imports vs namespace aliases |-| Global unique | 0.50 | Target name appears exactly once across the whole repo |--Resolved call sites become `CALLS` edges in the graph. Unresolvable call sites are discarded. Each `CALLS` edge stores the confidence score on the edge data. `DEFINES` and `HAS_METHOD` edges are added during `add_file()` when symbol nodes are created.--`file_subgraph()` returns a filtered view of the `DiGraph` containing only `file` and `package` nodes. All file-level metrics (PageRank, betweenness, SCCs, Louvain, in-degree dead code) run on this subgraph to prevent symbol-node cardinality from distorting centrality scores.--After building the static import graph, GraphBuilder also adds **framework-aware synthetic edges** via `add_framework_edges()`. This detects common framework patterns and creates edges for dependencies that static import resolution misses:--- **pytest**: `conftest.py` → test files in the same/child directories-- **Django**: `admin.py` → `models.py`, `urls.py` → `views.py`, `forms.py` → `models.py`, `serializers.py` → `models.py` (same directory)-- **FastAPI**: files with `include_router()` → the router modules they include-- **Flask**: files with `register_blueprint()` → the blueprint modules they register--Framework detection uses the existing `detect_tech_stack()` function (which scans `pyproject.toml`, `package.json`, etc.) to know which frameworks are present.--**Import resolution** is the tricky part — each language has different rules:--```-Python relative: "from .sibling import x" → resolve dots + walk up directories-Python absolute: "from pkg.calc import x" → try pkg/calc.py, pkg/calc/__init__.py-TypeScript: "./utils" → try utils.ts, utils.tsx, utils/index.ts-Go: "github.com/foo/bar" → match last segment "bar" by stem-Generic fallback: stem matching → "calculator" matches calculator.py-```--Alias forms (`import X as Y`, `from X import Y as Z`, Go aliased imports, Rust `use_as_clause`, TS namespace imports) are handled by `_extract_import_bindings()` and stored in separate `module_aliases` tracking so `CallResolver` can look up both the alias and the original name.--### 2.4 GitIndexer — "What's the history of each file?"--**The problem:** Code structure (imports, symbols) is only half the story. You also need to know: who owns this file? How often does it change? Is it a hotspot? What files change together?--**What it extracts per file:**--```-Timeline-├── commit_count_total, commit_count_90d, commit_count_30d-├── first_commit_at, last_commit_at, age_days-└── merge_commit_count_90d--Ownership-├── primary_owner (by git blame — who wrote the most lines)-├── recent_owner (most commits in last 90 days)-├── contributor_count-├── bus_factor (minimum contributors for 80% of commits)-└── top_authors_json (top 5 by commit count)--Churn-├── lines_added_90d, lines_deleted_90d-├── avg_commit_size-├── churn_percentile (rank among all files, 0.0-1.0)-├── is_hotspot (churn_percentile >= 0.75 AND >= 3 commits in 90d AND real line movement)-└── is_stable (> 10 total commits BUT 0 in 90d)--Significant Commits-└── Top 10 commits that matter (filtered)- - Skip: merge commits, bot authors, < 12 chars- - Skip: "Bump version", "chore:", "ci:", "style:" (unless decision signal)- - Decision signals: "migrate", "refactor", "deprecate", "rewrite", etc.-```--**Bus factor** deserves explanation. It answers: "if people leave, when does knowledge become dangerously concentrated?"--```-Example: file with 100 commits- Alice: 60 commits (60%)- Bob: 25 commits (25%)- Carol: 10 commits (10%)- Dave: 5 commits (5%)--Walk from top: Alice alone = 60%. Not 80%. Add Bob: 85%. >= 80%.-Bus factor = 2.--If both Alice AND Bob leave, knowledge drops below 20%.-Bus factor of 1 = single point of failure.-```--**Co-change detection** finds files that change together:--```-Commit 1: [auth.py, config.py, tests/test_auth.py]-Commit 2: [auth.py, config.py]-Commit 3: [auth.py, config.py, middleware.py]--auth.py ↔ config.py: co-changed 3 times → strong signal-auth.py ↔ middleware.py: co-changed 1 time → weak signal-```--Recent co-changes count more than old ones. The score uses exponential decay:--```-score = Σ exp(-age_days / 180)-```--A co-change yesterday contributes ~1.0. A co-change 6 months ago contributes ~0.37. A co-change a year ago contributes ~0.13. This ensures the signal reflects current coupling patterns, not ancient history.--**Why a single git log call?** A naive approach would run `git log` per-file (10,000 files → 10,000 processes). Instead, GitIndexer runs one `git log --name-only` for the whole repo and parses all commits in a single pass. O(1) git processes instead of O(N).--### 2.5 ChangeDetector — "What changed since last run?"--**The problem:** After the initial indexing, you don't want to re-generate documentation for every file. You only want to update what changed.--**How it works:**--```-Step 1: git diff HEAD~1..HEAD → list of changed files--Step 2: For each changed file, parse old and new versions--Step 3: Detect symbol renames- Old file has: calculate(), Config- New file has: compute(), Config- "calculate" removed, "compute" added, same kind (function),- similar line position → likely rename (confidence scored via Levenshtein)--Step 4: Cascade through the graph- auth.py changed- → Who imports auth.py? → [main.py, middleware.py] (1-hop, full regen)- → Who imports those? → [app.py, cli.py] (2-hop, decay only)- → Co-change partners? → [config.py] (co-change, decay)--Step 5: Budget-sort regeneration list- Sort by PageRank (most important first)- Cap at cascade_budget (adaptive: 10 for 1 file, 30 for 2-5, up to 50 max)- Remaining pages → decay their confidence score without regenerating-```--**Why cascade?** If `utils.py` changes, the documentation for `service.py` (which imports `utils.py`) is now potentially wrong — it might reference old function names or behavior. The cascade ensures dependent documentation stays accurate.--**Why budget?** Without a budget, changing a widely-imported file like `config.py` would trigger regeneration of hundreds of pages. The budget ensures a bounded cost per update, with PageRank-based prioritization so the most important pages get refreshed first.-------## 3. Generation Pipeline--The generation pipeline takes ingested data and produces wiki pages using LLMs.--### 3.1 Page Types and Levels--Repowise generates **10 types of pages** in **8 ordered levels**:--```-Level 0: api_contract ← API definitions (OpenAPI, Proto, GraphQL)-Level 1: symbol_spotlight ← Individual important symbols-Level 2: file_page ← Individual code files-Level 3: scc_page ← Circular dependency documentation-Level 4: module_page ← Directory-level summaries-Level 5: cross_package ← Inter-package boundaries (monorepo only)-Level 6: repo_overview ← Repo-wide summary- architecture_diagram ← Mermaid dependency diagram-Level 7: infra_page ← Dockerfiles, Makefiles, Terraform- diff_summary ← Change summaries-```--**Why levels?** Later levels depend on earlier levels. A module_page (level 4) references file_pages (level 2). The repo_overview (level 6) references module_pages (level 4). By generating in order, later pages can include summaries of earlier pages as context for the LLM.--**Within each level**, pages generate concurrently (controlled by a semaphore, default concurrency = 5).--### 3.2 Page Budget — "How many pages should we generate?"--Not every file deserves its own wiki page. The budget controls cost:--```python-budget = max(50, int(total_files * 0.10)) # at most 10% of files, minimum 50-```--The budget is allocated across page types:--```-Fixed overhead (always generated):- + all API contract files- + all SCC cycles (size > 1)- + all modules (top-level directories)- + repo_overview + architecture_diagram--Remaining budget split between:- file_pages: top 10% files by PageRank (capped by remaining)- symbol_spotlights: top 10% public symbols by PageRank (capped by remaining)-```--**Example for a 500-file repo:**--```-Budget = max(50, 500 × 0.10) = 50 pages--Fixed overhead:- 3 API contracts + 2 SCC cycles + 8 modules + 2 overview = 15--Remaining = 50 - 15 = 35- file_pages: top 10% of 500 = 50, capped at 35 → 25 file pages- symbol_spotlights: top 10% of symbols, capped at 10-```--### 3.3 Significant File Selection — "Which files get their own page?"--A file gets a Level 2 page if it passes `_is_significant_file()`:--```-Is it a package __init__.py with symbols? → YES (module interface)-Is it an entry point? → YES-Is its PageRank >= threshold (top percentile)? → YES-Is its betweenness centrality > 0? → YES (bridge file)-Does it have >= 1 symbol? → Required (unless entry point or high PageRank)--Everything else → included only in module-level summaries-```--**Why betweenness overrides PageRank here:** A bridge file might not be widely imported (low PageRank), but it's the only connection between two subsystems. Documenting it helps developers understand the coupling point.--### 3.4 ContextAssembler — "What context does the LLM need?"--Each page type has a corresponding context assembler method that builds a dataclass of everything the LLM needs to know. The context is then rendered into a Jinja2 template to form the user prompt.--**File page context example:**--```-FilePageContext-├── file_path, language-├── symbols (public first, then private)-│ └── Each with: name, kind, signature, docstring, visibility-├── imports, exports-├── dependencies (what I import) + dependents (who imports me)-├── file_source_snippet (raw code, trimmed to token budget)-├── pagerank_score, betweenness_score, community_id-├── git_metadata (ownership, churn, significant commits)-├── co_change_pages (files that change with this one)-├── dead_code_findings (unused symbols in this file)-├── depth: "minimal" | "standard" | "thorough"-├── dependency_summaries (summaries of already-generated pages)-└── rag_context (related pages from vector search)-```--**Token budgeting** ensures context fits the LLM window:--```-Token estimate = len(text) // 4 (rough approximation, no tiktoken dependency)--Budget = 48,000 tokens per page--Allocation priority:-1. File path + language + symbol signatures (always included)-2. Symbol docstrings (if budget allows)-3. Import list (capped at 30) (if budget allows)-4. Source code snippet (remainder of budget)- → If source > 40% of budget → use structural summary instead-```--### 3.5 Generation Depth — "How detailed should docs be?"--Each file gets a depth level that tells the LLM how much detail to produce:--```-"thorough" if:- - File is a hotspot (high churn + high commits)- - OR has > 100 total commits AND > 10 in last 90 days- - OR has >= 8 significant commits- - OR has co-change partners--"minimal" if:- - File is stable (many total commits but none recently)- - AND PageRank < 0.3- - AND commit count < 5--"standard" otherwise-```--**Why?** Hotspot files change often and are touched by many developers — they need comprehensive documentation explaining edge cases, rationale, and usage patterns. Stable low-importance files just need a brief API summary. This saves LLM tokens and keeps the wiki focused.--### 3.6 PageGenerator — "How are pages actually generated?"--The `generate_all()` method orchestrates everything:--```-async def generate_all():-- 1. Compute graph metrics (PageRank, betweenness, communities, SCCs)- 2. Compute page budget and thresholds- 3. For each level 0-7:- a. Build list of (page_id, coroutine) pairs- b. Skip pages already completed (for resumability)- c. Run all coroutines concurrently (semaphore-limited)- d. For each completed page:- - Embed in vector store (for RAG context in later levels)- - Extract summary (for dependency context in later levels)- - Record in checkpoint (for resumability)- 4. Return all generated pages-```--**Each page generation follows the same pattern:**--```-1. Assemble context → ContextAssembler.assemble_*() → dataclass-2. Render template → Jinja2 template → user_prompt string-3. Check cache → SHA256(model + type + prompt) → hit = skip LLM-4. Call LLM → provider.generate(system, user) → markdown response-5. Wrap result → GeneratedPage dataclass-6. Validate output → Cross-check backtick refs against AST symbols-```--**Step 6 (LLM output validation)** extracts all backtick-quoted names from the generated markdown (e.g., `` `calculate` ``, `` `Config` ``) and compares them against actual symbol names, exports, and imports from the ParsedFile. References that don't match any known name are logged as hallucination warnings and stored in `page.metadata["hallucination_warnings"]`. Common keywords and builtins are excluded from checking.--**After `generate_all()` completes**, the `update` command prints a **Generation Report** — a rich table showing pages by type, token counts (input/output/cached), estimated cost, elapsed time, stale page count, and hallucination warning count.--**System prompts are constant per page type.** This is intentional — Anthropic's prompt caching gives ~10% cost reduction when the system prompt is identical across requests. Since all file_pages share the same system prompt, the cache hit rate is high.--### 3.7 Job System — "What if generation crashes halfway?"--Generating documentation for a large repo might take hours and involve hundreds of LLM calls. If the process crashes at page 150 of 300, you don't want to start over.--**How it works:**--```-Checkpoint file: .repowise/jobs/{job_id}.json--{- "status": "running",- "total_pages": 300,- "completed_pages": 150,- "completed_page_ids": ["file_page:src/auth.py", "file_page:src/api.py", ...],- "failed_page_ids": ["file_page:src/broken.py"],- "current_level": 2-}-```--State machine:--```-pending → running → completed- ↓- failed- ↓- paused → running (resume)-```--On resume, `generate_all()` reads `completed_page_ids` and skips those pages. Generation continues from where it left off.--**Why checkpoint per page (not per level)?** A level might have 200 pages. Crashing at page 199 and restarting from page 1 of that level wastes 198 LLM calls. Per-page checkpointing means at most 1 wasted call on crash.--### 3.8 Freshness and Confidence Decay--Pages go stale as code changes. Repowise tracks this:--```-confidence = 1.0 at generation time- → decays linearly to 0.0 over expiry_threshold_days (default 30)--freshness_status:- "fresh" → source hash matches AND age < staleness_threshold (7 days)- "stale" → source hash changed OR age >= 7 days (but < 30)- "expired" → age >= 30 days (always regenerate)-```--**Source hash = SHA256(user_prompt).** If the code changes, the assembled context changes, the rendered template changes, and the hash changes. This detects staleness even without checking git — if the inputs to the LLM would be different, the page is stale.--### 3.9 RAG Integration — "Can pages reference each other?"--When generating a file_page, the system queries the vector store for related pages:--```-Query terms = file's exports or top 3 public symbol names-Results = top 3 semantically similar pages (excluding self)-Injected into ctx.rag_context as snippets-```--**Why?** If `service.py` imports `repository.py`, and we already generated a page for `repository.py`, the LLM documenting `service.py` can reference the repository documentation for accurate cross-references.--### 3.10 Editor File Generation (CLAUDE.md)--Repowise generates `CLAUDE.md` files for AI coding assistants. These are NOT LLM-generated — they're assembled from structured data:--```-CLAUDE.md contains:- - Architecture summary (from repo_overview page)- - Key modules table (sorted by PageRank)- - Entry points list- - Tech stack (categorized by type)- - Hotspot files table (high churn)- - Repowise MCP tools (recommended workflow)- - Build commands (from project config)-```--**Marker-based merge** preserves user customizations:--```markdown-# CLAUDE.md-<!-- Your custom instructions here — Repowise never touches this -->--Your hand-written notes, conventions, team rules...--<!-- REPOWISE:START — Do not edit below this line. Auto-generated by Repowise. -->-[Auto-generated content updated on each run]-<!-- REPOWISE:END -->-```--On update: only content between markers is replaced. Everything above/outside is preserved.-------## 4. Persistence Layer (Three Stores)--Repowise uses three independent storage systems because each answers a fundamentally different type of question.--### 4.1 SQL Store — "What exists?"--**Tech:** SQLAlchemy 2.0 + SQLite (default) or PostgreSQL--**What it stores:**--| Table | Contents | Key |-|-------|----------|-----|-| `repositories` | Registered repos (name, path, branch, sync state) | `local_path` |-| `wiki_pages` | Generated documentation | `page_id = "{type}:{path}"` |-| `wiki_page_versions` | Historical snapshots of pages | auto-incremented |-| `graph_nodes` | File nodes with computed metrics | `(repo_id, node_id)` |-| `graph_edges` | Import dependencies between nodes | `(repo_id, source, target)` |-| `wiki_symbols` | Functions, classes, methods | `(repo_id, symbol_id)` |-| `git_metadata` | Per-file ownership, churn, co-changes | `(repo_id, file_path)` |-| `generation_jobs` | Job status and progress | UUID |-| `dead_code_findings` | Unreachable files, unused exports | UUID |-| `decision_records` | Architectural Decision Records (ADRs) | composite natural key |--**Page versioning:**--```-First upsert → insert page, version=1, no PageVersion created-Second upsert → archive old content as PageVersion, increment to version=2-Third upsert → archive again, increment to version=3-```--This means: version 1 is the current content (in `wiki_pages`), older versions are in `wiki_page_versions`. You get history without doubling storage on the first write.--**Why natural keys?** Page IDs are `"{page_type}:{target_path}"` (e.g., `"file_page:src/auth.py"`). This means you can upsert a page knowing only its type and path — no need to query the database for an auto-generated ID first. Same for repositories (keyed by `local_path`) and decisions (keyed by title + source + evidence_file).--### 4.2 Full-Text Search — "Which pages mention X?"--**Two backends** (auto-detected from database dialect):--| Backend | Technology | How it works |-|---------|-----------|-------------|-| SQLite | FTS5 virtual table | `page_fts(page_id, title, content)` with BM25-like ranking |-| PostgreSQL | GIN index + tsvector | `to_tsvector('english', title || content)` with ts_rank |--**Query processing:**-1. Strip English stop words ("the", "is", "at", etc.)-2. Join remaining terms with OR (broad recall)-3. Support prefix matching: `"pay*"` matches "payment", "payload"--**Why a separate search index?** SQL LIKE queries don't rank results by relevance and are slow on large text columns. FTS5/tsvector indexes are optimized for text search and return results ranked by relevance.--### 4.3 Vector Store — "What's semantically similar to X?"--**Three implementations** (chosen at startup based on config):--| Implementation | Storage | Use case |-|---------------|---------|----------|-| InMemoryVectorStore | Python dict | Tests, tiny repos |-| LanceDBVectorStore | Local files (`.repowise/lancedb/`) | Default for production |-| PgVectorStore | PostgreSQL pgvector extension | When using PostgreSQL |--**How it works:**--```-1. Text → Embedder → float vector (e.g., 1536 dimensions)-2. Vector stored alongside page_id and metadata-3. Search: query text → embed → find nearest vectors by cosine similarity-4. Return top-k most similar pages-```--**All vectors are L2-normalized** (unit length). This means cosine similarity = dot product, which is cheaper to compute.--**Embedder options:**-- MockEmbedder: SHA-256 → 8-dim vector (deterministic, no API calls)-- OpenAI: `text-embedding-3-small` (1536 dims)-- Gemini: configurable dimensions--**Why a vector store alongside FTS?** FTS matches keywords — it finds "authentication" when you search "authentication." Vector search matches meaning — it finds "login flow" and "credential validation" when you search "authentication" because those concepts are semantically close in embedding space. Both are useful; Repowise tries vector search first and falls back to FTS.--### How the three stores work together--```-Page Generation:- LLM produces markdown- → SQL: upsert_page(page_id, content, metadata)- → FTS: index(page_id, title, content)- → Vector: embed_and_upsert(page_id, content, metadata)--Search query "how does auth work?":- → Vector store: top 5 semantically similar pages- → FTS fallback: keyword match if vector search fails- → SQL: fetch full page content for results--Graph query:- → SQL: read GraphNode/GraphEdge rows- → Reconstruct NetworkX graph for algorithms- → Return computed paths, neighborhoods, metrics-```-------## 5. LLM Provider Abstraction--Repowise supports 6 LLM providers behind a single interface.--### The interface--```python-class BaseProvider:- async def generate(system_prompt, user_prompt, max_tokens, temperature) → GeneratedResponse- provider_name → str # "anthropic", "openai", etc.- model_name → str # "claude-sonnet-4-6", "gpt-4o", etc.--GeneratedResponse:- content: str # markdown output- input_tokens: int- output_tokens: int- cached_tokens: int # Anthropic prompt cache hits-```--**Why an abstraction?** You might want to use Claude for production documentation but Ollama for local development. Or switch from OpenAI to Gemini when pricing changes. The abstraction means the generation pipeline doesn't care which LLM it's talking to.--### Provider implementations--| Provider | Key Feature | Default Model |-|----------|------------|---------------|-| **Anthropic** | Prompt caching (~10% cost savings), retry with backoff | claude-sonnet-4-6 |-| **OpenAI** | OpenAI-compatible endpoint support (works with proxies) | gpt-5.4-nano |-| **Gemini** | Runs sync SDK in thread pool (async wrapper) | gemini-3.1-flash-lite |-| **Ollama** | Local inference, no API key, air-gap compatible | configurable |-| **LiteLLM** | 100+ LLMs via unified API (Groq, Together, Azure, etc.) | configurable |-| **Mock** | Deterministic responses for testing | — |--### Provider Registry--```python-provider = get_provider("anthropic", api_key="sk-...", model="claude-sonnet-4-6")-# Automatically attaches a RateLimiter with Anthropic defaults (50 RPM, 100k TPM)-```--The registry uses **lazy imports** — `pip install repowise-core` works without installing the Anthropic or OpenAI SDK. The SDK is only imported when you actually request that provider.--### Prompt caching (Anthropic)--Anthropic caches the system prompt server-side. Since all file_pages share the same system prompt, subsequent requests within a session use the cached version at reduced token cost. Repowise exploits this by keeping system prompts constant per page type.-------## 6. Rate Limiter--LLM APIs have rate limits (e.g., Anthropic allows 50 requests/minute). The rate limiter prevents 429 errors.--### How it works--A **sliding-window** approach tracking both requests per minute (RPM) and tokens per minute (TPM):--```-┌─── 60-second window ──────────────────────────────┐-│ req req req req req ...... req [new req?] │-│ ↑ recorded timestamps │-└───────────────────────────────────────────────────┘--Can I make a new request?- 1. Prune timestamps older than 60 seconds- 2. Count remaining: if < RPM limit → RPM OK- 3. Sum tokens in window: if + estimated < TPM limit → TPM OK- 4. Both OK → proceed. Otherwise → sleep until a slot opens.-```--**Why sleep outside the lock?**--```python-async with self._lock:- # Check limits- if not ok:- sleep_time = calculate_wait()-# Release lock THEN sleep-await asyncio.sleep(sleep_time)-```--If we held the lock during sleep, all other coroutines would block waiting for the lock. By releasing before sleeping, other coroutines can check their own limits independently. This prevents thundering herd — multiple coroutines don't all wake up at the same instant.--### Default limits per provider--| Provider | RPM | TPM |-|----------|-----|-----|-| Anthropic | 50 | 100,000 |-| OpenAI | 60 | 150,000 |-| Gemini | 60 | 1,000,000 |-| Ollama | 1,000 | 10,000,000 |--Ollama limits are essentially unlimited (local inference). Gemini's TPM is high because token counting is more generous.--### Retry on 429--If the API returns 429 despite rate limiting (e.g., shared quota), exponential backoff kicks in:--```-Attempt 1: wait 2^1 + jitter = ~2.5 seconds-Attempt 2: wait 2^2 + jitter = ~4.7 seconds-Attempt 3: wait 2^3 + jitter = ~8.3 seconds-Max: 64 seconds-```-------## 7. Server Layer--### 7.1 FastAPI App--The server is a FastAPI application created via `create_app()` factory pattern.--**Startup (lifespan manager):**-1. Initialize SQLAlchemy async engine + session factory-2. Create FTS index (idempotent)-3. Build embedder from environment (REPOWISE_EMBEDDER → mock/gemini/openai)-4. Create vector store (InMemory or LanceDB)-5. Start APScheduler background jobs-6. Bridge state to MCP server (shared DB + stores)--**12 router groups:**--| Router | Path | Purpose |-|--------|------|---------|-| health | `/health` | Liveness check |-| repos | `/api/repos` | CRUD repositories |-| pages | `/api/pages` | Wiki pages + versioning + regeneration |-| search | `/api/search` | Full-text + semantic search |-| jobs | `/api/jobs` | Job status + SSE progress stream |-| symbols | `/api/symbols` | Symbol index lookup |-| graph | `/api/graph` | Dependency graph export + pathfinding |-| git | `/api/repos/{id}/git-*` | Hotspots, ownership, git summary |-| dead_code | `/api/dead-code` | Dead code findings |-| decisions | `/api/repos/{id}/decisions` | Architectural decision records |-| webhooks | `/api/webhooks` | GitHub + GitLab push handlers |-| chat | `/api/repos/{id}/chat` | Agentic chat with tool use |--### 7.2 Webhooks — Incremental Updates--When code is pushed to GitHub/GitLab, a webhook triggers incremental documentation updates:--```-GitHub push event- │- ▼- Verify HMAC-SHA256 signature- │- ▼- Store WebhookEvent in DB- │- ▼- Find matching Repository by URL- │- ▼- Create GenerationJob:- mode: "incremental"- config: {before: "abc123", after: "def456"}- │- ▼- Background worker picks up job:- 1. git diff before..after → changed files- 2. Re-parse changed files- 3. ChangeDetector cascades through graph- 4. Regenerate affected pages (budget-limited)- 5. Update SQL + FTS + Vector stores-```--### 7.3 Scheduler--Two recurring background jobs (APScheduler):--| Job | Interval | Purpose |-|-----|----------|---------|-| Staleness checker | 15 min | Find stale/expired pages across all repos |-| Polling fallback | 15 min | Compare stored HEAD commit vs actual git HEAD (catches missed webhooks) |--### 7.4 Doctor and Three-Store Repair--`repowise doctor` runs health checks: git repo, `.repowise/` dir, database, state.json, providers, stale pages, and **three-store consistency** (SQL vs vector store vs FTS index).--With `--repair`, it fixes detected mismatches:-- Re-embeds pages missing from the vector store-- Re-indexes pages missing from the FTS index-- Deletes orphaned entries from vector store and FTS that no longer exist in SQL--This is powered by `list_page_ids()` on vector stores and `list_indexed_ids()` on FullTextSearch — methods that return the set of page IDs each store knows about, enabling set-difference consistency checks.--### 7.5 Chat — Agentic Loop--The chat endpoint runs an agentic loop where the LLM can call Repowise tools:--```-User: "How does auth work in this codebase?"- │- ▼- LLM receives: system prompt (with repo context) + 10 tool schemas- │- ▼- Iteration 1: LLM calls search_codebase("authentication")- → Returns 5 relevant pages- │- ▼- Iteration 2: LLM calls get_context(["src/auth/login.py"])- → Returns docs + ownership + decisions- │- ▼- Iteration 3: LLM synthesizes answer- → Streams text response to user- │- ▼- Save conversation to DB (for continuity)-```--Max 10 iterations per request. Streamed via SSE (Server-Sent Events).-------## 8. MCP Tools--MCP (Model Context Protocol) lets AI coding assistants (Claude Code, Cursor, Windsurf, Cline) call Repowise tools directly. There are 13 tools (10 single-repo + 3 workspace-only), each answering a specific question. The most commonly used single-repo tools are described below.--### Tool 1: `get_overview` — "What is this codebase?"--**When to use:** First time exploring an unfamiliar repo.--**Returns:** Architecture summary, module map, entry points, and git health metrics (hotspot count, average bus factor, churn trend).--**Git health computation:**--```-churn_trend:- recent_rate = total_commits_30d / 30 days- baseline_rate = (total_commits_90d - total_commits_30d) / 60 days-- recent_rate > baseline × 1.3 → "increasing" (accelerating development)- recent_rate < baseline × 0.7 → "decreasing" (cooling down)- otherwise → "stable"-```--### Tool 2: `get_context` — "What does this code do?"--**When to use:** Before modifying a file, to understand its documentation, ownership, and governing decisions.--**Target resolution** (4-phase fallback):--```-Input: "auth.py"- 1. Try exact: file_page:auth.py → found? return- 2. Try module: target_path = auth.py → found? return- 3. Try symbol: ILIKE '%auth.py%' → found? return- 4. Try file: target_path = auth.py → found? return- 5. Fallback: check GitMetadata exists → suggest fuzzy matches-```--**Returns:** Documentation, symbol list, importers, ownership (primary + recent owner), last change, governing decisions, freshness score.--### Tool 3: `get_risk` — "Will changing this break anything?"--**When to use:** Before a refactor, to assess blast radius.--**Risk type classification:**--```-bug-prone: >= 40% of commits match (fix|bug|patch|hotfix|revert|crash|error)-churn-heavy: churn_percentile >= 0.7-bus-factor-risk: bus_factor == 1 AND total_commits > 20-high-coupling: dependents >= 5-stable: none of the above-```--**Impact surface** — BFS up 2 hops through reverse dependencies, ranked by PageRank:--```-auth.py changed- → middleware.py imports auth.py (PageRank 0.05)- → main.py imports middleware.py (PageRank 0.08, entry point)- → app.py imports main.py (PageRank 0.12)--Impact surface: [app.py, main.py, middleware.py] (top 3 by criticality)-```--### Tool 4: `get_why` — "Why was this built this way?"--**When to use:** When you find surprising code and need to understand the rationale.--**Four modes:**--| Mode | Trigger | Returns |-|------|---------|---------|-| Health dashboard | No query, no targets | Decision counts, stale decisions, ungoverned hotspots |-| Path analysis | Target provided | Decisions governing that file + origin story + alignment score |-| Semantic search | Query provided | Decisions matching the query semantically |-| Target-aware search | Both | Decisions matching query that also govern targets |--**Origin story** — reconstructs the history of a file:--```-Who created it? → first commit author-Who maintains it now? → primary owner by blame-Key decisions? → commits with "migrate", "refactor", "deprecate" matched to ADRs-Alignment? → "high" if active decisions exist and siblings are similarly governed-```--### Tool 5: `search_codebase` — "Where is X implemented?"--**When to use:** Looking for specific functionality across the codebase.--**Search strategy:**--```-1. Wait for vector store ready (background async loading, up to 30s)-2. Semantic search (embedding similarity)- → Fetch 3× limit (for filtering headroom)- → 8-second timeout-3. Fallback to FTS if semantic fails-4. Boost recently-modified files:- - Modified in last 30 days: +1.0× to relevance- - Modified in last 90 days: +0.5×-5. Normalize confidence relative to top result-```--### Tool 6: `get_dependency_path` — "How does A connect to B?"--**When to use:** Understanding how two seemingly unrelated files are connected.--**When a path exists:** Returns the chain of imports (BFS shortest path).--**When no path exists:** Returns rich diagnostic context:--```-visual_context:- reverse_path: Does B → A exist? (dependency flows the other way)- common_ancestors: Nodes reachable from both A and B (via undirected BFS)- shared_neighbors: Files that both A and B directly connect to- community_analysis: Are A and B in the same community?- bridge_suggestions: High-PageRank files connecting both communities--co_change_signal: If no import link but frequent co-changes → logical coupling-```--### Tool 7: `get_dead_code` — "What can we safely delete?"--**When to use:** Cleanup sprints, reducing maintenance burden.--**Findings organized in three tiers:**--| Tier | Confidence | Meaning |-|------|-----------|---------|-| High | >= 0.8 | Almost certainly dead. No importers, no recent commits, old. |-| Medium | 0.5 - 0.8 | Probably dead. No importers but has some recent activity. |-| Low | < 0.5 | Suspicious. Might be dynamically loaded or framework-used. |--**Supports rollup by directory or owner** — so you can say "show me all dead code owned by Alice in the payments/ directory."-------## 9. Frontend (Web UI)--### Tech Stack--```-Next.js 15 + React 19 + TypeScript-Tailwind CSS v4 + Radix UI primitives-SWR (data fetching) + SSE (live job progress)-React Flow (graph visualization) + ELK.js (hierarchical layout)-Shiki (syntax highlighting) + next-mdx-remote (wiki rendering)-Recharts (charts) + Mermaid (diagrams)-Framer Motion (animations)-```--### Pages--| Route | Purpose |-|-------|---------|-| `/` | Dashboard — repo list, recent jobs, aggregate stats |-| `/repos/[id]` | Repository overview |-| `/repos/[id]/wiki/[...slug]` | Wiki page viewer (MDX with Mermaid + syntax highlighting) |-| `/repos/[id]/graph` | Interactive dependency graph (5 view modes) |-| `/repos/[id]/search` | Full-text and semantic search |-| `/repos/[id]/symbols` | Symbol index (sortable, filterable table) |-| `/repos/[id]/coverage` | Documentation freshness dashboard |-| `/repos/[id]/ownership` | Code ownership breakdown |-| `/repos/[id]/hotspots` | High-churn files |-| `/repos/[id]/dead-code` | Dead code findings with bulk actions |-| `/repos/[id]/decisions` | Architectural decision records |-| `/settings` | Global and per-repo settings |--### Graph Visualization--**5 view modes:**--| Mode | What it shows | Layout |-|------|-------------|--------|-| Module | Directory-level nodes (click to drill down) | ELK hierarchical |-| Full | File-level dependency graph | ELK hierarchical |-| Architecture | Entry points + 3-hop reachability | ELK hierarchical |-| Dead code | Unreachable nodes highlighted | ELK hierarchical |-| Hot files | High-churn files + their dependencies | ELK hierarchical |--**ELK.js** (Eclipse Layout Kernel) is used instead of force-directed layout because dependency graphs are DAGs — they have a natural top-to-bottom flow. ELK's layered algorithm respects this directionality, producing clean hierarchical layouts instead of the tangled hairballs that force-directed layouts create for DAGs.--**Interactive features:**-- **Drill-down**: In module view, click a module to expand into sub-modules-- **Path finder**: Select two nodes, find the shortest dependency path-- **Context menu**: Right-click for view docs, explore, set as path endpoint-- **Color modes**: By language, PageRank, or community-- **Ego sidebar**: Click a node to see its stats, git metadata, and connections-- **MiniMap**: Color-coded by doc coverage or importance-------## Putting It All Together--Here's the complete flow from `repowise init` to serving documentation:--```-repowise init ./my-project- │- ▼- FileTraverser: walk directory, apply filters- → 500 files discovered- │- ▼- ASTParser: tree-sitter queries per file- → 500 ParsedFiles with 3,000 symbols and 2,000 imports- │- ▼- GraphBuilder: resolve imports, build directed graph- → 500 nodes, 2,000 edges- → Compute: PageRank, betweenness, SCCs, communities- │- ▼- GitIndexer: mine commit history- → Ownership, churn, bus factor, co-changes per file- │- ▼- DeadCodeAnalyzer: graph reachability from entry points- → 15 unreachable files, 30 unused exports- │- ▼- PageGenerator.generate_all():- → Level 0: 3 API contracts- → Level 1: 10 symbol spotlights- → Level 2: 25 file pages- → Level 3: 2 SCC cycle pages- → Level 4: 8 module pages- → Level 5: 3 cross-package pages- → Level 6: repo overview + architecture diagram- → Level 7: 2 infra pages- Total: 55 pages generated via LLM- │- ▼- Persistence:- → SQL: 55 pages + 500 graph nodes + 2,000 edges + 500 git metadata rows- → FTS: 55 pages indexed for keyword search- → Vector: 55 pages embedded for semantic search- → Graph: metrics stored in graph_nodes table- │- ▼- CLAUDE.md: generated with architecture summary, module map, hotspots- │- ▼- Ready to serve:- → repowise serve → REST API + Web UI at http://localhost:8877- → repowise mcp → MCP server for Claude Code / Cursor / Cline- → repowise search → CLI search across documentation- → repowise update → Incremental sync after code changes-```diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdnew file mode 100644index 000000000..b7af8b842--- /dev/null+++ b/docs/architecture/language-support.md@@ -0,0 +1,379 @@+# Language Support: Architecture & Internals++How the language pipeline is built, and how to add a new language. For the+user-facing "what works today" matrix, see+[docs/LANGUAGE_SUPPORT.md](../LANGUAGE_SUPPORT.md).++The pipeline is fully modular. Language identity data lives in a centralised+`LanguageRegistry`; per-language extraction logic lives in `extractors/`;+per-language import resolution lives in `resolvers/`. Adding a language means+dropping one file into each relevant subpackage and registering it in that+subpackage's dispatcher, with **zero changes** to `parser.py`, `graph.py`,+`traverser.py`, or any analysis core file.++---++## How the pipeline processes a file++```+File discovered by FileTraverser+ |+ v+Extension/filename -> LanguageTag (via LanguageRegistry)+ |+ +-- Config/data language? -> empty ParsedFile (passthrough)+ +-- Special format? -> special_handlers.py (OpenAPI/Dockerfile/Makefile/SQL)+ +-- Has grammar? -> tree-sitter AST parsing+ |+ v+ .scm query extracts:+ @symbol.def / @symbol.name -> Symbol nodes+ @import.statement / @import.module -> Import edges+ @call.target / @call.receiver -> Call edges+ |+ v+ Per-language extractors:+ - Named bindings (import name -> source symbol)+ - Heritage (extends/implements/traits)+ - Docstrings (Python, JSDoc, GoDoc, Rustdoc, Javadoc)+ - Visibility (public/private/protected)+ |+ v+ GraphBuilder resolves imports:+ Python: dotted module paths via a source-root-aware module index+ (src/ + monorepo packages/*/src + PEP 420 namespace+ packages), __init__.py re-export barrels, stem fallback+ TS/JS: relative paths, tsconfig aliases, workspace exports,+ `export ... from` re-export barrels, node_modules+ Go: go.mod module path stripping+ Rust: crate::/self::/super::, mod.rs probing+ C/C++: compile_commands.json include directories+ Dart: package:/dart:/relative URIs via the pubspec name map ++ library-name index (dotted part-of)+ Lightweight tier (Elixir/Clojure/Haskell/Lean 4/Erlang/F#):+ regex-extracted imports vs a declared-module-name index+ dbt: ref()/source() vs a per-project model-name index+ Other: stem-map fallback (filename matching)+ |+ v+ Graph analysis:+ PageRank, community detection, dead code, execution flows+```++---++## Module layout++Per-language code lives in dedicated subpackages so adding a language means+dropping a file into each rather than editing monoliths.++```+ingestion/+ languages/ # LanguageRegistry + LanguageSpec (identity data)+ spec.py # LanguageSpec dataclass (the schema)+ registry.py # LanguageRegistry lookup interface + REGISTRY singleton+ specs/ # one module per language, each exporting `SPEC`+ __init__.py # aggregates every SPEC into ordered `ALL_SPECS`+ python.py typescript.py go.py rust.py csharp.py … (44 tags)+ python_modules.py # dotted-module <-> file index (src / monorepo / PEP 420)+ extractors/ # Per-language AST extraction+ visibility.py # symbol visibility (public/private/protected)+ signatures.py # human-readable signature building+ docstrings.py # module + symbol docstring extraction+ bindings/ # import name + alias binding extraction (per-lang)+ __init__.py # extract_import_bindings dispatcher+ python.py ts_js.py go.py rust.py java.py kotlin.py+ ruby.py csharp.py swift.py scala.py php.py cpp.py dart.py+ heritage/ # inheritance/interface/trait extraction (per-lang)+ __init__.py # extract_heritage + HERITAGE_EXTRACTORS dispatcher+ python.py ts_js.py java.py go.py rust.py cpp.py+ kotlin.py ruby.py swift.py csharp.py scala.py php.py dart.py+ resolvers/ # Per-language import resolution+ python.py # dotted imports via module index: __init__.py+ # barrels, src/ + monorepo packages/*/src, namespace pkgs+ typescript.py # multi-ext probe, tsconfig aliases+ go.py # go.mod module path stripping+ rust.py # crate::/self::/super::, mod.rs probing+ cpp.py # compile_commands.json include paths+ kotlin.py # package-to-directory mapping (shared JVM index)+ ruby.py # require/require_relative resolution+ csharp.py / dotnet/ # namespace-based + MSBuild project graph+ swift.py # module import resolution+ scala.py # package-to-directory mapping (shared JVM index)+ php.py # namespace/PSR-4 resolution+ sql.py # dbt ref()/source() lineage+ generic.py # stem-matching fallback+ framework_edges/ # Framework convention edges (one module per framework + base.py)+ # __init__.py re-exports add_framework_edges; iterates FrameworkHandler list+ # django/fastapi/flask/aspnet/rails/laravel/spring/express/go/rust/typo3+ # hono/next_app/quarkus/micronaut/trpc/remix/gtest + pytest_edges+ dynamic_hints/ # Per-language dynamic-edge extractors+ base.py # DynamicHintExtractor + DynamicEdge+ registry.py # HintRegistry+ django.py pytest_hints.py python_imports.py node.py dotnet.py+ spring.py ruby.py php.py scala.py swift.py c.py cpp.py luau.py go.py jvm.py+ parser.py # ASTParser (language-agnostic orchestration)+ graph.py # GraphBuilder (import/call/heritage resolution)++analysis/+ dead_code/ # Dead code detection+ analyzer.py # DeadCodeAnalyzer class + detection passes+ models.py # DeadCodeKind, DeadCodeFindingData, DeadCodeReport+ constants.py # never-flag globs, framework decorators, fixtures+ dynamic_markers.py # per-language source-text dynamic markers+```++The source-of-truth registry is+`ingestion/languages/specs/__init__.py`, which builds `ALL_SPECS`+(order-significant, first-spec-wins extension map) from one `specs/<tag>.py`+module per language. `LanguageSpec`'s `import_support` field+(`"full" | "partial" | "none"`) is the closest formal signal to a "tier";+the tier names in the user-facing doc are a documentation grouping layered on+top of `import_support` plus the presence of binding / heritage / resolver+modules. (The section-header comments inside `specs/__init__.py` predate the+current state and should not be treated as a live tier reference.)++---++## Adding a new language++### Step 1: Add a `LanguageSpec` module++Language identity data lives in `languages/specs/`, **one module per+language**. Create+`packages/core/src/repowise/core/ingestion/languages/specs/mylang.py`+exporting a single `SPEC`:++```python+"""LanguageSpec for mylang."""++from ..spec import LanguageSpec++SPEC = LanguageSpec(+ tag="mylang",+ display_name="MyLang",+ extensions=frozenset({".ml"}),+ grammar_package="tree_sitter_mylang", # PyPI package name+ scm_file="mylang.scm", # query file name+ heritage_node_types=frozenset({"class_declaration"}),+ entry_point_patterns=("main.ml",),+ manifest_files=("mylang.toml",),+ shebang_tokens=("mylang",),+ builtin_calls=frozenset({"print", "len"}), # filter from call graph+ builtin_parents=frozenset({"Object"}), # filter from heritage+ color_hex="#AB47BC",+)+```++Then register it in `languages/specs/__init__.py` by importing the module and+slotting it into the `ALL_SPECS` tuple. **Order matters**: `LanguageRegistry`+builds its extension map first-spec-wins, so place more specific languages+ahead of ones that share an extension (e.g. TypeScript before JavaScript). You+never edit `registry.py` itself.++### Step 2: Add the `LanguageTag`++Add `"mylang"` to the `LanguageTag` Literal type in+`packages/core/src/repowise/core/ingestion/models.py`. (`EXTENSION_TO_LANGUAGE`+and `SPECIAL_FILENAMES` are derived from the registry filtered to these tags,+so this remains a required manual step.)++### Step 3: Write a tree-sitter query file++Create `packages/core/src/repowise/core/ingestion/queries/mylang.scm` using+tree-sitter S-expression syntax. Follow the capture-name conventions:++| Capture | Purpose | Required? |+|---------|---------|-----------|+| `@symbol.def` | Full definition node (line numbers, kind lookup) | Yes |+| `@symbol.name` | Name identifier | Yes |+| `@symbol.params` | Parameter list | No |+| `@symbol.modifiers` | Decorators / visibility modifiers | No |+| `@symbol.receiver` | Go-style method receiver | No |+| `@import.statement` | Full import node | Yes |+| `@import.module` | Module path being imported | Yes |+| `@call.target` | Function/method being called | No (enables call graph) |+| `@call.receiver` | Object the call is made on | No |+| `@call.arguments` | Call arguments | No |++`python.scm` and `typescript.scm` are good starting points.++### Step 4: Add a `LanguageConfig` entry++Add a parser configuration to `LANGUAGE_CONFIGS` in+`packages/core/src/repowise/core/ingestion/language_configs.py` (re-exported+from `parser.py` for back-compat):++```python+"mylang": LanguageConfig(+ symbol_node_types={+ "function_definition": "function",+ "class_definition": "class",+ },+ import_node_types=["import_statement"],+ export_node_types=[],+ visibility_fn=public_by_default, # from extractors.visibility+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_definition"}),+ entry_point_patterns=["main.ml"],+),+```++### Step 5: Add the tree-sitter grammar dependency++Add the grammar package to `pyproject.toml`:++```toml+[project]+dependencies = [+ # ...+ "tree-sitter-mylang>=0.23,<1",+]+```++### Step 6 (optional): Binding extractor++For full-tier support, add an extractor module under+`extractors/bindings/mylang.py` and register it in the+`extract_import_bindings()` dispatcher. Without this, imports are still+resolved but named-binding-level call resolution won't work.++### Step 7 (optional): Heritage extractor++Add a module under `extractors/heritage/mylang.py` and register it in the+`HERITAGE_EXTRACTORS` dict. Without this, inheritance chains won't appear in+the graph.++### Step 8 (optional): Import resolver++If the language has a non-trivial import system, create a resolver in+`resolvers/mylang.py` and register it in the `_RESOLVERS` dict in+`resolvers/__init__.py`. For simple languages, the generic stem-map fallback+(matching by filename) works out of the box.++### Verify++```bash+# Run the parser tests+pytest tests/ -k "mylang or sample_repo" -x++# Index a real project+repowise init /path/to/mylang-project+```++No changes are needed to `traverser.py`, `dead_code.py`, `page_generator.py`,+`cost_estimator.py`, or any other consumer file, they all derive their+language sets from the registry automatically.++---++## Optional language-specific passes++Several pluggable hooks let a language opt into deeper resolution without+touching the shared pipeline files:++- **`graph_warmups.py`**, register a one-time pre-import warmup (e.g. building+ a project index) so its cost shows up as its own phase instead of inflating+ `graph.imports`. Warmups can also set `is_never_flag=True` on file nodes a+ build manifest declares secondary (the dead-code analyzer consults this in+ `_should_never_flag`), so each repo's own build files teach the analyzer what+ to ignore without extending the hardcoded glob list. Used today by+ `_warmup_jvm` to exempt Gradle non-`main` source sets automatically.+- **`type_ref_resolution._STRATEGIES`**, register a strategy that resolves+ parameter-type captures (`@param.type`) to file-level `type_use` edges.+ Drives DI-aware analysis and keeps type-only interfaces off the dead list.+- **`languages/<lang>_member_reads.py`**, emit `reads` edges for property /+ member access. Used today for C# `var x = new T()` locals; the same shape+ applies to any statically-typed language.+- **`extractors/synthetic_symbols.py`**, recognise source-generator attributes+ and emit the symbols the generator would produce at compile time. Used today+ for CommunityToolkit MVVM (`[ObservableProperty]`, `[RelayCommand]`) and JVM+ Lombok / `record` / Kotlin `data class`; the same shape fits Kotlin+ `@Parcelize`, etc.+- **`extractors/visibility.py::refine_<lang>_visibility`**, node-aware+ visibility refinement for languages where access is dictated by AST context+ (C/C++ access specifiers, storage class, export attributes) rather than+ modifier text alone.++The three code-health signal layers are each driven by the same+per-language plugin pattern, registered in a dict exactly like `resolvers/`:++- **`analysis/health/complexity/languages.py`** (`LANGUAGE_MAPS`), the+ code-health complexity walker's per-language node-type map, independent of the+ ingestion `.scm` queries. A map gives McCabe complexity, nesting, cognitive+ complexity, and per-function markers; optional `class_kinds` /+ `self_identifiers` / `member_access_kinds` add class-level metrics (LCOM4,+ god-class), and `assert_kinds` / `assert_call_kinds` add assertion-block+ smells. Ships for the 9 Full languages plus Dart. See `complexity/README.md`.+- **`analysis/health/perf/dialects/`** (`PERF_DIALECTS`), the **performance**+ signal. A `PerfDialect` owns callee extraction (the per-grammar seam), the+ execution-sink lexicon (`sink_kind`), the constant-loop / string-concat /+ async predicates, and its own marker list, so Go contributes `defer_in_loop`,+ Java/Go contribute `regex_compile_in_loop`, C# contributes+ `blocking_sync_in_async`, and the Phase-7a loop markers are opt-in per+ dialect. Every method has a safe "no signal" default.+- **`analysis/health/dataflow/dialects/`** (`DEFUSE_DIALECTS`), the+ **dataflow** layer (intra-procedural CFG + def/use + reaching definitions,+ powering **Extract Method**). A `DefUseDialect` owns the read-vs-write+ classification of each statement and the parameter binders; the CFG builder,+ the reaching-definitions fixpoint, and the Extract Method slicer stay+ language-agnostic (the control-flow grammar they branch on lives on the+ `LanguageNodeMap`). The full pass runs only for functions a structural marker+ already flagged (`large_method` / `brain_method` / `complex_method`), so it+ stays within the health-pass budget.++All tiers are purely additive and degrade to silence: an unmapped language+produces no findings rather than wrong ones.++---++## Workspace contract extraction++In workspace mode (multiple repos indexed together), repowise links+service-to-service API contracts (HTTP routes, gRPC services, and DB tables) so+a provider endpoint in one repo connects to its consumers in another. The+extractors live in `core/workspace/extractors/` and follow the same+dialect-plugin shape: the orchestrator owns only the file walk, and each+framework / client library is an independent module registered in a tuple.++```+workspace/extractors/+ base.py # iter_source_files walk + ScanContext (shared by all)+ langs.py # registry-derived extension sets (JS_TS, PYTHON, RUST, …)+ http/+ dialect.py # HttpDialect protocol + build_provider/consumer_contract+ paths.py # normalize_http_path + URL helpers+ express.py fastapi.py spring.py laravel.py go.py aspnet.py # providers+ js_clients.py python_clients.py csharp_http.py rust_clients.py # consumers+ rust_axum.py mounts.py # providers+ __init__.py # HttpExtractor + PROVIDER_DIALECTS / CONSUMER_DIALECTS+ grpc/+ dialect.py # GrpcDialect protocol + make_grpc_contract+ proto.py go.py java.py python.py typescript.py csharp.py+ __init__.py # GrpcExtractor + DIALECTS+ data/ # table providers (DDL / ORM entities) <-> SQL consumers+```++A dialect declares the file extensions it understands (via `langs.py`) and+turns regex matches into `Contract`s through shared builders, so every dialect+emits identically-shaped providers/consumers and path-normalization lives in+one place. **Adding a framework or client** means dropping one module into+`http/`, `grpc/`, or `data/` and appending its dialect to the relevant registry+tuple, no orchestrator edits.++| Contract | Providers | Consumers |+|----------|-----------|-----------|+| **HTTP** | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal), Rust (Axum routes, Actix/Rocket attribute macros) | `fetch` / `axios` / URL-literal wrappers (JS/TS), `requests` / `httpx` (Python), `HttpClient` / `UnityWebRequest` / Best.HTTP (C#), `reqwest` (Rust) |+| **gRPC** | `.proto` IDL, Go, Java, Python, NestJS (`@GrpcMethod`), C# (gRPC-dotnet) | Go, Java, Python, C# |+| **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, ORM entities (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback) |++See [docs/WORKSPACES.md](../WORKSPACES.md) for the user-facing workspace guide.++---++## See also++- [docs/LANGUAGE_SUPPORT.md](../LANGUAGE_SUPPORT.md), user-facing support matrix+- [docs/CODE_HEALTH.md](../CODE_HEALTH.md), code-health markers and per-language precision hazards+- [architecture/code-health.md](code-health.md), code-health layer internals+- [architecture/ARCHITECTURE.md](ARCHITECTURE.md), full system architecturediff --git a/docs/internals/llm-generation.md b/docs/internals/llm-generation.mddeleted file mode 100644index 85bde0137..000000000--- a/docs/internals/llm-generation.md+++ /dev/null@@ -1,900 +0,0 @@-# LLM Doc Generation — Deep Dive--This document is a precise, code-level description of how repowise builds prompts and calls-LLMs to produce wiki pages. It covers every piece of context that goes into each call,-the exact generation ordering, how scalability is handled, and a frank gap analysis of-where the current implementation diverges from the intended design.--**Validated against:** actual generated output from `interview-coach/.repowise/export/` —-a test run on a 2022-file monorepo (Python + TypeScript) using Gemini, producing 33 pages.-------## Table of Contents--1. [High-Level Pipeline](#1-high-level-pipeline)-2. [Page Types and Generation Levels](#2-page-types-and-generation-levels)-3. [What Context Goes to the LLM — Per Page Type](#3-what-context-goes-to-the-llm--per-page-type)-4. [Token Budget Mechanics](#4-token-budget-mechanics)-5. [Generation Ordering and Significance Filtering](#5-generation-ordering-and-significance-filtering)-6. [Prompt Caching and Provider Layer](#6-prompt-caching-and-provider-layer)-7. [Confidence and Freshness Tracking](#7-confidence-and-freshness-tracking)-8. [Scalability: Small vs. Large Repos](#8-scalability-small-vs-large-repos)-9. [Output Quality: What the LLM Actually Produces](#9-output-quality-what-the-llm-actually-produces)-10. [Gap Analysis — What Is Not Yet Wired Up](#10-gap-analysis--what-is-not-yet-wired-up)-------## 1. High-Level Pipeline--Every wiki page follows the same three-step cycle:--```-ParsedFile + graph metrics + git metadata- │- ▼-ContextAssembler.assemble_*()- │ builds a typed context dataclass- ▼-Jinja2 template rendered → user_prompt string- │- ▼-LLMProvider.generate(system_prompt, user_prompt)- │- ▼-GeneratedPage (markdown content + token counts + confidence=1.0)-```--The key files:--| File | Role |-|------|------|-| `generation/context_assembler.py` | Assembles typed context dataclasses from ingestion output |-| `generation/page_generator.py` | Renders prompts, calls provider, wraps in `GeneratedPage` |-| `generation/models.py` | `GeneratedPage`, `GenerationConfig`, decay math |-| `generation/templates/*.j2` | One Jinja2 template per page type |-------## 2. Page Types and Generation Levels--repowise generates 10 distinct page types in a strict dependency-ordered sequence:--| Level | Page Type | What It Documents | Template |-|-------|-----------|-------------------|----------|-| 0 | `api_contract` | OpenAPI / Protobuf / GraphQL schema files | `api_contract.j2` |-| 1 | `symbol_spotlight` | Top-10% public symbols by PageRank | `symbol_spotlight.j2` |-| 2 | `file_page` | Significant source files | `file_page.j2` |-| 3 | `scc_page` | Circular dependency clusters (len > 1) | `scc_page.j2` |-| 4 | `module_page` | Top-level directories as modules | `module_page.j2` |-| 5 | `cross_package` | Monorepo inter-package boundaries | *(stub — not yet implemented)* |-| 6 | `repo_overview` | Repository-level architecture summary | `repo_overview.j2` |-| 6 | `architecture_diagram` | Mermaid dependency graph | `architecture_diagram.j2` |-| 7 | `infra_page` | Dockerfile, Makefile, Terraform, shell | `infra_page.j2` |-| 7 | `diff_summary` | Git diff summaries (maintenance path) | `diff_summary.j2` |--Within each level, pages run concurrently up to `config.max_concurrency` (default: 5).-A level never starts until all coroutines in the previous level complete or fail.--**Page ID format:** `"{page_type}:{target_path}"` — deterministic, used for resume and-deduplication.-------## 3. What Context Goes to the LLM — Per Page Type--Every LLM call is two parts:-- **System prompt** — a constant string per page type (enables Anthropic prefix caching)-- **User prompt** — rendered Jinja2 template with the assembled context--### 3.1 `file_page` — the most important page type--**System prompt (constant):**-```-You are repowise, an expert technical documentation generator.-Your task is to produce comprehensive, accurate wiki pages from source code.-Output markdown only. Do not include preamble or apologies.-Required sections: ## Overview, ## Public API, ## Dependencies, ## Usage Notes.-```--**User prompt context** (assembled by `ContextAssembler.assemble_file_page()`):--| Context piece | Source | Always included? |-|---------------|--------|-----------------|-| File path | `ParsedFile.file_info.path` | Yes |-| Language | `ParsedFile.file_info.language` | Yes |-| Module docstring | `ParsedFile.docstring` | If present |-| PageRank score | `graph_builder.pagerank()[path]` | Yes |-| Betweenness centrality | `graph_builder.betweenness_centrality()[path]` | Yes |-| Community ID (Louvain cluster) | `graph_builder.community_detection()[path]` | Yes |-| Flags: `is_api_contract`, `is_entry_point`, `is_test` | `ParsedFile.file_info` | Yes |-| Public symbols first (name, kind, signature, docstring, visibility, complexity, decorators, start/end lines) | `ParsedFile.symbols` | Within token budget |-| Private documented symbols | `ParsedFile.symbols` | Within token budget |-| Private undocumented symbols | `ParsedFile.symbols` | Within token budget |-| Import statements (up to 30) | `ParsedFile.imports[].raw_statement` | Within token budget |-| Export names | `ParsedFile.exports` | Yes |-| Dependencies (files this imports, from graph edges) | `graph.successors(path)` | Yes |-| Dependents (files that import this, from graph edges) | `graph.predecessors(path)` | Yes |-| Parse errors | `ParsedFile.parse_errors` | If present |-| Source code snippet | `source_bytes` decoded, trimmed to budget | Within token budget |-| RAG context (related page summaries) | `ctx.rag_context` list | If populated |-| Git: primary owner + % lines | `git_metadata.primary_owner_name` | If git enabled |-| Git: top 3 contributors | `git_metadata.top_authors` | If git enabled |-| Git: significant commit messages (date, author, message) | `git_metadata.significant_commit_messages` | If git enabled |-| Git: total commit count + age in days | `git_metadata.commit_count_total` | If git enabled |-| Git: `is_hotspot` flag | `git_metadata.is_hotspot` | If git enabled |-| Git: `is_stable` flag | `git_metadata.is_stable` | If git enabled |-| Git: co-change partners (files changed together without import link) | `git_metadata.co_change_partners[:3]` | If git enabled |-| Dead code findings (symbol name, reason, confidence, safe_to_delete) | From `DeadCodeAnalyzer` | If dead code enabled |--**Symbol priority order** in the prompt: public → private-with-docstring → private-undocumented.-Each symbol's token cost is measured before adding — the loop stops when budget is exhausted.--**Source code placement:** The source snippet always comes last in the budget calculation.-All other fields are reserved first; the source gets whatever tokens remain.--### 3.2 `symbol_spotlight`--**System prompt:**-```-You are repowise, an expert technical documentation generator.-Write a detailed spotlight page for a single code symbol.-Output markdown only.-Required sections: ## Purpose, ## Signature, ## Parameters, ## Returns, ## Example Usage.-```--**User prompt context:**--| Context piece | Source |-|---------------|--------|-| Symbol name, qualified name, kind | `Symbol` |-| File path | `ParsedFile.file_info.path` |-| `is_async` flag | `Symbol.is_async` |-| Complexity estimate | `Symbol.complexity_estimate` |-| Full signature string | `Symbol.signature` |-| Docstring (if any) | `Symbol.docstring` |-| Decorators | `Symbol.decorators` |-| Callers (files that import the containing module, from graph in-edges) | `graph.predecessors(path)` |--**Note:** Symbol spotlight only gets the signature + docstring — not the actual function body-(source code). There is no per-symbol source extraction.--### 3.3 `module_page`--**System prompt:**-```-You are repowise, an expert technical documentation generator.-Write a module-level overview page summarising all files in the module.-Output markdown only.-Required sections: ## Overview, ## Public API Summary, ## Architecture Notes.-```--**User prompt context:**--| Context piece | Source |-|---------------|--------|-| Module path (top-level directory name) | `Path(file_path).parts[0]` |-| Language | From constituent files |-| Total symbol count | Summed from all `FilePageContext` in the module |-| Public symbol count | Filtered from symbol dicts |-| Entry point files | Files where `is_entry_point == True` |-| Cross-module dependencies | Aggregated `dependencies` minus intra-module edges |-| Cross-module dependents | Aggregated `dependents` minus intra-module edges |-| Mean PageRank of module files | Mean of `pagerank_score` across all file contexts |-| File list | All file paths in the module |-| Team ownership summary | `module_git_summary` (variable injection, see gap §9.3) |--**Important:** The module page gets `FilePageContext` objects (which contain symbol metadata),-but the Jinja2 template only renders the file path list — it does not include the file pages'-actual generated markdown content. The LLM sees which files are in the module but not what-those files do.--### 3.4 `scc_page`--**System prompt:**-```-You are repowise, an expert technical documentation generator.-Document this circular dependency cycle and provide actionable refactoring advice.-Output markdown only.-Required sections: ## Cycle Description, ## Files Involved, ## Why This Exists,-## Refactoring Suggestions.-```--**User prompt context:**--| Context piece | Source |-|---------------|--------|-| SCC ID | `f"scc-{index}"` |-| Cycle description string | `"Circular dependency cycle: A → B → C"` (ordered paths joined) |-| Files in cycle | `sorted(scc)` — path list |-| Total symbol count across all cycle members | Summed from `FilePageContext` list |--**Note:** The SCC page context is very thin — the LLM gets file paths and a total symbol-count but no signatures, no source, and no information about which symbols create the cycle.--### 3.5 `repo_overview`--**System prompt:**-```-You are repowise, an expert technical documentation generator.-Write a high-level repository overview suitable for onboarding new developers.-Output markdown only.-Required sections: ## Project Summary, ## Technology Stack, ## Entry Points, ## Architecture.-```--**User prompt context:**--| Context piece | Source |-|---------------|--------|-| Repo name | `repo_structure.name` |-| Is monorepo | `repo_structure.is_monorepo` |-| Total files | `repo_structure.total_files` |-| Total lines of code | `repo_structure.total_loc` |-| Circular dependency count | SCCs with `len > 1` |-| Package list (name, path, language) | `repo_structure.packages` |-| Language distribution (percent per language) | `repo_structure.root_language_distribution` |-| Entry points | `repo_structure.entry_points` |-| Top 20 files by PageRank (path + score) | Top of `pagerank` dict sorted descending |-| Codebase health signals | `repo_git_summary` (variable injection, see gap §9.3) |--### 3.6 `architecture_diagram`--**System prompt:**-```-You are repowise, an expert technical documentation generator.-Generate an architecture overview with a Mermaid diagram.-You MUST include a fenced mermaid block with graph TD showing key dependencies.-Output markdown only.-```--**User prompt context:**--| Context piece | Source |-|---------------|--------|-| Repo name | Passed directly |-| ALL graph nodes (every non-external file) | `graph.nodes()` filtered |-| ALL graph edges (every dependency) | `graph.edges()` filtered |-| Community → member file mapping | All entries in `community` dict |-| SCC groups (only non-singleton) | `sccs` filtered |--**Warning:** For large repos this dumps every node and edge — a 1,000-file repo produces-a prompt with 1,000 node lines and potentially thousands of edge lines. See gap §9.5.--### 3.7 `api_contract`--**System prompt:**-```-... Document this API contract file for developers integrating with the service.-Required sections: ## Overview, ## Endpoints, ## Schemas, ## Authentication, ## Examples.-```--**User prompt context:** Full raw file content (trimmed to token budget) + function signatures-as endpoints + class names as schemas.--### 3.8 `infra_page`--**System prompt:**-```-... Document this infrastructure file for DevOps and platform engineers.-Required sections: ## Purpose, ## Key Targets/Stages, ## Configuration, ## Operational Notes.-```--**User prompt context:** Full raw file content (trimmed to token budget) + symbol names-(e.g., Makefile targets).--### 3.9 `diff_summary`--**System prompt:**-```-... Summarise the changes between two git refs and their documentation impact.-Required sections: ## Summary, ## Changed Files, ## Symbol Changes, ## Affected Documentation.-```--**User prompt context:** Added/deleted/modified file lists, symbol diffs, affected page IDs,-trigger commit SHA + message + author + diff text (trimmed to 1,000 tokens).-------## 4. Token Budget Mechanics--### Budget constants (from `GenerationConfig` defaults)--| Setting | Default | What it controls |-|---------|---------|-----------------|-| `token_budget` | 8,000 tokens | Maximum context fed to the LLM per call |-| `max_tokens` | 4,096 tokens | Maximum LLM output |-| `temperature` | 0.3 | Low temperature for consistent, factual output |--### Token estimation--repowise uses a rough heuristic: `len(text) // 4` characters-to-tokens. No tiktoken-dependency. This is accurate for English prose (~4 chars/token) but underestimates for-dense code (operators, brackets, identifiers) and overestimates for unicode-heavy code.--### Budget allocation for `file_page` (in order)--```-budget = 8,000 tokens-─────────────────────────────────────────────────────────-Step 1: path + language overhead ~5 tokens (always)-Step 2: public symbol signatures accumulated, stop when budget hit-Step 3: private documented symbol sigs accumulated, stop when budget hit-Step 4: private undocumented symbol sigs accumulated, stop when budget hit-Step 5: import statements (max 30) skipped entirely if over budget-Step 6: source code snippet trimmed to REMAINING tokens-─────────────────────────────────────────────────────────-Git context, dead code, RAG context: added to the dataclass but NOT-included in the budget calculation — they expand the prompt beyond the budget.-```--**Key insight:** The source code is the lowest-priority item in the budget allocation.-For a file with many symbols, the source may be heavily truncated or replaced with-`...[truncated]`.--### Page budget cap--Total page count is capped at `max(50, N_files * max_pages_pct)` where-`max_pages_pct = 0.10`. For a 100-file project: cap = 50 pages. For a 50,000-file-project: cap = 5,000 pages. Fixed-overhead pages (api, scc, module, overview, diagram)-are subtracted from this budget before allocating file pages and symbol spotlights.-File pages get priority over symbol spotlights within the remaining budget.-------## 5. Generation Ordering and Significance Filtering--### Why ordering matters--The generation order is topologically motivated: dependencies are generated before-dependents. This means when a file page is generated, its imported modules' pages-already exist in the vector store — they can theoretically be retrieved as RAG context-for the importing file's generation.--### File page significance filter--Not every code file gets its own `file_page`. A file is significant if ALL of:-- Has at least `file_page_min_symbols` (default: 1) symbols, AND-- Is an entry point, OR in the top PageRank percentile, OR has non-zero betweenness centrality--Files that pass this filter get a generated page. Files that don't still have their-`FilePageContext` assembled (needed for module pages) but no LLM call is made.--**For a 100-file project:** With `file_page_top_percentile = 0.10`, the top ~10 files-by PageRank get pages, plus all entry points and bridge files. In practice, betweenness-centrality > 0 catches most architecturally important files even at low PageRank.--**For a 50,000-file project (tokio-rs scale):** The same logic applies — only the most-central files get individual pages. Low-PageRank leaf files (test helpers, simple data-structures) are documented only at the module level.--### Module grouping--Modules are defined as `Path(file_path).parts[0]` — the top-level directory. A file-at `src/auth/jwt.py` belongs to module `src`. A file at `tests/test_auth.py` belongs-to module `tests`. This is a simple heuristic that works well for standard Python/Go-layouts but less well for deeply nested monorepos.--### Generation depth auto-upgrade--When git metadata is available, `_select_generation_depth()` can upgrade to `"thorough"`:-- `is_hotspot == True`-- > 100 total commits AND > 10 in last 90 days-- >= 8 significant commit messages-- Any co-change partners--Or downgrade to `"minimal"`:-- `is_stable == True` AND PageRank < 0.3 AND < 5 total commits--Note: The `depth` selection is computed but currently not plumbed through to the-template or the `generate_*` calls — the value is returned but unused in `generate_all`.-------## 6. Prompt Caching and Provider Layer--### In-process SHA256 cache--`PageGenerator` maintains an in-memory dict keyed by:-```python-SHA256(f"{model_name}:{page_type}:{user_prompt}")-```--If the same file is enqueued twice (e.g., after a resume), the cached response is-returned without an LLM call. This cache is per-process — it does not persist across-`repowise init` runs.--### Anthropic prefix caching--System prompts are module-level Python constants (not Jinja2 templates). This is-intentional: Anthropic's server-side prefix caching only works when the prefix is-byte-for-byte identical across calls. Using a constant guarantees this.--For a 1,000-file repo with Anthropic, all `file_page` calls share the same system-prompt. The system prompt is billed once; subsequent calls reuse the cached prefix.-Cost reduction on large repos is typically 60–90% on input tokens.--### Batch mode (Anthropic only)--`AnthropicProvider.generate_batch()` submits all requests for a level as a single-Message Batches API request. Cheaper (~50%) than streaming but asynchronous — the-job polls for completion. Enabled by default for `repowise init`. Pass `--no-batch`-for streaming (faster, costlier).-------## 7. Confidence and Freshness Tracking--Every `GeneratedPage` starts with `confidence = 1.0`. Confidence decays over time-and on code changes.--### Time-based decay (`decay_confidence`)--Linear decay from 1.0 to 0.0 over `expiry_threshold_days` (default: 30):-```python-new_confidence = max(0.0, 1.0 - days_since_update / expiry_threshold_days)-```--### Change-driven decay (`compute_confidence_decay_with_git`)--Applied multiplicatively. Base factors:--| Relationship to changed file | Base decay |-|-----------------------------|------------|-| Direct (source file changed) | × 0.85 |-| 1-hop (symbol called/inherited) | × 0.95 |-| 2-hop (looser reference) | × 0.98 |-| Co-change partner (no import link) | × 0.97 |--Git modifiers applied on top:--| Condition | Effect |-|-----------|--------|-| `is_hotspot` + direct | × 0.94 additional |-| `is_hotspot` + 1-hop | × 0.95 additional |-| `is_stable` + direct | × 1.03 additional (slower decay) |-| Commit message contains "rewrite/refactor/migrate" + direct | × 0.71 additional (hard decay) |-| Commit message contains "typo/lint/format" + direct | × 1.12 additional (soft decay) |--### Freshness status thresholds--| `confidence` | Status | UI badge |-|-------------|--------|----------|-| ≥ 0.80 | fresh | green |-| 0.60–0.79 | stale | yellow |-| 0.30–0.59 | outdated | red |-| < 0.30 | unusable | red prominent |-------## 8. Scalability: Small vs. Large Repos--### Small project (100 files)--- Page cap: `max(50, 100 * 0.10) = 50` pages-- All entry points + bridge files get `file_page`-- Top 10% symbols get `symbol_spotlight`-- Likely 1–3 modules (top-level dirs), so 1–3 `module_page` entries-- Full graph fits in memory as NetworkX `DiGraph` in `.repowise/graph.json`-- Full source snippets fit in token budget for most files-- `repowise init` runs in minutes--### React / tokio-rs scale (thousands of files)--- Page cap: `max(50, 5000 * 0.10) = 500` pages for a 5,000-file repo-- Significance filter is critical — only architecturally central files get pages-- Module grouping by top-level dir creates logical package pages-- Graph switches to SQLite-backed `networkit` above 30K nodes-- `concurrent_jobs = 5` prevents runaway API parallelism-- `repowise init` supports `--resume` — checkpoint after every completed page-- Batch mode (Anthropic) makes large-scale init economically practical-- Source snippets for large files will be heavily truncated-------## 9. Output Quality: What the LLM Actually Produces--This section is grounded in the `interview-coach` test run exports. The test run used-`gemini-3.1-flash-lite-preview` via LiteLLM on a 2022-file monorepo, producing 33 pages-in ~17 minutes. `token_budget=8000`, `max_tokens=4096`, `max_concurrency=3`.--### 9.1 File pages — consistently high quality--`supabase_service.py.md`, `node_creators.py.md`, `supabase_client.py.md` all show:-- Correct Overview section that accurately describes the module's purpose-- Accurate Public API section listing all methods/functions with their signatures-- Correct Dependencies (listed as module paths, not wiki summaries — see gap 10.2)-- Non-trivial Usage Notes: the LLM inferred singleton pattern, RLS security implications,- TTS-aware response length constraints, state key requirements — none of which are in- the signature. This comes entirely from reading the source snippet.--**Verdict:** File page quality is excellent. The raw source code in the prompt is doing-most of the work.--### 9.2 Symbol spotlight — good quality from signature alone--`get_user_analyses.md` produces all required sections (Purpose, Signature, Parameters,-Returns, Example Usage) with only the signature and docstring as input. The generated-example is syntactically correct and semantically plausible.--**Verdict:** For well-named symbols with full type signatures, the output is useful-even without the source body (gap 10.8). For complex symbols with no docstring,-quality will degrade.--### 9.3 Module pages — surprisingly good despite thin context--`backend.md` covers a module containing hundreds of files. The context only included-file paths, symbol counts, and dependency paths — no file page content. Yet the output-correctly identifies major sub-systems (Pipecat, resume analyzer, email engine, thita_bot),-architecture patterns (service-oriented, middleware-based auth), and technology choices.--The LLM is doing pure inference from directory structure and file path names. This works-well for descriptively-named codebases. It would produce generic output for a codebase-with opaque naming (e.g. `svc1/`, `lib2/`).--**Verdict:** Module quality is better than the thin context would suggest, but is-entirely dependent on meaningful file and directory naming.--### 9.4 SCC pages — excellent despite minimal context--Both SCC pages reviewed (`scc-69.md`, `scc-1068.md`) produced genuinely useful output:-- `scc-69` correctly inferred the auth→payment→tier data flow cycle and why each link- exists, purely from the three file names-- `scc-1068` correctly identified the `__init__.py` re-export + registration pattern- anti-pattern, noted the deprecated status, and suggested deletion as the primary fix--Both provided concrete, specific refactoring strategies with code examples.--**Verdict:** SCC quality is excellent. The LLM extracts significant signal from file-path names alone. Gap 10.6 (thin context) is technically correct but practically less-impactful than initially assessed.--### 9.5 Repo overview — excellent--`repo.md` correctly identifies the monorepo structure, accurately reports 7 circular-dependencies, names the technology stack (Next.js, Pipecat, Supabase, Manim, Crawl4AI),-and lists real entry points. The architecture section is coherent and accurate.--**Verdict:** Repo overview quality is excellent.--### 9.6 Architecture diagram — good output but fragile approach--`interview-coach.md` contains a clean 7-node Mermaid diagram for a 2022-file repo.-The context passed in lists all 2022 node names and thousands of edges — the raw-prompt must have been massive. The LLM abstracted to high-level components anyway.--**This is coincidentally good, not reliably good.** A different model or a different-run could produce a 2022-node unrenderable Mermaid block. The approach of dumping all-nodes/edges relies on the LLM choosing to abstract, without any guidance to do so.-Gap 10.4 stands.--### 9.7 Job tracking — confirmed broken in production run--From `jobs/6b10db4b-....json` (a failed job):-```json-{- "total_pages": 0,- "completed_pages": 0,- "failed_pages": 5,- "failed_page_ids": ["level-1", "level-2", "level-3", "level-4", "level-6"]-}-```--Two confirmed bugs:-1. `total_pages: 0` and `completed_pages: 0` even though 33 pages exist in `state.json`.- Root cause: `job_system.start_job(job_id, len(all_pages))` is called at the *end* of- `generate_all`, after all generation completes. The counter is set to the final count- post-hoc, never live during generation.-2. `failed_page_ids` contains level names (`"level-1"`) not page IDs. Root cause:- `job_system.fail_page(job_id, f"level-{level}", str(r))` passes the level string- as the page ID. The job log is unactionable for debugging specific failed pages.-------## 10. Gap Analysis — What Is Not Yet Wired Up--The following gaps represent divergence between the intended architecture and the-current code. Severity ratings are informed by the actual output quality observed-in the `interview-coach` test run — where the LLM compensated for some gaps through-inference, and exposed others clearly.-------### 10.1 RAG context is never populated during `file_page` generation (CRITICAL)--**What the architecture says:**-> "RAG context — vector store similarity search using this file's top exported symbols-> as the query. Returns the top 3 most relevant already-generated pages."--**What the code does:**-`ContextAssembler.assemble_file_page()` returns a `FilePageContext` with-`rag_context: list[str] = field(default_factory=list)` — always an empty list.-The vector store is never queried during context assembly. The field is only populated-in `assemble_update_context()` — and there it's used to pass trigger commit info,-not related page summaries.--**Impact:** The most powerful quality driver described in the architecture is not active.-File pages are generated without any knowledge of what their dependencies actually do.--**What needs to happen:** `assemble_file_page()` needs the vector store passed in,-and must call `vector_store.search(query=exported_symbol_names, top_k=3)` to retrieve-related page summaries before building the context.-------### 10.2 Import summaries are missing — dependencies shown as bare paths only (CRITICAL)--**What the architecture says:**-> "Import summaries — for each file this file imports from: the summary of that file's-> already-generated wiki page (if available), or just its public API signatures."--**What the code does:**-`file_page.j2` renders `ctx.dependencies` as a list of file path strings:-```-## Dependencies (files this imports)-- `src/auth/jwt.py`-- `src/db/connection.py`-```--The LLM sees that `jwt.py` is imported but has no idea what `jwt.py` does. The-generation level ordering guarantees that `jwt.py`'s page was already generated — but-that page's content is never retrieved and included.--**Confirmed in output:** `supabase_service.py.md` lists `core.config`, `models.resume_analyzer_models`,-`services.supabase_service` as dependency names — these are module path strings inferred-from import statements. The LLM wrote accurate descriptions of what each dependency does,-but only because it read the source snippet and recognized the import patterns. Without the-source (e.g., for a large chunked file), dependency sections would be empty.--**Impact:** Dependency section quality is fragile — it works when source fits in the budget,-fails for large files. With import summaries, the LLM could document dependencies even when-source is truncated.--**What needs to happen:** After Level 2 completes, each file's generated page content-should be queryable by path. During context assembly, resolved dependency summaries-(or at minimum, their public symbol signatures) should be embedded in the prompt.-------### 10.3 `module_git_summary` and `repo_git_summary` are dead template variables (SIGNIFICANT)--**What the templates do:**-Both `module_page.j2` and `repo_overview.j2` have blocks gated on these variables:-```jinja2-{% if module_git_summary is defined and module_git_summary %}-## Team ownership-...-{% endif %}-```--**What the code does:**-`PageGenerator.generate_module_page()` renders the template as:-```python-user_prompt = self._render("module_page.j2", ctx=ctx)-```--`module_git_summary` is never passed as a kwarg. In Jinja2 with `StrictUndefined`,-accessing an undefined variable raises an error — but the `is defined` check safely-returns False, so the block is silently skipped every time.--**Confirmed in output:** `backend.md` has no ownership section. `repo.md` has no health-signals section (no hotspot count, no top churn files). Both template blocks were silently-skipped on every call.--**Impact:** Module pages never show team ownership. Repo overview pages never show-health signals (hotspot count, stable files, top churn files, oldest file).--**What needs to happen:** Both generators need to query git metadata and pass-`module_git_summary=...` and `repo_git_summary=...` as keyword arguments to `_render()`.-------### 10.4 Architecture diagram dumps ALL nodes and edges regardless of repo size (SIGNIFICANT)--**What the code does:**-`assemble_architecture_diagram()` passes every non-external node and every edge to-the template. For a 1,000-file repo:-```-**Nodes** (1,000 files):-- `src/auth/jwt.py`-- `src/auth/session.py`-... 998 more lines ...--**Edges** (3,500 dependencies):-- `src/app.py` → `src/auth/jwt.py`-... 3,499 more lines ...-```--This produces a prompt that will exceed any reasonable token budget and result in-an unrenderable or truncated Mermaid diagram.--**Observed in test run:** The 2022-file repo produced `interview-coach.md` with a clean-7-node Mermaid diagram. The LLM abstracted the thousands of nodes/edges to high-level-components. This happened despite receiving an enormous context — likely because the-prompt was so large the LLM had no choice but to summarise. The output was good *this-time*, but the approach is fragile: a less capable model, a stricter max_tokens setting,-or a repo with less descriptive paths would produce a broken or unrenderable diagram.--**Impact:** The architecture diagram is fragile at scale. It works by luck with capable-models but has no structural guarantee of producing a useful Mermaid diagram.--**What needs to happen:**-- Filter nodes to top-N by PageRank (e.g., top 50)-- Filter edges to only those connecting the selected nodes-- Collapse communities into single labeled nodes for the Mermaid output-- Provide a separate "module-level" diagram view using `module_page` membership-------### 10.5 Large file chunking is not implemented — only truncation (SIGNIFICANT)--**What the architecture says:**-> "Files over `large_file_threshold_kb` (100KB) are handled differently: extracts-> public symbol signatures only for the top-level context, generates one sub-page per-> major class or function group, synthesizes a file page from the sub-pages."--**What the code does:**-`_trim_to_budget()` truncates source to whatever tokens remain after symbols and-imports. A 150KB file with many symbols may have its source truncated to ~500 tokens-or less. There is no sub-page generation, no chunking strategy, and no synthesis step.--**Impact:** Large files (common in tokio-rs, React internals) get documentation-built from heavily truncated source. The LLM cannot see the lower half of the file.-------### 10.6 SCC context provides no symbol information (LOW — LLM compensates well)--**What the code does:**-`assemble_scc_page()` creates a string `"Circular dependency cycle: A → B → C"`-and a total symbol count. The template renders these two pieces.--**What the architecture says:**-> "Generate each SCC member with reduced context (own source + signatures of cycle-> partners only)"--The SCC page context has no signatures, no source, and no information about which-specific symbols create the cycle (the imports that close the loop).--**Observed in test run:** Despite this, `scc-69.md` and `scc-1068.md` both produced-excellent output. The LLM inferred cycle causes and provided specific, actionable-refactoring advice entirely from file path names. `scc-1068` correctly identified the-`__init__.py` re-export anti-pattern and even recommended deletion since the module-is deprecated — information visible only in the path `deprecated/interview_service_old/`.--**Revised impact:** For descriptively-named codebases, SCC quality is high despite-thin context. For codebases with opaque names (`module_a/`, `handler_v2/`), the-LLM would produce generic advice. Adding the specific cross-imports that close the-cycle would improve reliability across all codebases.-------### 10.7 Cross-package generation is stubbed out for monorepos (SIGNIFICANT)--**What the code does:**-```python-# ---- Level 5: cross_package (only if monorepo) -----if repo_structure.is_monorepo:- log.info("Skipping cross_package generation (Phase 4)")-```--No `cross_package` pages are ever generated. For a monorepo like a React-scale project,-this means there is no documentation of how `@react/core` depends on `@react/scheduler`,-or what the public API boundary between packages is.-------### 10.8 Symbol spotlight lacks source body (MODERATE — degrades for undocumented symbols)--`symbol_spotlight.j2` includes the signature and docstring but not the function body.-For a complex 80-line function with no docstring, the LLM gets only the signature line.-It cannot generate "## Example Usage" or explain implementation details without seeing-the code.--**Observed in test run:** `get_user_analyses.md` produced a correct, usable example.-But `get_user_analyses` has a full type signature with all parameter names and types —-the LLM had enough to infer usage. For internal symbols with opaque signatures and no-docstring, the output would degrade to a near-empty example section.--**What needs to happen:** Extract the source lines between `symbol.start_line` and-`symbol.end_line` from `source_bytes` and include them in the spotlight context.-------### 10.9 Generation depth selection result is unused (MODERATE)--`_select_generation_depth()` computes `"minimal"` / `"standard"` / `"thorough"` based-on git metadata and PageRank, but the return value is never plumbed into `generate_all()`-or any template. All file pages receive identical treatment regardless of depth.--**What needs to happen:** Pass the computed depth to the template as a `ctx.depth`-field and use it to conditionally include/exclude context sections (e.g., skip source-snippet for `"minimal"` pages, include extra analysis instructions for `"thorough"`).-------### 10.10 `_sort_level_files` is defined but never awaited (MINOR)--```python-async def _sort_level_files(self, files, git_meta_map, pagerank) -> list[ParsedFile]:- ...-```--This method is defined but never called in `generate_all()`. Level 2 processes-`code_files` in the order they come from the traverser. Entry points, hotspots, and-high-PageRank files should be generated first to maximize their availability as RAG-context for later files — but this priority sort is never applied.-------### 10.11 Token budget default (8K) doesn't match architecture doc (12K) (MINOR)--`GenerationConfig.token_budget` defaults to `8000`. The architecture document states:-> "Token budget: the total assembled context targets 12K tokens."--The architecture doc also describes a specific priority drop order (git context is the-*last* thing dropped), while the code drops git context first (it's outside the budget-calculation entirely — it's appended unconditionally after the budget loop).--**Observed in test run:** Config snapshot from `jobs/6b10db4b-....json` confirms-`token_budget: 8000` was used in the actual run.-------### 10.12 Job progress tracking is broken (SIGNIFICANT — live UI will show wrong data)--`job_system.start_job(job_id, len(all_pages))` is called at the *end* of `generate_all`,-after all pages have been generated. This means:-- During generation, `total_pages` is always `0` in the DB-- `completed_pages` never increments during generation-- The SSE job stream sent to the web UI shows `0 / 0` pages for the entire run-- If the process crashes mid-run, the job log shows 0 completed even if 400 pages- finished before the crash--**Confirmed in test run:** A failed job (`6b10db4b-....json`) shows-`total_pages: 0, completed_pages: 0` with `failed_pages: 5`, despite `state.json`-recording 33 successfully generated pages from a separate run.--**What needs to happen:** Call `start_job(job_id, estimated_total)` at the *start* of-`generate_all`, before the first level runs. Use the significance filter pre-computation-that already exists to estimate page count before generation begins.-------### 10.13 `failed_page_ids` stores level names, not page IDs (MINOR)--```python-job_system.fail_page(job_id, f"level-{level}", str(r))-```--The second argument is the page ID, but `f"level-{level}"` is passed instead of an-actual page ID. The resulting `failed_page_ids` list contains entries like-`["level-1", "level-2", "level-3"]` — useless for identifying which specific pages-failed or retrying them on resume.--**Confirmed in test run:** `failed_page_ids: ["level-1", "level-2", "level-3", "level-4", "level-6"]`-in the failed job JSON.--**What needs to happen:** When catching exceptions from `asyncio.gather`, extract the-page ID from the coroutine context and pass that instead of the level string.-------## Summary: Gaps by Priority--Severity ratings updated based on actual output from the `interview-coach` test run.--| # | Gap | Severity | Evidence | Effort |-|---|-----|----------|----------|--------|-| 10.1 | RAG context never populated | **Critical** | Always `[]` in code | Medium |-| 10.2 | Import summaries are bare paths | **Critical** | Confirmed in all file pages | Medium |-| 10.3 | `module_git_summary`/`repo_git_summary` dead | **Significant** | Confirmed missing in `backend.md`, `repo.md` | Low |-| 10.4 | Architecture diagram dumps all nodes/edges | **Significant** | Worked by luck in test run; fragile | Medium |-| 10.5 | No large file chunking | **Significant** | Not exercised in test run; logic gap clear | High |-| 10.6 | SCC context has no symbols | **Low** | LLM compensates well from path names alone | Low |-| 10.7 | Cross-package pages stubbed | **Significant** | Hardcoded skip in `generate_all` | High |-| 10.8 | Symbol spotlight lacks source body | **Moderate** | Good output for typed symbols; degrades for untyped | Low |-| 10.9 | Depth selection unused | **Moderate** | `_select_generation_depth` return value discarded | Low |-| 10.10 | `_sort_level_files` never called | **Minor** | Dead async method | Low |-| 10.11 | Budget is 8K not 12K | **Minor** | Confirmed 8K in job snapshot | Low |-| 10.12 | Job progress tracking broken | **Significant** | `total_pages: 0` in live jobs; SSE shows 0/0 | Low |-| 10.13 | `failed_page_ids` stores level names | **Minor** | Confirmed `["level-1","level-2",...]` in job JSON | Low |